1

I met a strange bug. I have worked on it for 2 days, but failed to solve it. So I want to post it here to see if someone can help on this. I found python-iptables(iptc) cannot work with syslog module. Please see the following code. test1() will only send the first 2 log messages. test2 and test3 works properly. I tested this on both ubuntu16.04 and 20.04, python3.6 and python3.8.

import syslog
import iptc # pip install python-iptables
import os
import socket

def log(msg):
    syslog.openlog(ident="xxxxxx")
    syslog.syslog(syslog.LOG_INFO, msg)
    syslog.closelog()

def log2(msg):
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM|socket.SOCK_CLOEXEC)
    sock.connect("/dev/log")
    sock.send(("  xxxxxx: "+msg).encode("utf-8"))
    sock.close()

def add_rule_cmdline():
    os.system("iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT")

def add_rule_iptc():
    table = iptc.Table(iptc.Table.FILTER)
    chain = iptc.Chain(table, "INPUT")
    rule1 = {'target': 'ACCEPT','conntrack': {'ctstate': 'RELATED,ESTABLISHED'}}
    chain.append_rule(iptc.easy.encode_iptc_rule(rule1))
    table.close()

#no test2 received
def test1():  
    log("test0")
    os.system("iptables -F")
    log("test1")
    add_rule_iptc()
    log("test2")

#working
def test2():  
    log("test0")
    os.system("iptables -F")
    log("test1")
    add_rule_cmdline()
    log("test2")

#working
def test3():  
    log2("test0")
    os.system("iptables -F")
    log2("test1")
    add_rule_iptc()
    log2("test2")
VPfB
  • 14,927
  • 6
  • 41
  • 75
Wei Yao
  • 11
  • 2
  • If you replace `log` with `print`, do you get the expected output? BTW, if this is your first SO question, it is very well written! – VPfB May 19 '21 at 09:39
  • Thanks. If I use print() instead it is OK. I read python C source code, libc source code and libiptc source code in order to find out the root cause. But no lucky. I finally have a workaround. But I'm not feeling confortable. So I write it here to see if anybody can help. – Wei Yao May 21 '21 at 03:04
  • I find it interesting, but I'm using nftables and there are no iptables binaries and libraries installed on my Linux system. I cannot run your test program, but here is an idea: If your default policy is DROP, and you flush all rules with `iptables -F` and `syslog` uses UDP packets to port 514 (and not a socket), then the packet will be dropped and nothing will be logged. – VPfB May 21 '21 at 10:43

0 Answers0