Linux 系统管理 : swatch 命令详解

swatch命令用于系统监控程序。

swatch可用来监控系统记录文件,并在发现特定的事件时,执行指定的动作。swatch所监控的事件以及对应事件的动作都存放在swatch的配置文件中。预设的配置文件为拥护根目录下的.swatchrc。然而在Red Hat Linux的预设用户根目录下并没有.swatchrc配置文件,您可将/usr/doc/swatch-2.2/config_files/swatchrc.personal文件复制到用户根目录下的.swatchrc,然后修改.swatchrc所要监控的事件及执行的动作。

语法

swatch [-A <分隔字符>][-c <设置文件>][-f <记录文件>][-I <分隔字符>][-P <分隔字符>][-r <时间>][-t <记录文件>][-A <分隔字符>][-c <设置文件>][-f <记录文件>][-I <分隔字符>][-P <分隔字符>][-r <时间>][-t <记录文件>]

参数说明

  • -A<分隔字符>  预设配置文件中,动作的分隔字符,预设为逗号。
  • -c<设置文件>  指定配置文件,而不使用预设的配置文件。
  • -f<记录文件>  检查指定的记录文件,检查完毕后不会继续监控该记录文件。
  • -I<分隔字符>  指定输入记录的分隔字符,预设为换行字符。
  • -P<分隔字符>  指定配置文件中,事件的分隔字符,预设为逗号。
  • -r<时间>  在指定的时间重新启动。
  • -t<记录文件>  检查指定的记录文件,并且会监控加入记录文件中的后继记录。

实例

开启系统监视

<span style="color:#880000"># swatch</span>

 

详解:

 

 一. 准备
1. 下载和解压缩最新的Swatch软件包.建议从Swatch的官方网站获得可靠的Swatch软件包.
下载网址: http://sourceforge.net/projects/swatch/
1) 创建Swatch软件包存放的目录.
mkdir -p /usr/local/src/log
2) 解压缩源代码包
tar zpxf swatch-***.tar.gz
二. 安装
cd swatch-***
      perl Makefile.PL
可能出现: 
Checking if your kit is complete...
Looks good
Warning: prerequisite Date::Calc 0 not found.
Warning: prerequisite Date::Format 0 not found.
Warning: prerequisite File::Tail 0 not found.
Warning: prerequisite Time::HiRes 1.12 not found.
解决方法1:
perl -MCPAN -e shell
>install Date::Calc
然后就一直点Yes,依次安装剩下的三个。
解决方法2:
      直接用wget下载下列文件

http://search.cpan.org/CPAN/authors/id/S/ST/STBEY/Date-Calc-5.3.tar.gz
http://search.cpan.org/CPAN/authors/id/G/GB/GBARR/TimeDate-1.1301.tar.gz
http://search.cpan.org/CPAN/authors/id/M/MG/MGRABNAR/File-Tail-0.98.tar.gz
http://search.cpan.org/CPAN/authors/id/J/JH/JHI/Time-HiRes-1.37.tar.gz

 

   然后,
$ tar zxvf $SOURCE/Date-calc-5.3.tar.gz
$ cd $SOURCE/Date-Calc-5.2
$ perl Makefile.PL
$ make
$ make test
$ su
# make install



make
make test
make install
make realclean
Swatch程序安装成功后, Perl模块将会用于Swatch程序的运行.
三 使用
    1、使用之前,需要创建一个.conf文件
例如:创建一个/root/abc.conf文件,内容为:
      watchfor /[Ff]ail/
      echo red
      bell 1
      exec "echo 000000"

    2、简单使用
    swatch --config-file=/root/abc.conf
--examine=/var/log/secure.1
   得到结果:
*** swatch version 3.2.3 (pid:11950) started at 三 9月 17 09:06:06 CST 2008

Sep 4 22:33:18 localhost sshd[16376]: Failed password for root from 172.17.199.15 port 2883 ssh2
000000
    3、其他
    3.1一个conf脚本示例
I. More detailed swatch.conf example script 

 

# Swatch configuration file for constant monitoring

ignore /news/

# Server problems -- we consider this to be relatively low-priority, so we just get email.
watchfor /restart|panic|halt/
 bell
 mail=admin@foo.bar,subject=Log_Data_Server_Info

# SSH stuff -- also low-priority, but we still want to know when users are ssh'd in. 
watchfor /SSH|sshd2/
 mail=admin@foo.bar,subject=Log_Data_SSH

# We want to know if someone tries to SU root -- does everything (emails multiple people, 
# emails cell phone, pages Admin with pager code 911)
watchfor /root/
 bell
 mail=admin@foo.bar:other_admin@bar.foo:5551212@cell_messaging.com,subject=Log_Data_ROOT
 throttle 0:2:0,use=regex  # so it doesn't confuse the modem and interrupt paging
 exec chat -f /etc/chatscript.txt -v -s -T 911 < /dev/modem > /dev/modem

# router problems - does everything (emails multiple people, emails cell phone, pages Admin 
# with pager code 444)
watchfor /router/
 bell 
 mail=admin@foo.bar:other_admin@bar.foo:5551212@cell_messaging.com,subject=Log_Data_Router
 throttle 0:2:0,use=regex
 exec chat -f /etc/chatscript.txt -v -s -T 444 < /dev/modem > /dev/modem

# If adduser is run, could be critical -- does everything (emails multiple people, emails cell 
# phone, pages Admin with pager code 666)
watchfor /addgrp|adduser/
 bell
 mail=admin@foo.bar:other_admin@bar.foo:5551212@cell_messaging.com,subject=Log_Data_Adduser
 throttle 0:2:0,use=regex
 exec chat -f /etc/chatscript.txt -v -s -T 666 < /dev/modem > /dev/modem

# Bad login attempts -- mails us and pages Admin with pager code 888
watchfor /authentication failure/
 bell
 mail=admin@foo.bar:other_admin@bar.foo:5551212@cell_messaging.com,subject=Log_Data_Bad_Login
 throttle 0:2:0,use=regex
 exec chat -f /etc/chatscript.txt -v -s -T 888 < /dev/modem > /dev/modem

# end of swatch.conf

 

3.2 Swatch可以设置成开机后自动后台运行,只需要在rc.local加入一行:
/usr/bin/swatch -c /etc/swatch.conf - t /var/log/messages &


3.3如果希望Swatch监控多个日志文件,需要多次执行Swatch,如果每类文件的设置不同,相应的conf文件也不同。

3.3.1使用Swatch来自东禁止非法连接。(下面是参考,还没研究过)
http://cubic9.com/Linux/Swatch/
http://raijin.ddo.jp/pukiwiki/pukiwiki.php?%C9%D4%C0%B5%A5%A2%A5%AF%A5%BB%A5%B9%B4%C6%BB%EB
http://tobysoft.net/wiki/index.php?Ubuntu%2Fswatch

3.4 Swatch时时监视新增加的内容,使用 -t

The -t flag tells Swatch which file it should tail (monitor).

3.5 另一个conf例子:

Some important Swatch switches, listed alphabetically. See the sample config files for specific usage examples:

bell 
Make the console beep. You can change the number of beeps; default is 1.

continue 
If multiple watchfor sections contain a pattern which could occur in the same single log entry, then "continue" will tell Swatch to continue comparing its key patterns to the log entry even after it finds the first match. Take for example a watchfor section that contains both /root/ and /login/, and the log line "root: login successful" is generated. Swatch would normally just execute actions when it saw the first match -- "root" -- and then stop parsing that line of the log, thus effectively ignoring the occurrence of "login" in this case. "Continue" prevents this.

echo 
Dump flagged log entries to the console.

exec 
Execute whatever shell command follows. See section on chat for examples.

ignore 
We can tell Swatch to ignore the things we don't care about. The syntax for this is ignore /whatever/ where "whatever" is the pattern in question. The command and the pattern should be separated by spaces or tabs. Separate each item with the pipe character |.

mail 
Send email message to any number of addresses, separated by colons. For our convenience, we can make the subject line reflect the items flagged (see sample config file for syntax). The email message body will, by default, contain the full line of the log entry that triggered Swatch. 

throttle 
The throttle command keeps the action (whatever follows on the next line) from being executed too many times at once, which might happen if the event in question generates multiple lines in the log, which each contain the string we're watching for. So, we use throttle to suppress subsequent reportings of the same event for a specified period of time after the first instance of the event. The format is throttle HH:MM:SS (hours, minutes, and seconds) and the use=regex option tells Swatch to use the pattern specified in the watchfor line, as opposed to using the message body itself, which is the default. For example, the log messages: "sshd2[PID]: Local disconnected: Connection closed." and "sshd2[PID]: connection lost: 'Connection closed.'" use slightly different wording, so the default throttle settings would not work here. But if we include use=regex, then sshd2 is the determining string, and thus throttle will work correctly.

watchfor 
This is what we use to specify which log entries to watch for, and subsequently what to do in the instance of such an entry. Separate each item with the pipe character |. 

A sample Swatch configuration file: 

Expect to go back and tweak the config file a few times when you first begin using Swatch. You'll find that some patterns you specify in the watchfor sections will appear elsewhere in subtle ways, resulting in unintended flagging by Swatch. For example, if you specify "watchfor /su/" intending to flag the su command (someone trying to switch to another user) then Swatch will flag that, but will also trigger on any log line that contains the word "succeeded" (which appears in the event of a successful, legitimate login!) Try using "watchfor /root/" instead. Remember that you can test to see if Swatch is listening and behaving properly by using the "logger x" command.

 

# Sample Swatch configuration file for constant monitoring.
ignore /news/

watchfor /restart|panic|halt/ 
 bell 
 mail=admin@foo.bar:other_admin@bar.foo,subject=Log_Data_Crash

watchfor /SSH|sshd2/    # watch for both the session and the daemon
 echo 
 bell 
 throttle 0:2:0,use=regex  # in case of multiple attempts in rapid succession; 
      # ssh also generates multiple log lines even for a
     # single successful login
 mail=admin@foo.bar,subject=Log_Data_SSH

watchfor /blah|blah/ etc... 

# End of script (a more detailed sample config file is included at the end of this document)


You can separate different events and have Swatch perform different alerting routines, based on severity, type, etc.. For example, server problems like reboots, kernel panics, etc. could be set up to result in an email with subject line "LogData-Server" while suspicious login attempts could have subject line "LogData-AuthFail," etc. See the complete configuration example at the end of this document for more examples. Breaking things down like this makes it easier for you to sort the emails generated by Swatch, and you can tell from one glance at your inbox what kinds of things have been happening on your network. 

A good idea is to have redundant alert methods available to Swatch, especially for the more critical events. For example, specify multiple email addresses (preferably belonging to multiple people who can find you) in the more important watchfor sections. 

 

3.6另一个conf例子

Swatch Rules

The main configuration file is /etc/swatch/swatch.conf. Here is a good example:

File: /etc/swatch/swatch.conf
# Global swatch filter file

# To ignore a IP-range
ignore /216\.239\.37\./

# Invalid SSH Login Attempts
watchfor /(: [iI]nvalid [uU]ser )(.*)( from )(.*)$/
        throttle threshold=3,delay=0:1:0,key=$4
        mail addresses=admin\@domain.com,subject="SSH:\ Invalid\ User\ Access-IPTables\ Rule\ Added"
        exec "/sbin/iptables -A swatch_rejects -s $4 -j DROP"

# Failed SSH Login Attempts
watchfor /(: [fF]ailed password for )(.*)( from )(.*)( port )(.*)$/
        throttle threshold=3,delay=0:1:0,key=$4
        mail addresses=admin\@domain.com,subject="SSH:\ Invalid\ User\ Access-IPTables\ Rule\ Added"
        exec "/sbin/iptables -A swatch_rejects -s $4 -j DROP"

# Invalid SSH Login Attempts. Another one - just formed differently
watchfor /([aA]uthentication [fF]ailure for [iI]llegal [uU]ser )(.*)( from )(.*)$/
        throttle threshold=3,delay=0:1:0,key=$4
        mail addresses=admin\@domain.com,subject="SSH:\ Invalid\ User\ Access-IPTables\ Rule\ Added"
        exec "/sbin/iptables -A swatch_rejects -s $4 -j DROP"

A little explanation of whats being done:

ignore /216\.239\.37\./

This is to ignore, in this case, a IP-range. Very usefull to minimize the possibility that you lock yourself out.

watchfor /(: [iI]nvalid [uU]ser )(.*)( from )(.*)$/ watchfor /(: [fF]ailed password for )(.*)( from )(.*)( port )(.*)$/ watchfor /([aA]uthentication [fF]ailure for [iI]llegal [uU]ser )(.*)( from )(.*)$/

This is to search our logs for the string between //. The parens in the first watchfor are important - they break up the log file line into chucks that are used for $1,$2,$3, ... $n. In this case, for example, $1 is ": Invalid User "; $2 is all the junk in the first (.*); $3 is " from "; and $4 is all the junk in the second (.*) -- which happens to be the IP address you want. Note: the $ at the end signifies end of line. Also, note that the $4 works in both the first and third watchfor code block -- this is pure coincidence and you may need to change the $4 to a different paren set if you are working with your own custom watchfor block.

throttle threshold=3,delay=0:1:0,key=$4

  • The "key" tell swatch how to identify the log line. We can't use the whole string here, because the same attacker (ie the same IP) will probably try multiple user names. The key can refer to one of the parens set in the search string (here, $4 = the IP).
  • The "threshold" is the number of times swatch need to see the "key" to execute the actions below.
  • The "delay" is the validity of each "key". When older that 'delay', the "key" is discarded. Use a syntax like HH:MM:SS.

Note: If this does work in 3.1.1, it may not work with loggers such as metalog, because it says instead "Last output repeated N times" So naturally swatch won't find multiple occurances often in those cases.

mail addresses=admin\@domain.com,subject="SSH:\ Invalid\ User\ Access-IPTables\ Rule\ Added"

Mail a user stating that a new rule has been added to iptables.

exec "/sbin/iptables -A swatch_rejects -s $4 -j DROP"

Add the offending ip to "swatch_rejects" and drop all future incoming packets from that address. If you are using shorewall, you can define in this way:

exec "/sbin/shorewall drop $4"

3.7

Another way to control swatch to a greater degree is to specify what time of day a given action may be performed. You can do this by sticking a “when=” option after any action. For example, below I've got a .swatchrc entry for a medium-importance event I want to know about via console messages during weekdays, but I'll need e-mail messages to know about it during the weekend. To do this I set the when option:

/file system full/ echo=red mail addresses=mick\@visi.com, subject=Volume_Full,when=7-1:1-24

The syntax of the when= option is when=range_of_days:range_of_hours. Thus, we see that any time the message “file system full” is logged, swatch will echo the log entry to the console in red ink. It will also send e-mail, but only if it's Saturday (“7”) or Sunday (“1”).

 

说明:

 

 

过滤 
    日志具有无可替代的价值,但不幸的是它们经常被忽略,因为系统管理员在并不充裕的时间里难以查看大量的 
信息。标准的日志功能不能自动过滤和检查日志记录,并提供系统管理员所需要的信息。下面我将简述如何过滤并 
得到所需要的信息,然后介绍一个日志工具。 
    本文的第一部份将讲述如何制定过滤计划和所需要的信息,第二部份是日志过滤的实现。本文介绍的日志工具 
是Todd Atkins开发的swatch。


开始 
    首先应该制定计划。制定日志计划的步骤有三步:第一步详细说明你需要知道什么,确定要从系统日志中得到 
什么信息;第二步是确定哪些日志包含有这些信息;第三步是制定可以得到这些信息的触发器。 
    例如,假设你非常关心sendmail的安全,特别想知道是否有人试图使用你的邮件服务器作垃圾邮件转发。另外 
你还想知道是否有人试图通过SMTP命令(如expn、vrfy)未经授权获取相关信息。这些就是我们第一步所要确定的 
内容。 
    第二步是选择信息源,或包含有所城信息的日志文件。可以通过系统日志配置文件/etc/syslog.conf了解所需 
信息被记录到哪里。例如,以下是电子邮件日志存放位置的配置: 
homer#cat /etc/syslog.conf | grep mail 
mail.debug ifdef(`LOGHOST', /var/log/syslog, @loghost) 
    最后一步就是定义触发器,即指定所需要记录的日志信息。在这里我们需要的是两个针对sendmail的触发器。 
        1、试图将邮件服务器作为邮件转发器非授权IP地址。 
        2、试图使用已经被关闭的命令(如expn)的用户/或IP地址。 
    要确定触发器的定义正确与否,可模拟触发事件,并用/usr/bin/tail -f命令监视日志文件。对于第一个触 
发器(非授权IP地址试图使用邮件服务器作邮件转发),可从一个非授权IP地址尝试使用邮件服务器作邮件转发, 
同时通过/usr/bin/tail -f命令查看日志记录。 
Oct 3 14:48:51 homer sendmail[6704]: OAA06704: 
ruleset=check_rcpt,arg1=bsmith@domain.com, relay=foo@moo.com 
[206.54.252.1],reject=550 bsmith@domain.com... Relaying denied 
    我们可以看到在moo.com上有人在试图通过我们的邮件服务器转发邮件,这很可能是垃圾邮件的信号。这就是 
一个非授权邮件转发的日志记录触发器。请注意信息中还包含有IP地址和域名。 
    现在,测试一下第二个触发器(非授权使用expn命令)。登录到SMTP端口并执行expn命令,同时通过 
/usr/log/tail -f /var/log/syslog命令查看日志记录。 
Oct 2 20:28:37 homer sendmail[5453]: NOQUEUE: foo@moo.com[206.54.252.1]: expn bsmith [rejected] 
    我们可以看到在moo.com上有人试图查询用户名bsmith。在使用expn命令时将激活这个触发器。请注意信息中 
还包含有IP地址和域名。 
    上面我们简述了制定日志过滤的三个步骤。首先是确定需要什么信息:非授权使用邮件服务器作邮件转发和 
非授权使用expn命令。然后是确定包含这些信息的日志:/var/log/syslog。最后,通过模拟事件验证日志触发 
器。现在是我们建立自动化过滤器的时候了。


SWATCH 
    SWATCH (The Simple WATCHer and filer) 是Todd Atkins开发的用于实时监视日志的PERL程序。Swatch利 
用指定的触发器监视日志记录,当日志记录符合触发器条件时,swatch会按预先定义好的方式通知系统管理员。 
在本文的例子中,我们需要swatch在有人攻击sendmail时报警。 
    Swatch非常容易安装。它是一个PERL程序,无需编译。Swatch有一个很有用的安装脚本,将所有的库文件、 
手册页和PERL文件复制到相应目录下。安装完成后,只要创建一个配置文件,就可以运行程序了。Swatch的下载 
网址:ftp://ftp.stanford.edu/general/security-tools/swatch 
    配置文件swatchrc是swatch软件的重点。这个文本文件告诉swatch需要监视什么日志,需要寻找什么触发器, 
和当触发时所要执行的动作。当swatch发现到与swatchrc中定义的触发器正则表达式相符时,它将执行在swatchrc 
中定义的通知程序。Swatch通过使用/usr/bin/tail -f实时监视日志文件。 
    现在让我们为在上面提到的sendmail日志创建一个swatchrc文件。目的是当有人试图攻击我们的邮件服务器时 
sendmail将通过电子邮件通知我们。swatchrc文件的内容格式如下。它包含了四个用制表符分隔的字段,前面两个 
字段是必须的,而后面两个字段是可选的。 
    第一个字段的格式是: 
    /pattern/pattern/ 
    其中的"pattern"代表一个swatch将要进行搜索匹配的正则表达式,也就是我们的触发器。 
    第二个字段的格式是: 
    Action,action... 
    其中的"action"是当表达式匹配时所要执行的动作。Swatch允许指定包括email、呼叫或任何指定的执行文件。 
    第三个字段(可选)的格式是: 
    HH:MM:SS 
    HH是小时数,MM是分钟数,SS是秒数。这个时间间隔是设置swatch忽略同一匹配表达式的最大时间。例如,如 
果你定义时间间隔为5分钟,swatch在这个时间间隔内对同一匹配表达式将只报告一次,即使该表达式可能已匹配了 
20次。 
    第四个字段(如果使用了第三个字段,则此字段是必需的)是一个时间标签,格式为start:length。它定义了 
在通知消息中时间标签的位置和长度。 
    在这个sendmail实例中,我们将要为上面的两个触发器创建含有相应匹配表达式的swatchrc文件。我们希望只 
要其中有一个表达式匹配,系统将向abuse@ourcompany.com发送包含匹配记录的通知电子邮件。然而,我们也要避 
免被过多的警告信息所淹没。例如,如果攻击者试图在一分钟内转发1000封电子邮件,可能产生大量的通知消息。 
因此,我们决定设置时间间隔为5分钟。这样,不管在5分钟内有多少次匹配同一个表达式,都只会发送一封通知邮 
件。下面就是我们最终创建的swatchrc文件内容: 
    /Relaying denied|expn/ echo=normal,mail=abuse@ourcompany.net 5:00 0:16 
    第一个字段内容为"/Relaying denied|expn/"。如果swatch发现匹配了其中的任何表达式,它将发送一个警告 
信息。第一个表达式"Relaying denied"对应于我们上面提到的第一个触发器,此时的日志将记录有人正试图进行 
非授权邮件转发。第二个表达式"expn"则对应于第二个触发器,此时的日志将记录有人正试图执行expn命令。这两 
个触发器的具体情况请回顾本文的第一部份。 
    第二个字段内容为"echo=nomal,mail=abuse@company.com", 
    表示将发送包含匹配日志记录的电子邮件到abuse@ourcompany.com。 
    第三和第四个字段(可选字段)内容为"5:00 0:16",表示在5分钟内不会重复同一个警告消息,并定义了时间 
标签的位置和长度。 
    现在我们已正确配置了swatchrc文件,最后一个步骤就是启动swatch进程。Swatch启动时可以带很多参数,但 
使用通常如下格式启动它就可以了: 
    /usr/local/bin/swatch -c /var/log/syslogrc -t /var/log/syslog & 
    -c参数用于指定配置文件,-t参数指定实时监视的日志文件,"&"使swatch在后台运行。启动后,swatch产生 
子进程,因此swatch是以两个进程运行的,在停止swatch时必须杀掉两个进程。现在,sendmail的日志记录将被自 
动进行过滤,任何时间只要有人想利用你的sendmail系统,你接收到包含了匹配日志记录的电子邮件。


总结 
    日志是很强大的工具,然而它的大量数据也很容易淹没我们。如果我们没有足够的时间去检查数以兆计的数据 
时,很可能会忽略那些有用的资料。日志自动化过滤系统可以帮助我们解决这个问题。这些自动化过滤系统将我们 
所需要的信息实时地通知我们。希望本文能对如何定制你自己的日志文件自动过滤器有一定的帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HarkerYX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值