Thursday, November 21, 2013

Log rotate

Log files are the most valuable tools available for Linux system security. The logrotate program is used to provide the administrator with an up-to-date record of events taking place on the system. The logrotate utility may also be used to back up log files, so copies may be used to establish patterns for system use. In this Daily Drill Down, I’ll cover the following topics:
  • The logrotate configuration
  • Setting defaults for logrotate
  • Using the include option to read other configuration files
  • Setting rotation parameters for specific files
  • Using the include option to override defaults
Log files are the most valuable tools available for Linux system security. The logrotate program is used to provide the administrator with an up-to-date record of events taking place on the system. The logrotate utility may also be used to back up log files, so copies may be used to establish patterns for system use. In this Daily Drill Down, I’ll cover the following topics:
  • The logrotate configuration
  • Setting defaults for logrotate
  • Using the include option to read other configuration files
  • Setting rotation parameters for specific files
  • Using the include option to override defaults

The logrotate program
The logrotate program is a log file manager. It is used to regularly cycle (or rotate) log files by removing the oldest ones from your system and creating new log files. It may be used to rotate based on the age of the file or the file’s size, and usually runs automatically through the cronutility. The logrotate program may also be used to compress log files and to configure e-mail to users when they are rotated.

The logrotate configuration
The logrotate program is configured by entering options in the /etc/logrotate.conf file. This is a text file, which may contain any of the configuration options listed in the table below. The options entered in /etc/logrotate.conf may be used to set configuration parameters for any log file on the system. These options may also be used to allow logrotate to read configuration parameters from other log files, by using the include parameter.

Option
Function
compressThis is used to compress the rotated log file with gzip.
nocompressThis is used when you do not want to compress rotated log files.
copytruncateThis is used when processes are still writing information to open log files. This option copies the active log file to a backup and truncates the active log file.
nocopytruncateThis copies the log files to backup, but the open log file is not truncated.
create mode owner groupThis rotates the log file and creates a new log file with the specified permissions, owner, and group. The default is to use the same mode, owner, and group as the original file.
nocreateThis prevents the creation of a new log file.
delaycompressWhen used with the compress option, the rotated log file is not compressed until the next time it is cycled.
nodelaycompressThis overrides delaycompress. The log file is compressed when it is cycled.
errors addressThis mails logrotate errors to an address.
ifemptyWith this, the log file is rotated even if it is empty. This is the default forlogrotate.
notifemptyThis does not rotate the log file if it is empty.
mail addressThis mails log files that are cycled to an address. When mail log files are cycled, they are effectively removed from the system.
nomailWhen mail log files are cycled, a copy is not mailed.
olddir directoryWith this, cycled log files are kept in the specified directory. This directory must be on the same filesystem as the current log files.
noolddirCycled log files are kept in the same directory as the current log files.
prerotate/endscriptThese are statements that enclose commands to be executed prior to a log file being rotated. The prerotate and endscript keywords must appear on a line by themselves.
postrotate/endscriptThese are statements that enclose commands to be executed after a log file has been rotated. The postrotate and endscript keywords must appear on a line by themselves.
dailyThis is used to rotate log files daily.
weeklyThis is used to rotate log files weekly.
monthlyThis is used to rotate log files monthly.
rotate countThis specifies the number of times to rotate a file before it is deleted. A count of 0 (zero) means no copies are retained. A count of 5 means five copies are retained.
tabootext [+] listThis directs logrotate to not rotate files with the specified extension. The default list of extensions is .rpm-orig, .rpmsave, v, and ~.
size sizeWith this, the log file is rotated when the specified size is reached. Size may be specified in bytes (default), kilobytes (sizek), or megabytes (sizem).

The /etc/logrotate.conf file
The /etc/logrotate.conf file is the default configuration file for logrotate. The default/etc/logrotate.conf file installed with Red Hat Linux is shown below:
# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# send errors to root
errors root
# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
#compress
1
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own lastlog or wtmp --we'll rotate them here
/var/log/wtmp {
    monthly
    create 0664 root utmp
    rotate 1
}

/var/log/lastlog {
    monthly
    rotate 1
}

# system-specific logs may be configured here


Setting defaults for logrotate
Default configuration settings are normally placed close to the beginning of the logrotate.conffile. These settings are usually in effect system-wide. The default settings for logrotate on this system are established in the first 12 lines of the file.

The third line
weekly

specifies that all log files will be rotated weekly.

The fifth line
rotate 4

specifies that four copies of old log files are retained before the files are cycled. Cycling refers to removing the oldest log files and replacing them with new copies.

The seventh line
errors root

sends all logrotate error messages to root.

The ninth line
create

configures logrotate to automatically create new log files. The new log files will have the same permissions, owner, and group as the file being rotated.

The eleventh line
#compress

prevents logrotate from compressing log files when they are rotated. Compression is enabled by removing the comment (#) from this line.

Using the include option
The include option allows the administrator to take log file rotation information, which may be installed in several files, and use it in the main configuration file. When logrotate finds the includeoption on a line in logrotate.conf, the information in the file specified is read as if it appeared in/etc/logrotate.conf.

Line 13 in /etc/logrotate.conf
include /etc/logrotate.d

tells logrotate to be read in the log rotation parameters, which are stored in the files contained in the /etc/logrotate.d directory. The include option is very useful when RPM packages are installed on a system. RPM packages’ log rotation parameters will typically install in the /etc/logrotate.ddirectory.

The include option is important. Some of the applications that install their log rotation parameters to /etc/logrotate.d by default are apachelinuxconfsambacron, and syslog. Theinclude option allows the parameters from each of these files to be read into logrotate.conf.

Using the include option in /etc/logrotate.conf allows the administrator to configure a rotation policy for these packages through a single configuration file.

Using include to override defaults
When a file is read by /etc/logrotate.conf, the rotation parameters specified in the include will override the parameters specified in the logrotate file. An example of /etc/logrotate.conf being overridden is shown below:
#Log rotation parameters for linuxconf
/var/log/htmlaccess.log
{ errors jim
notifempty
nocompress
weekly
prerotate
/usr/bin/chattr -a /var/log/htmlaccess.log
endscript
postrotate
/usr/bin/chattr +a /var/log/htmlaccess.log
endscript
}
/var/log/netconf.log
{ nocompress
monthly
}


In this example, when the /etc/logrotate.d/linuxconf file is read by /etc/logrotate.conf, the following options will override the defaults specified in /etc/logrotate.conf:
Notifempty
errors jim


The nocompress and weekly options do not override any options contained in/etc/logrotate.conf.

Setting parameters for a specific file
Configuration parameters for a specific file are often required. A common example would be to include a section in the /etc/logrotate.conf file to rotate the /var/log/wtmp file once per month and keep only one copy of the log. When configuration is required for a specific file, the following format is used:
#comments
/full/path/to/file
{
option(s)
}


The following entry would cause the /var/log/wtmp file to be rotated once a month, with one backup copy retained:
#Use logrotate to rotate wtmp
/var/log/wtmp
{
monthly
rotate 1
}

Although the opening bracket may appear on a line with other text or commands, the closing bracket must be on a line by itself.
Using the prerotate and postrotate options
The section of code below shows a typical script in /etc/logrotate.d/syslog. This section applies only to /var/log/messages. On a production server, /etc/logrotate.d/syslog would probably contain similar entries.
/var/log/messages
{
prerotate
/usr/bin/chattr -a /var/log/messages
endscript
postrotate
/usr/bin/kill -HUP syslogd
/usr/bin/chattr +a /var/log/messages
endscript
}


The format for this script uses the following methods:
  • The first line, /var/logmessages, declares the file for which this script will be used.
  • The curly braces,{ }, are used to enclose the entire script. All commands contained within these braces will be run on the /var/log/messages file.
  • The prerotate command specifies actions to be taken prior to the file being rotated bylogrotate.
  • The command /usr/bin/chattr -a is run to remove the append-only attribute from/var/log/messages.
  • The endscript command marks the end of the prerotate portion of this script.
  • The next line, postrotate, specifies the following commands are to be run on/var/log/messages after the file has been rotated by logrotate.
  • The command /usr/bin/killall -HUPsyslogd is run to reinitiate the system logging daemon,syslogd.
  • The next command, /usr/bin/chattr +a /var/log/messages, reassigns the append-onlyattribute to the /var/log/messages file. This means the file may only be seen in append mode. This prevents the file from being overridden by any other program or user.
  • The endscript command appears on a line by itself and marks the end of the postrotateportion of this script.
  • The last curly brace,}, marks the end of commands to be applied to the /var/log/messagesfile.

Running logrotate
There are three steps involved in running logrotate:
  1. Identify the log files on your system.
  2. Create rotation schedules and parameters for the log files.
  3. Run logrotate through the cron daemon.

The code below shows the default cronjob shipped with Red Hat Linux to allow logrotate to run daily:
#/etc/cron.daily/logrotate
#! /bin/sh

/usr/sbin/logrotate   /etc/logrotate.conf


This cronjob allows logrotate to run daily with the rotation parameter specified in/etc/logrotate.conf.
Tao file httpd trong  /etc/logrotate.d/httpd với nội dung như sau:
/var/log/httpd/*log {
   maxage 365
    rotate 99
   # size=10M
   daily
   compress
    copytruncate
    notifempty
    missingok
    create 644 root root
}
Cấu hình trên sẽ tạo file logrotate hằng ngày cho httpd và nén nó đuôi mặc định .gz




2.Cấu hình logrotate cho freeswitch theo size tự rotate

Tạo file cấu hình:
vi /etc/logrotate.d/freeswitch
Sửa nội dung file
/usr/local/freeswitch/log/freeswitch.log {
    maxage 365
    rotate 99     
   size=10M
    compress
    copytruncate
    notifempty
    missingok
    create 644 root root
}
Tạo crontab để tiến hành rotate khi kiểm tra thấy file log có size=10M

/usr/bin/crondtab -e
 Sửa file thành chạy kiểm tra 10 phút 1 lần (với hệ thống nhỏ có thể check 1 tiếng 1 lần hoặc hơn)
*/10 * * * * /usr/sbin/logrotate /etc/logrotate.d/freeswitch

Wednesday, November 20, 2013

The-Perfect-Apache-Configuration

# ----------------------------------------------------------------------
# Apache configuration file
# This file is best used in /apache2/httpd.conf, but works (slower) in .htaccess
#
# I've spent quite a bit of time compiling what I find to be optimial to me
# and my server. This file is based on:
# - HTML5BoilerPlate: https://github.com/h5bp/html5-boilerplate/
# - W3 Edge: http://www.w3-edge.com/
# - Yahoo! Best Practices: http://developer.yahoo.com/performance/rules.html
# - Caching Tutorial: http://www.mnot.net/cache_docs/
# - Personal experience
#
# v1.2 / 2013.07.01 / Greg Rickaby
# ----------------------------------------------------------------------
# Specify a Default Charset
AddDefaultCharset utf-8
# ----------------------------------------------------------------------
# Cache Control via HTTP Headers + Expires
# Generation of Expires and Cache-Control HTTP headers according to user-specified criteria
# http://httpd.apache.org/docs/2.0/mod/mod_headers.html
# ----------------------------------------------------------------------
# Expires Defaults
<IfModule mod_expires.c>
        ExpiresActive On
        # Set default expires to 2 days
        ExpiresDefault A172800
        ExpiresByType text/css A31536000
        ExpiresByType application/x-javascript A31536000
        ExpiresByType text/x-component A31536000
        ExpiresByType text/html A3600
        ExpiresByType text/richtext A3600
        ExpiresByType image/svg+xml A3600
        ExpiresByType text/plain A3600
        ExpiresByType text/xsd A3600
        ExpiresByType text/xsl A3600
        ExpiresByType text/xml A3600
        ExpiresByType video/asf A31536000
        ExpiresByType video/avi A31536000
        ExpiresByType image/bmp A31536000
        ExpiresByType application/java A31536000
        ExpiresByType video/divx A31536000
        ExpiresByType application/msword A31536000
        ExpiresByType application/vnd.ms-fontobject A31536000
        ExpiresByType application/x-msdownload A31536000
        ExpiresByType image/gif A31536000
        ExpiresByType application/x-gzip A31536000
        ExpiresByType image/x-icon A31536000
        ExpiresByType image/jpeg A31536000
        ExpiresByType application/vnd.ms-access A31536000
        ExpiresByType audio/midi A31536000
        ExpiresByType video/quicktime A31536000
        ExpiresByType audio/mpeg A31536000
        ExpiresByType video/mp4 A31536000
        ExpiresByType video/mpeg A31536000
        ExpiresByType application/vnd.ms-project A31536000
        ExpiresByType application/x-font-otf A31536000
        ExpiresByType application/vnd.oasis.opendocument.database A31536000
        ExpiresByType application/vnd.oasis.opendocument.chart A31536000
        ExpiresByType application/vnd.oasis.opendocument.formula A31536000
        ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
        ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
        ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
        ExpiresByType application/vnd.oasis.opendocument.text A31536000
        ExpiresByType audio/ogg A31536000
        ExpiresByType application/pdf A31536000
        ExpiresByType image/png A31536000
        ExpiresByType application/vnd.ms-powerpoint A31536000
        ExpiresByType audio/x-realaudio A31536000
        ExpiresByType image/svg+xml A31536000
        ExpiresByType application/x-shockwave-flash A31536000
        ExpiresByType application/x-tar A31536000
        ExpiresByType image/tiff A31536000
        ExpiresByType application/x-font-ttf A31536000
        ExpiresByType audio/wav A31536000
        ExpiresByType audio/wma A31536000
        ExpiresByType application/vnd.ms-write A31536000
        ExpiresByType application/vnd.ms-excel A31536000
        ExpiresByType application/zip A31536000
</IfModule>
# No caching for dynamic files
<filesMatch "\.(php|cgi|pl|htm)$">
        ExpiresDefault A0
        Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
        Header set Pragma "no-cache"
</filesMatch>
# 1 MIN
<filesMatch "\.(html)$">
        ExpiresDefault A60
        Header set Cache-Control "max-age=60, must-revalidate"
</filesMatch>
# 2 DAYS
<filesMatch "\.(xml|txt)$">
        ExpiresDefault A172800
        Header set Cache-Control "max-age=172800, must-revalidate"
</filesMatch>
# 1 WEEK
<filesMatch "\.(jpg|jpeg|png|gif|swf|js|css)$">
        ExpiresDefault A604800
        Header set Cache-Control "max-age=604800, must-revalidate"
</filesMatch>
# 1 MONTH
<filesMatch "\.(ico|pdf|flv)$">
        ExpiresDefault A2419200
        Header set Cache-Control "max-age=2419200, must-revalidate"
</filesMatch>
# ----------------------------------------------------------------------
# Mime Types
# Mime Associates the requested filename's extensions with the file's behavior and content
# http://httpd.apache.org/docs/2.0/mod/mod_mime.html
# ----------------------------------------------------------------------
<IfModule mod_mime.c>
        AddType text/css .css
        AddType application/x-javascript .js
        AddType text/x-component .htc
        AddType text/html .html .htm
        AddType text/richtext .rtf .rtx
        AddType image/svg+xml .svg .svgz
        AddType text/plain .txt
        AddType text/xsd .xsd
        AddType text/xsl .xsl
        AddType text/xml .xml
        AddType video/asf .asf .asx .wax .wmv .wmx
        AddType video/avi .avi
        AddType image/bmp .bmp
        AddType application/java .class
        AddType video/divx .divx
        AddType application/msword .doc .docx
        AddType application/vnd.ms-fontobject .eot
        AddType application/x-msdownload .exe
        AddType image/gif .gif
        AddType application/x-gzip .gz .gzip
        AddType image/x-icon .ico
        AddType image/jpeg .jpg .jpeg .jpe
        AddType application/vnd.ms-access .mdb
        AddType audio/midi .mid .midi
        AddType video/quicktime .mov .qt
        AddType audio/mpeg .mp3 .m4a
        AddType video/mp4 .mp4 .m4v
        AddType video/mpeg .mpeg .mpg .mpe
        AddType application/vnd.ms-project .mpp
        AddType application/x-font-otf .otf
        AddType application/vnd.oasis.opendocument.database .odb
        AddType application/vnd.oasis.opendocument.chart .odc
        AddType application/vnd.oasis.opendocument.formula .odf
        AddType application/vnd.oasis.opendocument.graphics .odg
        AddType application/vnd.oasis.opendocument.presentation .odp
        AddType application/vnd.oasis.opendocument.spreadsheet .ods
        AddType application/vnd.oasis.opendocument.text .odt
        AddType audio/ogg .ogg
        AddType application/pdf .pdf
        AddType image/png .png
        AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
        AddType audio/x-realaudio .ra .ram
        AddType application/x-shockwave-flash .swf
        AddType application/x-tar .tar
        AddType image/tiff .tif .tiff
        AddType application/x-font-ttf .ttf .ttc
        AddType audio/wav .wav
        AddType audio/wma .wma
        AddType application/vnd.ms-write .wri
        AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
        AddType application/zip .zip
</IfModule>
# ----------------------------------------------------------------------
# Gzip compression
# Compress content before it is delivered to the client
# http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
# ----------------------------------------------------------------------
<IfModule mod_deflate.c>
        # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
        <IfModule mod_setenvif.c>
                <IfModule mod_headers.c>
                        SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
                        RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
                </IfModule>
        </IfModule>
        <IfModule filter_module>
                # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
                FilterDeclare COMPRESS
                FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html
                FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css
                FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain
                FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml+xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss+xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom+xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject
                FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg+xml
                FilterProvider COMPRESS DEFLATE resp=Content-Type $image/x-icon
                FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf
                FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype
                FilterChain COMPRESS
                FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no
        </IfModule>
        <IfModule !mod_filter.c>
                # Legacy versions of Apache
                AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
                AddOutputFilterByType DEFLATE application/javascript
                AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
                AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
                AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
        </IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Start rewrite engine
# Provides a rule-based rewriting engine to rewrite requested URLs on the fly
# http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
# ----------------------------------------------------------------------
# FollowSymLinks must be enabled for this to work
<IfModule mod_rewrite.c>
        Options +FollowSymlinks
        RewriteEngine On
</IfModule>
# Block access to "hidden" directories whose names begin with a period
<IfModule mod_rewrite.c>
        RewriteCond %{SCRIPT_FILENAME} -d
        RewriteCond %{SCRIPT_FILENAME} -f
        RewriteRule "(^|/)\." - [F]
</IfModule>
# ----------------------------------------------------------------------
# Disable server signature (Security)
# Configures the Server HTTP response header
# http://httpd.apache.org/docs/2.2/mod/core.html#serversignature
# ----------------------------------------------------------------------
ServerSignature Off
ServerTokens Prod
# ----------------------------------------------------------------------
# Disable directory browsing (Security)
# Generates directory indexes, automatically, similar to the Unix ls command or the Win32 dir shell command
# http://httpd.apache.org/docs/2.0/mod/mod_autoindex.html
# ----------------------------------------------------------------------
<IfModule mod_autoindex.c>
        Options -Indexes
</IfModule>
# ----------------------------------------------------------------------
# Block access to backup and source files (Security)
# This files may be left by some text/html editors and pose a great security danger
# ----------------------------------------------------------------------
<FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
        Order allow,deny
        Deny from all
        Satisfy All
</FilesMatch>
# ----------------------------------------------------------------------
# Increase cookie security (Security)
# This files may be left by some text/html editors and pose a great security danger
# ----------------------------------------------------------------------
<IfModule php5_module>
        php_value session.cookie_httponly true
</IfModule>
# ----------------------------------------------------------------------
# Webfont access
# Allow access from all domains for webfonts.
# ----------------------------------------------------------------------
<IfModule mod_headers.c>
        <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
                Header set Access-Control-Allow-Origin "*"
        </FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# Force latest IE rendering engine
# ----------------------------------------------------------------------
<IfModule mod_headers.c>
        Header set X-UA-Compatible "IE=Edge,chrome=1"
                # mod_headers can't match by content-type, but we don't want to this header on everything
                <FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$" >
                        Header unset X-UA-Compatible
                </FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# Instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
# https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
# ----------------------------------------------------------------------
<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# CORS-enabled images (@crossorigin)
# Send CORS headers if browsers request them; enabled by default for images.
# http://developer.mozilla.org/en/CORS_Enabled_Image
# http://blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
# http://hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
# http://wiki.mozilla.org/Security/Reviews/crossoriginAttribute
# ----------------------------------------------------------------------
<IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
                <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
                        SetEnvIf Origin ":" IS_CORS
                        Header set Access-Control-Allow-Origin "*" env=IS_CORS
                </FilesMatch>
        </IfModule>
</IfModule>