CentOS 6.X Denyhosts配置

Denyhosts

This howto will show you how to install and configure Denyhosts on your server or desktop system to help further prevent unwanted attacks or access to your systems.

它会分析/var/log/secure(redhat,Fedora Core)等日志文件,当发现同一IP在进行多次SSH密码尝试时就会记录IP到/etc/hosts.deny文件,从而达到自动屏蔽该IP的目的。 

Applicable to Centos Versions:

  • Centos 5.x

  • Centos 6.x

Requirements

Explanation of requirements.

  1. Root access to the machine(s) in question.

  2. A cup of fine Central American coffee

环境监察

首选检查Sshd是否支持 Tcpwrap,只有支持Tcpwrap才可以安装Denyhost
# ldd /usr/sbin/sshd |grep wrap

libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f622e88d000)        //出现此信息时表示支持

再检查 Python的版本,Python2.3以上版本可以直接安装
# python -V
Python 2.6.6

均达到要求

Doing the Work

Basic description of what will be done and what is expected.

  1. First, I suggest you implement some or all of the security measures outlined in zcats’ well written howto on securing SSH. Click the link below to be redirected:

zcats'"securing SSH" Howto

Installation of Denyhosts:

]# yum install denyhosts   //在线安装denyhosts
(note: if you have errors at this stage please visit #fedora or #centos on Freenode IRC depending what OS you're running.)

Configuration of Denyhosts:

]# vi /etc/denyhosts.conf    //创建配置文件,最后有示例配置文件
(note: i've attached a sample working config here at the bottom that you can use to tune your own, verbose explanations are included within the denyhosts.conf file.)

Starting the service and marking it to run on each system reboot:

]# service denyhosts start; chkconfig --level 2345 denyhosts on    //开机启动
(note: could take a minute or 2 start start initially, give this command at least 2-3 min to return you to a bash prompt)

Allowing yourself unrestricted access with the allowed-hosts and hosts.allow lists:

]# vi /var/lib/denyhosts/allowed-hosts
]# vi /etc/hosts.allow
//IP地址白名单:将IP地址加入这两个文件中,不会受拦截限制
(note: you'll want to add in these 2 files the IP(s) you will use to connect to your system that's running Denyhosts so that you aren't inadvertently denied access to your own system(s).)

Configuration file sample for Denyhosts:  //示例配置文件

 
       ############ THESE SETTINGS ARE REQUIRED ###################################################################################### SECURE_LOG: the log file that contains sshd logging info# if you are not sure, grep "sshd:" /var/log/*## The file to process can be overridden with the --file command line# argument# SSH日志文件# Redhat or Fedora:SECURE_LOG = /var/log/secure## Mandrake, FreeBSD or OpenBSD: #SECURE_LOG = /var/log/auth.log## SuSE:#SECURE_LOG = /var/log/messages## Mac OS X (v10.4 or greater - #   also refer to:   http://www.denyhosts.net/faq.html#macos#SECURE_LOG = /private/var/log/asl.log## Mac OS X (v10.3 or earlier):#SECURE_LOG=/private/var/log/system.log################################################################################################################################################### HOSTS_DENY: the file which contains restricted host access information# 将阻止IP写入到hosts.deny# Most operating systems:HOSTS_DENY = /etc/hosts.deny# Defines the active ban list.# Some BSD (FreeBSD) Unixes:#HOSTS_DENY = /etc/hosts.allow## Another possibility (also see the next option):#HOSTS_DENY = /etc/hosts.evil################################################################################################################################################# PURGE_DENY: removed HOSTS_DENY entries that are older than this time#             when DenyHosts is invoked with the --purge flag##      format is: i[dhwmy]#      Where 'i' is an integer (eg. 7) #            'm' = minutes#            'h' = hours#            'd' = days#            'w' = weeks#            'y' = years# # never purge:
# 过多久后清除已阻止IPPURGE_DENY = 6y# I figure the average hardware lifecycle of servers is 2 years or less# so 6 years should be plenty if i want an IP permanently banned. # purge entries older than 1 week#PURGE_DENY = 1w## purge entries older than 5 days#PURGE_DENY = 5d## For the default Fedora Extras install, we want timestamping but no# expiration (at least by default) so this is deliberately set high.# Adjust to taste.#PURGE_DENY = 4w################################################################################################################################################ PURGE_THRESHOLD: defines the maximum times a host will be purged.  # Once this value has been exceeded then this host will not be purged. # Setting this parameter to 0 (the default) disables this feature.## default: a denied host can be purged/re-added indefinitelyPURGE_THRESHOLD = 1## a denied host will be purged at most 2 times. #PURGE_THRESHOLD = 2 # This step assures a repeat offender is forever banned and maintained in /etc/hosts.deny################################################################################################################################################ BLOCK_SERVICE: the service name that should be blocked in HOSTS_DENY# # man 5 hosts_access for details## eg.   sshd: 127.0.0.1  # will block sshd logins from 127.0.0.1# 阻止服务名# To block all services for the offending host:BLOCK_SERVICE = ALL# To block only sshd:#BLOCK_SERVICE  = sshd# To only record the offending host and nothing else (if using# an auxilary file to list the hosts).  Refer to: # http://denyhosts.sourceforge.net/faq.html#aux#BLOCK_SERVICE =    # I've set this to "ALL" because if any user is attempting malicious entry to the system,# I want all potential avenues of damage to be cut-off instantly. Bans can easily be lifted,# a compromised system could rob you of a lifetime of work and effort.################################################################################################################################################ DENY_THRESHOLD_INVALID: block each host after the number of failed login # attempts has exceeded this value.  This value applies to invalid# user login attempts (eg. non-existent user accounts)# //无效用户(在/etc/passwd未列出)登录失败次数DENY_THRESHOLD_INVALID = 1# I've set this value to 1 attempt for a user without an account on the system# attempting to login, they obviously have no right even trying to login so they# should be blocked immediately.################################################################################################################################################ DENY_THRESHOLD_VALID: block each host after the number of failed # login attempts has exceeded this value.  This value applies to valid# user login attempts (eg. user accounts that exist in /etc/passwd) except# for the "root" user# 允许普通用户登录失败的次数DENY_THRESHOLD_VALID = 3# I've set known user login attempts to 3 for increased security in a login/pass scenario.# For added security you can restrict access only to users with the proper ssh id_dsa or# id_rsa keys. (see fedorasolved.org for more info on setting this up.)################################################################################################################################################ DENY_THRESHOLD_ROOT: block each host after the number of failed # login attempts has exceeded this value.  This value applies to # "root" user login attempts only.# 允许root登录失败的次数DENY_THRESHOLD_ROOT = 1# Since i've set my sshd_config to refuse root logins, I want this set to only 1 attempt# at root login before the offending IP is banned since no one should be logging in as root.################################################################################################################################################ DENY_THRESHOLD_RESTRICTED: block each host after the number of failed # login attempts has exceeded this value.  This value applies to # usernames that appear in the WORK_DIR/restricted-usernames file only.# 针对有限制的用户DENY_THRESHOLD_RESTRICTED = 1# This refers to /var/lib/denyhosts/hosts-restricted, I don't want these people logging in# at all so i set the failed threshold to 1 attempt before banning the IP.################################################################################################################################################ WORK_DIR: the path that DenyHosts will use for writing data to# (it will be created if it does not already exist).  ## Note: it is recommended that you use an absolute pathname# for this value (eg. /home/foo/denyhosts/data)# 将deny的host或ip纪录到Work_dir中WORK_DIR = /var/lib/denyhosts# This defines the working directory for Denyhosts################################################################################################################################################ SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS## SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES|NO# If set to YES, if a suspicious login attempt results from an allowed-host# then it is considered suspicious.  If this is NO, then suspicious logins # from allowed-hosts will not be reported.  All suspicious logins from # ip addresses that are not in allowed-hosts will always be reported.#SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES# This (YES) setting monitors all IPs (even allowed IPs) for suspicious connections# or attempts and logs/reports this activity for investigation. ############################################################################################################################################## HOSTNAME_LOOKUP## HOSTNAME_LOOKUP=YES|NO# If set to YES, for each IP address that is reported by Denyhosts,# the corresponding hostname will be looked up and reported as well# (if available).# 是否做域名反解HOSTNAME_LOOKUP=YES# This setting allows for hostname lookup on all IPs reported by denyhosts.############################################################################################################################################## LOCK_FILE## LOCK_FILE=/path/denyhosts# If this file exists when DenyHosts is run, then DenyHosts will exit# immediately.  Otherwise, this file will be created upon invocation# and deleted upon exit.  This ensures that only one instance is# running at a time.## Redhat/Fedora:
# 将DenyHOts启动的pid纪录到LOCK_FILE中,已确保服务正确启动,防止同时启动多个服务。LOCK_FILE = /var/lock/subsys/denyhosts## Debian#LOCK_FILE = /var/run/denyhosts.pid## Misc#LOCK_FILE = /tmp/denyhosts.lock#######################################################################       ############ THESE SETTINGS ARE OPTIONAL ##################################################################################### ADMIN_EMAIL: if you would like to receive emails regarding newly# restricted hosts and suspicious logins, set this address to # match your email address.  If you do not want to receive these reports# leave this field blank (or run with the --noemail option)## Multiple email addresses can be delimited by a comma, eg:# ADMIN_EMAIL = [email protected], [email protected], [email protected]# 设置管理员邮件地址ADMIN_EMAIL = put the email address here you want mailed when new IP entries are added.################################################################################################################################################# SMTP_HOST and SMTP_PORT: if DenyHosts is configured to email # reports (see ADMIN_EMAIL) then these settings specify the# email server address (SMTP_HOST) and the server port (SMTP_PORT)# #SMTP_HOST = localhost#SMTP_HOST = smtp1.your_server_here.netSMTP_PORT = 25################################################################################################################################################ # SMTP_USERNAME and SMTP_PASSWORD: set these parameters if your # smtp email server requires authentication##SMTP_USERNAME=foo#SMTP_PASSWORD=bar################################################################################################################################################ SMTP_FROM: you can specify the "From:" address in messages sent# from DenyHosts when it reports thwarted abuse attempts#SMTP_FROM = DenyHosts <denyhosts@your_site.com>################################################################################################################################################# SMTP_SUBJECT: you can specify the "Subject:" of messages sent# by DenyHosts when it reports thwarted abuse attemptsSMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]############################################################################################################################################### SMTP_DATE_FORMAT: specifies the format used for the "Date:" header# when sending email messages.## for possible values for this parameter refer to: man strftime## the default:#SMTP_DATE_FORMAT = %a, %d %b %Y %H:%M:%S %z############################################################################################################################################### SYSLOG_REPORT## SYSLOG_REPORT=YES|NO# If set to yes, when denied hosts are recorded the report data# will be sent to syslog (syslog must be present on your system).# The default is: NO#SYSLOG_REPORT=YES##SYSLOG_REPORT=NO# Obvious.############################################################################################################################################## ALLOWED_HOSTS_HOSTNAME_LOOKUP## ALLOWED_HOSTS_HOSTNAME_LOOKUP=YES|NO# If set to YES, for each entry in the WORK_DIR/allowed-hosts file,# the hostname will be looked up.  If your versions of tcp_wrappers# and sshd sometimes log hostnames in addition to ip addresses# then you may wish to specify this option.#ALLOWED_HOSTS_HOSTNAME_LOOKUP=YES# This section refers to /var/lib/denyhosts/allowed-hosts file, which adds in a hostname# lookup into the log entry.############################################################################################################################################ # # AGE_RESET_VALID: Specifies the period of time between failed login# attempts that, when exceeded will result in the failed count for # this host to be reset to 0.  This value applies to login attempts # to all valid users (those within /etc/passwd) with the # exception of root.  If not defined, this count will never# be reset.## See the comments in the PURGE_DENY section (above) # for details on specifying this value or for complete details # refer to:  http://denyhosts.sourceforge.net/faq.html#timespec#AGE_RESET_VALID=5m# This section refers to resetting the allowed login attempts to 0 for valid users# on the system after being locked out or using any of the 3 given attempts in the# "DENY_THRESHOLD_VALID" variable above. Currently, this is set to reset to 0 after# 5 minutes of inactivity (i.e. logging into the system).############################################################################################################################################ # # AGE_RESET_ROOT: Specifies the period of time between failed login# attempts that, when exceeded will result in the failed count for # this host to be reset to 0.  This value applies to all login # attempts to the "root" user account.  If not defined,# this count will never be reset.## See the comments in the PURGE_DENY section (above) # for details on specifying this value or for complete details # refer to:  http://denyhosts.sourceforge.net/faq.html#timespec#AGE_RESET_ROOT=6y# This essentially is another step to make *sure* a specific banned IP *stays* banned.############################################################################################################################################# # AGE_RESET_RESTRICTED: Specifies the period of time between failed login# attempts that, when exceeded will result in the failed count for # this host to be reset to 0.  This value applies to all login # attempts to entries found in the WORK_DIR/restricted-usernames file.  # If not defined, the count will never be reset.## See the comments in the PURGE_DENY section (above) # for details on specifying this value or for complete details # refer to:  http://denyhosts.sourceforge.net/faq.html#timespec#AGE_RESET_RESTRICTED=25d# This section refers to login attempts made by the IPs listed in the# /var/lib/denyhosts/hosts-restricted file. This lets us specify a time period# after which the login attempts defined in the variable DENY_THRESHOLD_RESTRICTED# is reset to 0 failed attempts.############################################################################################################################################ ## AGE_RESET_INVALID: Specifies the period of time between failed login# attempts that, when exceeded will result in the failed count for# this host to be reset to 0.  This value applies to login attempts # made to any invalid username (those that do not appear # in /etc/passwd).  If not defined, count will never be reset.## See the comments in the PURGE_DENY section (above) # for details on specifying this value or for complete details # refer to:  http://denyhosts.sourceforge.net/faq.html#timespec#AGE_RESET_INVALID=10d# Same as DENY_THRESHOLD_RESTRICTED above but for the variable DENY_THRESHOLD_INVALID# which defines login attempts by usernames nonexistent on the system.############################################################################################################################################## RESET_ON_SUCCESS: If this parameter is set to "yes" then the# failed count for the respective ip address will be reset to 0# if the login is successful.  ## The default is RESET_ON_SUCCESS = no#RESET_ON_SUCCESS = yes# This basically tells us if a valid user on the system accidentally fails logging# in twice but then has success on the third attempt that we should immediately reset# his faulty login attempt threshold to 0 again. (even admins forget logins ;))############################################################################################################################################# PLUGIN_DENY: If set, this value should point to an executable# program that will be invoked when a host is added to the# HOSTS_DENY file.  This executable will be passed the host# that will be added as it's only argument.##PLUGIN_DENY=/usr/bin/true############################################################################################################################################### PLUGIN_PURGE: If set, this value should point to an executable# program that will be invoked when a host is removed from the# HOSTS_DENY file.  This executable will be passed the host# that is to be purged as it's only argument.##PLUGIN_PURGE=/usr/bin/true############################################################################################################################################### USERDEF_FAILED_ENTRY_REGEX: if set, this value should contain# a regular expression that can be used to identify additional# hackers for your particular ssh configuration.  This functionality# extends the built-in regular expressions that DenyHosts uses.# This parameter can be specified multiple times.# See this faq entry for more details:#    http://denyhosts.sf.net/faq.html#userdef_regex##USERDEF_FAILED_ENTRY_REGEX=########################################################################   ######### THESE SETTINGS ARE SPECIFIC TO DAEMON MODE  ################################################################################### DAEMON_LOG: when DenyHosts is run in daemon mode (--daemon flag)# this is the logfile that DenyHosts uses to report it's status.# To disable logging, leave blank.  (default is: /var/log/denyhosts)# 自己的日志文件 DAEMON_LOG = /var/log/denyhosts## disable logging:#DAEMON_LOG = ############################################################################################################################################### # DAEMON_LOG_TIME_FORMAT: when DenyHosts is run in daemon mode # (--daemon flag) this specifies the timestamp format of# the DAEMON_LOG messages (default is the ISO8061 format:# ie. 2005-07-22 10:38:01,745)## for possible values for this parameter refer to: man strftime## Jan 1 13:05:59   DAEMON_LOG_TIME_FORMAT = %b %d %H:%M:%S## Jan 1 01:05:59 #DAEMON_LOG_TIME_FORMAT = %b %d %I:%M:%S####################################################################### ######################################################################## # DAEMON_LOG_MESSAGE_FORMAT: when DenyHosts is run in daemon mode # (--daemon flag) this specifies the message format of each logged# entry.  By default the following format is used:## %(asctime)s - %(name)-12s: %(levelname)-8s %(message)s## Where the "%(asctime)s" portion is expanded to the format# defined by DAEMON_LOG_TIME_FORMAT## This string is passed to python's logging.Formatter contstuctor.# For details on the possible format types please refer to:# http://docs.python.org/lib/node357.html## This is the default:DAEMON_LOG_MESSAGE_FORMAT = %(asctime)s - %(name)-12s: %(levelname)-8s %(message)s######################################################################## ######################################################################### DAEMON_SLEEP: when DenyHosts is run in daemon mode (--daemon flag)# this is the amount of time DenyHosts will sleep between polling# the SECURE_LOG.  See the comments in the PURGE_DENY section (above)# for details on specifying this value or for complete details# refer to:    http://denyhosts.sourceforge.net/faq.html#timespec# #DAEMON_SLEEP = 30s################################################################################################################################################# DAEMON_PURGE: How often should DenyHosts, when run in daemon mode,# run the purge mechanism to expire old entries in HOSTS_DENY# This has no effect if PURGE_DENY is blank.# 该项与PURGE_DENY 设置成一样,也是清除hosts.denied ssh 用户的时间DAEMON_PURGE = 1h########################################################################   #########   THESE SETTINGS ARE SPECIFIC TO     ##########   #########       DAEMON SYNCHRONIZATION         ############ Note: I do *not* recommend using this "feature". With security it's good to be paranoid.# The function of this setting is to talk to other servers and share ban lists.# I do not want other remote systems altering ban settings for core security# programs (i.e. Denyhosts).######################################################################### Synchronization mode allows the DenyHosts daemon the ability# to periodically send and receive denied host data such that# DenyHosts daemons worldwide can automatically inform one# another regarding banned hosts.   This mode is disabled by# default, you must uncomment SYNC_SERVER to enable this mode.## for more information, please refer to: #        http:/denyhosts.sourceforge.net/faq.html#sync ################################################################################################################################################# SYNC_SERVER: The central server that communicates with DenyHost# daemons.  Currently, denyhosts.net is the only available server# however, in the future, it may be possible for organizations to# install their own server for internal network synchronization## To disable synchronization (the default), do nothing. ## To enable synchronization, you must uncomment the following line:#SYNC_SERVER = http://xmlrpc.denyhosts.net:9911################################################################################################################################################# SYNC_INTERVAL: the interval of time to perform synchronizations if# SYNC_SERVER has been uncommented.  The default is 1 hour.# #SYNC_INTERVAL = 1h################################################################################################################################################# SYNC_UPLOAD: allow your DenyHosts daemon to transmit hosts that have# been denied?  This option only applies if SYNC_SERVER has# been uncommented.# The default is SYNC_UPLOAD = yes##SYNC_UPLOAD = no#SYNC_UPLOAD = yes################################################################################################################################################# SYNC_DOWNLOAD: allow your DenyHosts daemon to receive hosts that have# been denied by others?  This option only applies if SYNC_SERVER has# been uncommented.# The default is SYNC_DOWNLOAD = yes##SYNC_DOWNLOAD = no#SYNC_DOWNLOAD = yes################################################################################################################################################### SYNC_DOWNLOAD_THRESHOLD: If SYNC_DOWNLOAD is enabled this parameter# filters the returned hosts to those that have been blocked this many# times by others.  That is, if set to 1, then if a single DenyHosts# server has denied an ip address then you will receive the denied host.## See also SYNC_DOWNLOAD_RESILIENCY##SYNC_DOWNLOAD_THRESHOLD = 10## The default is SYNC_DOWNLOAD_THRESHOLD = 3 ##SYNC_DOWNLOAD_THRESHOLD = 3################################################################################################################################################# SYNC_DOWNLOAD_RESILIENCY:  If SYNC_DOWNLOAD is enabled then the# value specified for this option limits the downloaded data# to this resiliency period or greater.## Resiliency is defined as the timespan between a hackers first known # attack and it's most recent attack.  Example:## If the centralized   denyhosts.net server records an attack at 2 PM # and then again at 5 PM, specifying a SYNC_DOWNLOAD_RESILIENCY = 4h # will not download this ip address.## However, if the attacker is recorded again at 6:15 PM then the # ip address will be downloaded by your DenyHosts instance.  ## This value is used in conjunction with the SYNC_DOWNLOAD_THRESHOLD # and only hosts that satisfy both values will be downloaded.  # This value has no effect if SYNC_DOWNLOAD_THRESHOLD = 1 ## The default is SYNC_DOWNLOAD_RESILIENCY = 5h (5 hours)## Only obtain hackers that have been at it for 2 days or more:#SYNC_DOWNLOAD_RESILIENCY = 2d## Only obtain hackers that have been at it for 5 hours or more:#SYNC_DOWNLOAD_RESILIENCY = 5h########################################################################

Troubleshooting / How To Test

Having trouble with anything above? Here’s some hints that might help.

  1. “Command not found.” message even though you’re logged in as the “root” user?:

]$ use one of these 3 methods when logging in as root to get roots full working environment:]$ su - | su --login | su -l

Commands used were: yum, vi, service, chkconfig and su.

If you had a problem with or didn't understand one of these commands, I suggest you read the manpage. example:]# man yum

Common Problems & Fixes

Problems getting proper answers in IRC or forums? Read the outline here for tips on getting better answers by asking smarter questions.

More Information

Additional information or notes.

Disclaimer

We test this stuff on our own machines, really we do. But you may run into problems, if you do, come to #centoshelp on irc.freenode.net

Added Reading


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章