Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
My Possibly-Nicer Clamd Initscript Modification
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks
View previous topic :: View next topic  
Author Message
pigsboss
n00b
n00b


Joined: 27 Dec 2011
Posts: 20

PostPosted: Wed Jun 20, 2012 4:43 am    Post subject: My Possibly-Nicer Clamd Initscript Modification Reply with quote

Since I symlinked /var/run to /run, which is a tmpfs, my clamav keeps complaining on its every first start.

Here is my /etc/clamd.conf:
Code:

##
## Example config file for the Clam AV daemon
## Please read the clamd.conf(5) manual before editing this file.
##


# Comment or remove the line below.
# Example

# Uncomment this option to enable logging.
# LogFile must be writable for the user running daemon.
# A full path is required.
# Default: disabled
LogFile /var/log/clamav/clamd.log

# By default the log file is locked for writing - the lock protects against
# running clamd multiple times (if want to run another clamd, please
# copy the configuration file, change the LogFile variable, and run
# the daemon with --config-file option).
# This option disables log file locking.
# Default: no
#LogFileUnlock yes

# Maximum size of the log file.
# Value of 0 disables the limit.
# You may use 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)
# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes). To specify the size
# in bytes just don't use modifiers.
# Default: 1M
#LogFileMaxSize 2M

# Log time with each message.
# Default: no
LogTime yes

# Also log clean files. Useful in debugging but drastically increases the
# log size.
# Default: no
#LogClean yes

# Use system logger (can work together with LogFile).
# Default: no
#LogSyslog yes

# Specify the type of syslog messages - please refer to 'man syslog'
# for facility names.
# Default: LOG_LOCAL6
#LogFacility LOG_MAIL

# Enable verbose logging.
# Default: no
#LogVerbose yes

# Log additional information about the infected file, such as its
# size and hash, together with the virus name.
ExtendedDetectionInfo yes

# This option allows you to save a process identifier of the listening
# daemon (main thread).
# Default: disabled
PidFile /var/run/clamav/clamd.pid

# Optional path to the global temporary directory.
# Default: system specific (usually /tmp or /var/tmp).
TemporaryDirectory /var/tmp

# Path to the database directory.
# Default: hardcoded (depends on installation options)
#DatabaseDirectory /var/lib/clamav

# Only load the official signatures published by the ClamAV project.
# Default: no
#OfficialDatabaseOnly no

# The daemon can work in local mode, network mode or both.
# Due to security reasons we recommend the local mode.

# Path to a local socket file the daemon will listen on.
# Default: disabled (must be specified by a user)
LocalSocket /var/run/clamav/clamd.sock

# Sets the group ownership on the unix socket.
# Default: disabled (the primary group of the user running clamd)
#LocalSocketGroup virusgroup

# Sets the permissions on the unix socket to the specified mode.
# Default: disabled (socket is world accessible)
#LocalSocketMode 660

# Remove stale socket after unclean shutdown.
# Default: yes
#FixStaleSocket yes

# TCP port address.
# Default: no
#TCPSocket 3310

# TCP address.
# By default we bind to INADDR_ANY, probably not wise.
# Enable the following to provide some degree of protection
# from the outside world.
# Default: no
#TCPAddr 127.0.0.1

# Maximum length the queue of pending connections may grow to.
# Default: 200
#MaxConnectionQueueLength 30

# Clamd uses FTP-like protocol to receive data from remote clients.
# If you are using clamav-milter to balance load between remote clamd daemons
# on firewall servers you may need to tune the options below.

# Close the connection when the data size limit is exceeded.
# The value should match your MTA's limit for a maximum attachment size.
# Default: 25M
#StreamMaxLength 10M

# Limit port range.
# Default: 1024
#StreamMinPort 30000
# Default: 2048
#StreamMaxPort 32000

# Maximum number of threads running at the same time.
# Default: 10
#MaxThreads 20

# Waiting for data from a client socket will timeout after this time (seconds).
# Default: 120
#ReadTimeout 300

# This option specifies the time (in seconds) after which clamd should
# timeout if a client doesn't provide any initial command after connecting.
# Default: 5
#CommandReadTimeout 5

# This option specifies how long to wait (in miliseconds) if the send buffer is full.
# Keep this value low to prevent clamd hanging
#
# Default: 500
#SendBufTimeout 200

# Maximum number of queued items (including those being processed by MaxThreads threads)
# It is recommended to have this value at least twice MaxThreads if possible.
# WARNING: you shouldn't increase this too much to avoid running out  of file descriptors,
# the following condition should hold:
# MaxThreads*MaxRecursion + (MaxQueue - MaxThreads) + 6< RLIMIT_NOFILE (usual max is 1024)
#
# Default: 100
#MaxQueue 200

# Waiting for a new job will timeout after this time (seconds).
# Default: 30
#IdleTimeout 60

# Don't scan files and directories matching regex
# This directive can be used multiple times
# Default: scan all
#ExcludePath ^/proc/
#ExcludePath ^/sys/

# Maximum depth directories are scanned at.
# Default: 15
#MaxDirectoryRecursion 20

# Follow directory symlinks.
# Default: no
#FollowDirectorySymlinks yes

# Follow regular file symlinks.
# Default: no
#FollowFileSymlinks yes

# Scan files and directories on other filesystems.
# Default: yes
#CrossFilesystems yes

# Perform a database check.
# Default: 600 (10 min)
#SelfCheck 600

# Execute a command when virus is found. In the command string %v will
# be replaced with the virus name.
# Default: no
#VirusEvent /usr/local/bin/send_sms 123456789 "VIRUS ALERT: %v"

# Run as another user (clamd must be started by root for this option to work)
# Default: don't drop privileges
# User clamav

# Initialize supplementary group access (clamd must be started by root).
# Default: no
AllowSupplementaryGroups yes

# Stop daemon when libclamav reports out of memory condition.
#ExitOnOOM yes

# Don't fork into background.
# Default: no
#Foreground yes

# Enable debug messages in libclamav.
# Default: no
#Debug yes

# Do not remove temporary files (for debug purposes).
# Default: no
#LeaveTemporaryFiles yes

# Detect Possibly Unwanted Applications.
# Default: no
#DetectPUA yes

# Exclude a specific PUA category. This directive can be used multiple times.
# See http://www.clamav.net/support/pua for the complete list of PUA
# categories.
# Default: Load all categories (if DetectPUA is activated)
#ExcludePUA NetTool
#ExcludePUA PWTool

# Only include a specific PUA category. This directive can be used multiple
# times.
# Default: Load all categories (if DetectPUA is activated)
#IncludePUA Spy
#IncludePUA Scanner
#IncludePUA RAT

# In some cases (eg. complex malware, exploits in graphic files, and others),
# ClamAV uses special algorithms to provide accurate detection. This option
# controls the algorithmic detection.
# Default: yes
#AlgorithmicDetection yes


##
## Executable files
##

# PE stands for Portable Executable - it's an executable file format used
# in all 32 and 64-bit versions of Windows operating systems. This option allows
# ClamAV to perform a deeper analysis of executable files and it's also
# required for decompression of popular executable packers such as UPX, FSG,
# and Petite. If you turn off this option, the original files will still be
# scanned, but without additional processing.
# Default: yes
#ScanPE yes

# Executable and Linking Format is a standard format for UN*X executables.
# This option allows you to control the scanning of ELF files.
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
# Default: yes
#ScanELF yes

# With this option clamav will try to detect broken executables (both PE and
# ELF) and mark them as Broken.Executable.
# Default: no
#DetectBrokenExecutables yes


##
## Documents
##

# This option enables scanning of OLE2 files, such as Microsoft Office
# documents and .msi files.
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
# Default: yes
#ScanOLE2 yes


# With this option enabled OLE2 files with VBA macros, which were not
# detected by signatures will be marked as "Heuristics.OLE2.ContainsMacros".
# Default: no
#OLE2BlockMacros no

# This option enables scanning within PDF files.
# If you turn off this option, the original files will still be scanned, but
# without decoding and additional processing.
# Default: yes
#ScanPDF yes


##
## Mail files
##

# Enable internal e-mail scanner.
# If you turn off this option, the original files will still be scanned, but
# without parsing individual messages/attachments.
# Default: yes
#ScanMail yes

# Scan RFC1341 messages split over many emails.
# You will need to periodically clean up $TemporaryDirectory/clamav-partial directory.
# WARNING: This option may open your system to a DoS attack.
#          Never use it on loaded servers.
# Default: no
#ScanPartialMessages yes


# With this option enabled ClamAV will try to detect phishing attempts by using
# signatures.
# Default: yes
#PhishingSignatures yes

# Scan URLs found in mails for phishing attempts using heuristics.
# Default: yes
#PhishingScanURLs yes

# Always block SSL mismatches in URLs, even if the URL isn't in the database.
# This can lead to false positives.
#
# Default: no
#PhishingAlwaysBlockSSLMismatch no

# Always block cloaked URLs, even if URL isn't in database.
# This can lead to false positives.
#
# Default: no
#PhishingAlwaysBlockCloak no

# Allow heuristic match to take precedence.
# When enabled, if a heuristic scan (such as phishingScan) detects
# a possible virus/phish it will stop scan immediately. Recommended, saves CPU
# scan-time.
# When disabled, virus/phish detected by heuristic scans will be reported only at
# the end of a scan. If an archive contains both a heuristically detected
# virus/phish, and a real malware, the real malware will be reported
#
# Keep this disabled if you intend to handle "*.Heuristics.*" viruses
# differently from "real" malware.
# If a non-heuristically-detected virus (signature-based) is found first,
# the scan is interrupted immediately, regardless of this config option.
#
# Default: no
#HeuristicScanPrecedence yes

##
## Data Loss Prevention (DLP)
##

# Enable the DLP module
# Default: No
#StructuredDataDetection yes

# This option sets the lowest number of Credit Card numbers found in a file
# to generate a detect.
# Default: 3
#StructuredMinCreditCardCount 5

# This option sets the lowest number of Social Security Numbers found
# in a file to generate a detect.
# Default: 3
#StructuredMinSSNCount 5

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxx-yy-zzzz
# Default: yes
#StructuredSSNFormatNormal yes

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxxyyzzzz
# Default: no
#StructuredSSNFormatStripped yes


##
## HTML
##

# Perform HTML normalisation and decryption of MS Script Encoder code.
# Default: yes
# If you turn off this option, the original files will still be scanned, but
# without additional processing.
#ScanHTML yes


##
## Archives
##

# ClamAV can scan within archives and compressed files.
# If you turn off this option, the original files will still be scanned, but
# without unpacking and additional processing.
# Default: yes
#ScanArchive yes

# Mark encrypted archives as viruses (Encrypted.Zip, Encrypted.RAR).
# Default: no
#ArchiveBlockEncrypted no


##
## Limits
##

# The options below protect your system against Denial of Service attacks
# using archive bombs.

# This option sets the maximum amount of data to be scanned for each input file.
# Archives and other containers are recursively extracted and scanned up to this
# value.
# Value of 0 disables the limit
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 100M
MaxScanSize 0

# Files larger than this limit won't be scanned. Affects the input file itself
# as well as files contained inside it (when the input file is an archive, a
# document or some other kind of container).
# Value of 0 disables the limit.
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 25M
MaxFileSize 0

# Nested archives are scanned recursively, e.g. if a Zip archive contains a RAR
# file, all files within it will also be scanned. This options specifies how
# deeply the process should be continued.
# Note: setting this limit too high may result in severe damage to the system.
# Default: 16
#MaxRecursion 10

# Number of files to be scanned within an archive, a document, or any other
# container file.
# Value of 0 disables the limit.
# Note: disabling this limit or setting it too high may result in severe damage
# to the system.
# Default: 10000
MaxFiles 15000


##
## Clamuko settings
##

# Enable Clamuko. Dazuko must be configured and running. Clamuko supports
# both Dazuko (/dev/dazuko) and DazukoFS (/dev/dazukofs.ctrl). DazukoFS
# is the preferred option. For more information please visit www.dazuko.org
# Default: no
#ClamukoScanOnAccess yes

# The number of scanner threads that will be started (DazukoFS only).
# Having multiple scanner threads allows Clamuko to serve multiple
# processes simultaneously. This is particularly beneficial on SMP machines.
# Default: 3
#ClamukoScannerCount 3

# Don't scan files larger than ClamukoMaxFileSize
# Value of 0 disables the limit.
# Default: 5M
#ClamukoMaxFileSize 10M

# Set access mask for Clamuko (Dazuko only).
# Default: no
#ClamukoScanOnOpen yes
#ClamukoScanOnClose yes
#ClamukoScanOnExec yes

# Set the include paths (all files inside them will be scanned). You can have
# multiple ClamukoIncludePath directives but each directory must be added
# in a seperate line. (Dazuko only)
# Default: disabled
#ClamukoIncludePath /home
#ClamukoIncludePath /students

# Set the exclude paths. All subdirectories are also excluded. (Dazuko only)
# Default: disabled
#ClamukoExcludePath /home/bofh

# With this option you can whitelist specific UIDs. Processes with these UIDs
# will be able to access all files.
# This option can be used multiple times (one per line).
# Default: disabled
#ClamukoExcludeUID 0

# With this option enabled ClamAV will load bytecode from the database.
# It is highly recommended you keep this option on, otherwise you'll miss detections for many new viruses.
# Default: yes
#Bytecode yes

# Set bytecode security level.
# Possible values:
#       None - no security at all, meant for debugging. DO NOT USE THIS ON PRODUCTION SYSTEMS
#         This value is only available if clamav was built with --enable-debug!
#       TrustSigned - trust bytecode loaded from signed .c[lv]d files,
#                insert runtime safety checks for bytecode loaded from other sources
#       Paranoid - don't trust any bytecode, insert runtime checks for all
# Recommended: TrustSigned, because bytecode in .cvd files already has these checks
# Note that by default only signed bytecode is loaded, currently you can only
# load unsigned bytecode in --enable-debug mode.
#
# Default: TrustSigned
#BytecodeSecurity TrustSigned

# Set bytecode timeout in miliseconds.
#
# Default: 5000
# BytecodeTimeout 1000


I did some research on its initscript and configuration file. I've found clamd is started by root but the privilege is dropped to user clamav. And since /run (i.e. /var/run) where the *.pid and *.socket should be create is not writable by clamav, the clamd daemon then fails to start.

So I should either change the default location for the .pid and .socket file from /var/run/clamav to a non-tmpfs directory, or I should create the container for both of the files manually before the daemon is started. And there is actually the third way: don't drop the privilege to clamav, so that clamd can create any directory necessary all by itself. However I think it could possibly be safer to run clamdscan as a non-root user, I don't take this way.

I made some modifications on /etc/conf.d/clamd and /etc/init.d/clamd, so now the clamd daemon can be started smoothly:

Code:

# Config file for /etc/init.d/clamd                                                                                                                                         
                                                                                                                                                                           
# NOTICE: Since clamav-0.85-r1, only START_CLAMD and START_FRESHCLAM settings                                                                                               
#         are used, other are silently ignored                                                                                                                             
                                                                                                                                                                           
START_CLAMD=yes                                                                                                                                                             
START_FRESHCLAM=yes                                                                                                                                                         
CLAMD_NICELEVEL=3                                                                                                                                                           
FRESHCLAM_NICELEVEL=19                                                                                                                                                     
                                                                                                                                                                           
# added by pigsboss                                                                                                                                   
RUN_DIRECTORY=/var/run/clamav                                                                                                                                               
CLAMD_USER=clamav                                                                                                                                                           
CLAMD_GROUP=clamav 


Code:
#!/sbin/runscript                                                                                                                                                           
# Copyright 1999-2011 Gentoo Foundation                                                                                                                                     
# Distributed under the terms of the GNU General Public License v2                                                                                                         
# $Header: /var/cvsroot/gentoo-x86/app-antivirus/clamav/files/clamd.rc,v 1.18 2011/12/04 11:51:46 swegener Exp $                                                           
                                                                                                                                                                           
extra_commands="logfix"                                                                                                                                                     
                                                                                                                                                                           
depend() {                                                                                                                                                                 
        use net                                                                                                                                                             
        provide antivirus                                                                                                                                                   
}

start() {
        local clamd_socket=`awk '$1 == "LocalSocket" { print $2 }' /etc/clamd.conf`
        logfix

        if [ "${START_CLAMD}" = "yes" ]; then
                if [ -S "${clamd_socket:-/tmp/clamd}" ]; then
                        rm -f ${clamd_socket:-/tmp/clamd}
                fi

                ebegin "Starting clamd"

                # added by pigsboss
                if [ ! -e ${RUN_DIRECTORY} ]; then
                        mkdir -p ${RUN_DIRECTORY}
                        chown ${CLAMD_USER}.${CLAMD_GROUP} ${RUN_DIRECTORY}
                fi
                start-stop-daemon --start --quiet \
                        --nicelevel ${CLAMD_NICELEVEL:-0} \
                        --exec /usr/sbin/clamd
                eend $? "Failed to start clamd"
        fi

        if [ "${START_FRESHCLAM}" = "yes" ]; then
                ebegin "Starting freshclam"
                start-stop-daemon --start --quiet \
                        --nicelevel ${FRESHCLAM_NICELEVEL:-0} \
                        --exec /usr/bin/freshclam -- -d
                retcode=$?
                if [ ${retcode} = 1 ]; then
                        eend 0
                        einfo "Virus databases are already up to date."
                else
                        eend ${retcode} "Failed to start freshclam"
                fi
        fi

        if [ "${START_MILTER}" = "yes" ]; then
                if [ -z "${MILTER_CONF_FILE}" ]; then
                        MILTER_CONF_FILE="/etc/clamav-milter.conf"
                fi

                ebegin "Starting clamav-milter"
                start-stop-daemon --start --quiet \
                        --nicelevel ${MILTER_NICELEVEL:-0} \
                        --exec /usr/sbin/clamav-milter -- -c ${MILTER_CONF_FILE}
                eend $? "Failed to start clamav-milter"
        fi
}

stop() {
        if [ "${START_CLAMD}" = "yes" ]; then
                ebegin "Stopping clamd"
                start-stop-daemon --stop --quiet --name clamd
                eend $? "Failed to stop clamd"
        fi
        if [ "${START_FRESHCLAM}" = "yes" ]; then
                ebegin "Stopping freshclam"
                start-stop-daemon --stop --quiet --name freshclam
                eend $? "Failed to stop freshclam"
        fi
        if [ "${START_MILTER}" = "yes" ]; then
                ebegin "Stopping clamav-milter"
                start-stop-daemon --stop --quiet --name clamav-milter
                eend $? "Failed to stop clamav-milter"
        fi
}

logfix() {
        if [ "${START_CLAMD}" = "yes" ]; then
                # fix clamd log permissions
                # (might be clobbered by logrotate or something)
                local logfile=`awk '$1 == "LogFile" { print $2 }' /etc/clamd.conf`
                local clamav_user=`awk '$1 == "User" { print $2 }' /etc/clamd.conf`
                if [ -n "${logfile}" ] && [ -n "${clamav_user}" ]; then
                        if [ ! -f "${logfile}" ]; then
                                touch ${logfile}
                        fi
                        chown ${clamav_user} ${logfile}
                        chmod 640 ${logfile}
                fi
        fi

        if [ "${START_FRESHCLAM}" = "yes" ]; then
                # fix freshclam log permissions
                # (might be clobbered by logrotate or something)
                logfile=`awk '$1 == "UpdateLogFile" { print $2 }' /etc/freshclam.conf`
                local freshclam_user=`awk '$1 == "DatabaseOwner" { print $2 }' /etc/freshclam.conf`
                if [ -n "${logfile}" -a -n "${clamav_user}" ]; then
                        if [ ! -f "${logfile}" ]; then
                                touch ${logfile}
                        fi
                        chown ${freshclam_user} ${logfile}
                        chmod 640 ${logfile}
                fi
        fi
}


Basically I put a checkpoint in the start() {} block in /etc/init.d/clamd. Hence before the start-stop-daemon starts clamd daemon the script can check if the necessary directory e.g., /var/run/clamav exists. If not, the script would create one. In order to set proper permissions several variables are added to the /etc/conf.d/clamd file.

I don't know weather it is correct or not, for an ordinary user to modify the initscript itself.
_________________
Pig's Boss / 猪头
Back to top
View user's profile Send private message
John R. Graham
Administrator
Administrator


Joined: 08 Mar 2005
Posts: 10587
Location: Somewhere over Atlanta, Georgia

PostPosted: Fri Jul 06, 2012 12:16 am    Post subject: Reply with quote

Moved from Gentoo Chat to Documentation, Tips & Tricks.

- John
_________________
I can confirm that I have received between 0 and 499 National Security Letters.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum