|
|
@@ -25,8 +25,6 @@ import struct
|
|
|
|
import sys
|
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import time
|
|
|
|
|
|
|
|
|
|
|
|
from subprocess import Popen, PIPE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
uvscan_regex = re.compile(r"Found:?(?: the| potentially unwanted program| (?:virus|trojan) or variant)? (.+?)(?:\.| (?:virus |trojan )?)", re.MULTILINE)
|
|
|
|
uvscan_regex = re.compile(r"Found:?(?: the| potentially unwanted program| (?:virus|trojan) or variant)? (.+?)(?:\.| (?:virus |trojan )?)", re.MULTILINE)
|
|
|
|
|
|
|
|
|
|
|
@@ -40,10 +38,11 @@ async def uvscan_worker(queue):
|
|
|
|
uvscan, filename, cb = job
|
|
|
|
uvscan, filename, cb = job
|
|
|
|
proc = await asyncio.create_subprocess_exec(uvscan, "--secure", "--mime", "--noboot", "--panalyse", "--manalyse", filename, stdout=asyncio.subprocess.PIPE)
|
|
|
|
proc = await asyncio.create_subprocess_exec(uvscan, "--secure", "--mime", "--noboot", "--panalyse", "--manalyse", filename, stdout=asyncio.subprocess.PIPE)
|
|
|
|
stdout, _ = await proc.communicate()
|
|
|
|
stdout, _ = await proc.communicate()
|
|
|
|
|
|
|
|
os.remove(filename)
|
|
|
|
if proc.returncode == 13:
|
|
|
|
if proc.returncode == 13:
|
|
|
|
match = uvscan_regex.search(stdout.decode())
|
|
|
|
match = uvscan_regex.search(stdout.decode())
|
|
|
|
name = match.group(1) if match else "UNKNOWN"
|
|
|
|
name = match.group(1) if match else "UNKNOWN"
|
|
|
|
result = "stream: {} FOUND".format(name)
|
|
|
|
result = f"stream: {name} FOUND"
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
result = "stream: OK"
|
|
|
|
result = "stream: OK"
|
|
|
|
cb(result)
|
|
|
|
cb(result)
|
|
|
@@ -60,34 +59,32 @@ class AIO(asyncio.Protocol):
|
|
|
|
if not AIO.queue:
|
|
|
|
if not AIO.queue:
|
|
|
|
raise RuntimeError("queue not set")
|
|
|
|
raise RuntimeError("queue not set")
|
|
|
|
self.logger = logging.getLogger(__name__)
|
|
|
|
self.logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
self.tmpfile = None
|
|
|
|
|
|
|
|
|
|
|
|
def _send_response(self, response):
|
|
|
|
def _send_response(self, response):
|
|
|
|
response = response.encode() + AIO.separator
|
|
|
|
response = response.encode() + AIO.separator
|
|
|
|
self.logger.debug("{} sending response: {}".format(self.peer, response))
|
|
|
|
self.logger.debug(f"{self.peer} sending response: {response}")
|
|
|
|
self.transport.write(response)
|
|
|
|
self.transport.write(response)
|
|
|
|
self.transport.close()
|
|
|
|
self.transport.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def connection_made(self, transport):
|
|
|
|
def connection_made(self, transport):
|
|
|
|
self.peer = transport.get_extra_info("peername")
|
|
|
|
self.peer = transport.get_extra_info("peername")
|
|
|
|
self.logger.info("new connection from {}".format(self.peer))
|
|
|
|
self.logger.info(f"new connection from {self.peer}")
|
|
|
|
self.transport = transport
|
|
|
|
self.transport = transport
|
|
|
|
self.request_time = str(time.time())
|
|
|
|
self.request_time = str(time.time())
|
|
|
|
self.buffer = bytearray()
|
|
|
|
self.buffer = bytearray()
|
|
|
|
self.tmpfile = None
|
|
|
|
self.data = bytearray()
|
|
|
|
self.fh = None
|
|
|
|
|
|
|
|
self.fsize = 0
|
|
|
|
|
|
|
|
self.command = None
|
|
|
|
self.command = None
|
|
|
|
self.length = None
|
|
|
|
self.length = None
|
|
|
|
self.all_chunks = False
|
|
|
|
self.all_chunks = False
|
|
|
|
self.completed = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def data_received(self, data):
|
|
|
|
def data_received(self, data):
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
|
|
|
|
nbytes = len(data)
|
|
|
|
if self.all_chunks:
|
|
|
|
if self.all_chunks:
|
|
|
|
self.logger.warning("{} received {} bytes of garbage after last chunk".format(self.peer, len(data)))
|
|
|
|
self.logger.warning(f"{self.peer} received {nbytes} bytes of garbage after last chunk")
|
|
|
|
return
|
|
|
|
return
|
|
|
|
self.logger.debug("{} received {} bytes".format(self.peer, len(data)))
|
|
|
|
self.logger.debug(f"{self.peer} received {nbytes} bytes")
|
|
|
|
self.buffer.extend(data)
|
|
|
|
self.buffer.extend(data)
|
|
|
|
|
|
|
|
|
|
|
|
if not self.command:
|
|
|
|
if not self.command:
|
|
|
@@ -101,7 +98,7 @@ class AIO(asyncio.Protocol):
|
|
|
|
if command != "zINSTREAM":
|
|
|
|
if command != "zINSTREAM":
|
|
|
|
raise RuntimeError("unknown command")
|
|
|
|
raise RuntimeError("unknown command")
|
|
|
|
self.command = command
|
|
|
|
self.command = command
|
|
|
|
self.logger.debug("{} command is {}".format(self.peer, command))
|
|
|
|
self.logger.debug(f"{self.peer} command is {command}")
|
|
|
|
pos += 1
|
|
|
|
pos += 1
|
|
|
|
self.buffer = self.buffer[pos:]
|
|
|
|
self.buffer = self.buffer[pos:]
|
|
|
|
if self.command:
|
|
|
|
if self.command:
|
|
|
@@ -112,74 +109,74 @@ class AIO(asyncio.Protocol):
|
|
|
|
self.length = struct.unpack(">I", self.buffer[0:4])[0]
|
|
|
|
self.length = struct.unpack(">I", self.buffer[0:4])[0]
|
|
|
|
self.buffer = self.buffer[4:]
|
|
|
|
self.buffer = self.buffer[4:]
|
|
|
|
if self.length == 0:
|
|
|
|
if self.length == 0:
|
|
|
|
self.logger.debug("{} got all chunks".format(self.peer))
|
|
|
|
|
|
|
|
self.all_chunks = True
|
|
|
|
self.all_chunks = True
|
|
|
|
self.fh.close()
|
|
|
|
suffix = str(self.peer[1])
|
|
|
|
self.fh = None
|
|
|
|
tmpfile = os.path.join(AIO.config["tmpdir"], f"uvscan_{self.request_time}_{suffix}")
|
|
|
|
AIO.queue.put_nowait((AIO.config["uvscan_path"], self.tmpfile, self.process_uvscan_result))
|
|
|
|
self.logger.debug(f"{self.peer} got last chunk, save data to {tmpfile}")
|
|
|
|
self.logger.info("{} queued uvscan of {}, queue size is {}".format(self.peer, self.tmpfile, AIO.queue.qsize()))
|
|
|
|
with open(tmpfile, "wb") as f:
|
|
|
|
break
|
|
|
|
|
|
|
|
self.logger.debug("{} chunk size is {} bytes".format(self.peer, self.length))
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
if len(self.buffer) == 0:
|
|
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
if not self.fh:
|
|
|
|
|
|
|
|
tmpfile = os.path.join(AIO.config["tmpdir"], "uvscan_{}_{}".format(self.request_time, str(self.peer[1])))
|
|
|
|
|
|
|
|
self.logger.debug("{} saving data to {}".format(self.peer, tmpfile))
|
|
|
|
|
|
|
|
self.fh = open(tmpfile, "wb")
|
|
|
|
|
|
|
|
self.tmpfile = tmpfile
|
|
|
|
self.tmpfile = tmpfile
|
|
|
|
left = self.length - self.fsize
|
|
|
|
f.write(self.data)
|
|
|
|
data = self.buffer[0:left]
|
|
|
|
AIO.queue.put_nowait((AIO.config["uvscan_path"], tmpfile, self.process_uvscan_result))
|
|
|
|
self.fh.write(data)
|
|
|
|
queuesize = AIO.queue.qsize()
|
|
|
|
self.buffer = self.buffer[len(data):]
|
|
|
|
self.logger.info(f"{self.peer} queued uvscan of {tmpfile}, queue size is {queuesize}")
|
|
|
|
self.fsize += len(data)
|
|
|
|
break
|
|
|
|
if self.fsize < self.length:
|
|
|
|
self.logger.debug(f"{self.peer} got chunk size of {self.length} bytes")
|
|
|
|
self.logger.debug("{} got {} of {} bytes".format(self.peer, self.fsize, self.length))
|
|
|
|
|
|
|
|
else:
|
|
|
|
else:
|
|
|
|
self.logger.debug("{} chunk complete ({} bytes)".format(self.peer, self.length))
|
|
|
|
if len(self.buffer) < self.length:
|
|
|
|
|
|
|
|
nbytes = len(self.buffer)
|
|
|
|
|
|
|
|
self.logger.debug(f"{self.peer} got {nbytes} of {self.length} bytes")
|
|
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
self.logger.debug(f"{self.peer} chunk complete ({self.length} bytes)")
|
|
|
|
|
|
|
|
self.data.extend(self.buffer[0:self.length])
|
|
|
|
|
|
|
|
self.buffer = self.buffer[self.length:]
|
|
|
|
self.length = None
|
|
|
|
self.length = None
|
|
|
|
self.fsize = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
except (RuntimeError, IndexError, IOError, struct.error) as e:
|
|
|
|
except (RuntimeError, IndexError, IOError, struct.error) as e:
|
|
|
|
self.logger.warning("{} warning: {}".format(self.peer, e))
|
|
|
|
self.logger.warning(f"{self.peer} warning: {e}")
|
|
|
|
self._send_response(str(e))
|
|
|
|
self._send_response(str(e))
|
|
|
|
|
|
|
|
|
|
|
|
def process_uvscan_result(self, result):
|
|
|
|
def process_uvscan_result(self, result):
|
|
|
|
self.logger.info("{} received uvscan result of {}: {}".format(self.peer, self.tmpfile, result))
|
|
|
|
if not self.tmpfile:
|
|
|
|
self.completed = True
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
self.logger.info(f"{self.peer} received uvscan result of {self.tmpfile}: {result}")
|
|
|
|
self._send_response(result)
|
|
|
|
self._send_response(result)
|
|
|
|
|
|
|
|
self.tmpfile = None
|
|
|
|
|
|
|
|
|
|
|
|
def connection_lost(self, exc):
|
|
|
|
def connection_lost(self, exc):
|
|
|
|
if self.tmpfile:
|
|
|
|
if not self.tmpfile:
|
|
|
|
if not self.completed:
|
|
|
|
self.logger.info(f"closed connection to {self.peer}")
|
|
|
|
self.logger.warning("{} client prematurely closed connection, removing {} from scan queue".format(self.peer, self.tmpfile))
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
entries = []
|
|
|
|
entries = []
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
for entry in iter(AIO.queue.get_nowait, None):
|
|
|
|
for entry in iter(AIO.queue.get_nowait, None):
|
|
|
|
if not entry:
|
|
|
|
if not entry:
|
|
|
|
continue
|
|
|
|
continue
|
|
|
|
if entry[1] != self.tmpfile:
|
|
|
|
if self.tmpfile and entry[1] == self.tmpfile:
|
|
|
|
|
|
|
|
self.logger.warning(f"{self.peer} client prematurely closed connection, skipping scan of {self.tmpfile}")
|
|
|
|
|
|
|
|
os.remove(self.tmpfile)
|
|
|
|
|
|
|
|
self.tmpfile = None
|
|
|
|
|
|
|
|
continue
|
|
|
|
entries.append(entry)
|
|
|
|
entries.append(entry)
|
|
|
|
except asyncio.QueueEmpty:
|
|
|
|
except asyncio.QueueEmpty:
|
|
|
|
pass
|
|
|
|
pass
|
|
|
|
for entry in entries:
|
|
|
|
for entry in entries:
|
|
|
|
AIO.queue.put_nowait(entry)
|
|
|
|
AIO.queue.put_nowait(entry)
|
|
|
|
self.logger.debug("{} removing temporary file {}".format(self.peer, self.tmpfile))
|
|
|
|
|
|
|
|
if self.fh:
|
|
|
|
if self.tmpfile:
|
|
|
|
self.fh.close()
|
|
|
|
self.logger.warning(f"{self.peer} client prematurely closed connection, but scan is already running")
|
|
|
|
os.remove(self.tmpfile)
|
|
|
|
self.tmpfile = None
|
|
|
|
self.logger.info("closed connection to {}".format(self.peer))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
def main():
|
|
|
|
"Run uvscand."
|
|
|
|
"Run uvscand."
|
|
|
|
# parse command line
|
|
|
|
# parse command line
|
|
|
|
parser = argparse.ArgumentParser(description="uvscand daemon",
|
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
|
|
|
|
description="uvscand daemon",
|
|
|
|
formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=45, width=140))
|
|
|
|
formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=45, width=140))
|
|
|
|
parser.add_argument("-c", "--config", help="List of config files to read.", nargs="+",
|
|
|
|
parser.add_argument("-c", "--config", help="List of config files to read.", nargs="+", default=["/etc/uvscand.conf"])
|
|
|
|
default=["/etc/uvscand.conf"])
|
|
|
|
parser.add_argument("-m", "--maxprocs", help="Maximum number of parallel scan processes.", type=int, default=8)
|
|
|
|
parser.add_argument("-m", "--maxprocs", help="Maximum number of parallel scan processes.",
|
|
|
|
|
|
|
|
type=int, default=8)
|
|
|
|
|
|
|
|
parser.add_argument("-d", "--debug", help="Log debugging messages.", action="store_true")
|
|
|
|
parser.add_argument("-d", "--debug", help="Log debugging messages.", action="store_true")
|
|
|
|
args = parser.parse_args()
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
|
@@ -189,8 +186,8 @@ def main():
|
|
|
|
syslog_name = logname
|
|
|
|
syslog_name = logname
|
|
|
|
if args.debug:
|
|
|
|
if args.debug:
|
|
|
|
loglevel = logging.DEBUG
|
|
|
|
loglevel = logging.DEBUG
|
|
|
|
logname = "{}[%(name)s]".format(logname)
|
|
|
|
logname = f"{logname}[%(name)s]"
|
|
|
|
syslog_name = "{}: [%(name)s] %(levelname)s".format(syslog_name)
|
|
|
|
syslog_name = f"{syslog_name}: [%(name)s] %(levelname)s"
|
|
|
|
|
|
|
|
|
|
|
|
root_logger = logging.getLogger()
|
|
|
|
root_logger = logging.getLogger()
|
|
|
|
root_logger.setLevel(loglevel)
|
|
|
|
root_logger.setLevel(loglevel)
|
|
|
@@ -198,14 +195,14 @@ def main():
|
|
|
|
# setup console log
|
|
|
|
# setup console log
|
|
|
|
stdouthandler = logging.StreamHandler(sys.stdout)
|
|
|
|
stdouthandler = logging.StreamHandler(sys.stdout)
|
|
|
|
stdouthandler.setLevel(loglevel)
|
|
|
|
stdouthandler.setLevel(loglevel)
|
|
|
|
formatter = logging.Formatter("%(asctime)s {}: [%(levelname)s] %(message)s".format(logname), datefmt="%Y-%m-%d %H:%M:%S")
|
|
|
|
formatter = logging.Formatter(f"%(asctime)s {logname}: [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
|
|
|
stdouthandler.setFormatter(formatter)
|
|
|
|
stdouthandler.setFormatter(formatter)
|
|
|
|
root_logger.addHandler(stdouthandler)
|
|
|
|
root_logger.addHandler(stdouthandler)
|
|
|
|
|
|
|
|
|
|
|
|
# setup syslog
|
|
|
|
# setup syslog
|
|
|
|
sysloghandler = logging.handlers.SysLogHandler(address="/dev/log")
|
|
|
|
sysloghandler = logging.handlers.SysLogHandler(address="/dev/log")
|
|
|
|
sysloghandler.setLevel(loglevel)
|
|
|
|
sysloghandler.setLevel(loglevel)
|
|
|
|
formatter = logging.Formatter("{}: %(message)s".format(syslog_name))
|
|
|
|
formatter = logging.Formatter(f"{syslog_name}: %(message)s")
|
|
|
|
sysloghandler.setFormatter(formatter)
|
|
|
|
sysloghandler.setFormatter(formatter)
|
|
|
|
root_logger.addHandler(sysloghandler)
|
|
|
|
root_logger.addHandler(sysloghandler)
|
|
|
|
|
|
|
|
|
|
|
@@ -222,7 +219,7 @@ def main():
|
|
|
|
config = dict(parser.items("uvscand"))
|
|
|
|
config = dict(parser.items("uvscand"))
|
|
|
|
for option in ["bind_address", "bind_port", "tmpdir", "uvscan_path", "loglevel"]:
|
|
|
|
for option in ["bind_address", "bind_port", "tmpdir", "uvscan_path", "loglevel"]:
|
|
|
|
if option not in config.keys():
|
|
|
|
if option not in config.keys():
|
|
|
|
logger.error("option '{}' not present in config section 'uvscand'".format(option))
|
|
|
|
logger.error(f"option '{option}' not present in config section 'uvscand'")
|
|
|
|
sys.exit(1)
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
if not args.debug:
|
|
|
|
if not args.debug:
|
|
|
@@ -232,7 +229,7 @@ def main():
|
|
|
|
|
|
|
|
|
|
|
|
# check if uvscan binary exists and is executable
|
|
|
|
# check if uvscan binary exists and is executable
|
|
|
|
if not os.path.isfile(config["uvscan_path"]) or not os.access(config["uvscan_path"], os.X_OK):
|
|
|
|
if not os.path.isfile(config["uvscan_path"]) or not os.access(config["uvscan_path"], os.X_OK):
|
|
|
|
logger.error("uvscan binary '{}' does not exist or is not executable".format(config["uvscan_path"]))
|
|
|
|
logger.error(f"uvscan binary '{config['uvscan_path']}' does not exist or is not executable")
|
|
|
|
sys.exit(1)
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
# setup protocol
|
|
|
|
# setup protocol
|
|
|
|