代码改变世界

ssh使用相关

2020-05-30 15:18  youxin  阅读(889)  评论(0编辑  收藏  举报

修改ssh默认端口
1 . 登录服务器,打开sshd_config文件

[root@centos ~]# vim /etc/ssh/sshd_config
1
2 . 找到#Port 22,默认是注释掉的,先把前面的#号去掉,再插入一行设置成你想要的端口号,注意不要跟现有端口号重复

......

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
Port 22
Port 10022
.....
 
SSH默认监听端口是22,如果你不强制说明别的端口,”Port 22”注不注释都是开放22访问端口。上面我保留了22端口,防止之后因为各种权限和配置问题,导致连22端口都不能访问了,那就尴尬了。等一切都ok了,再关闭22端口。

Ok,继续,我增加了10022端口,大家修改端口时候最好挑10000~65535之间的端口号,10000以下容易被系统或一些特殊软件占用,或是以后新应用准备占用该端口的时候,却被你先占用了,导致软件无法运行。

3 . 重启SSH服务,最好也重启下服务器

systemctl restart sshd
shutdown -r now
 


4 . 尝试通过10022端口登录SSH,或者进入该服务器直接本地访问SSH如下:

[root@centos7 ~]#ssh root@localhost -p 10022
1
如果成功,说明10022已经完全可以使用了,接下来你就可以根据上述步骤把sshd_config的Port22注释掉就OK了,大工造成
————————————————

centos7 SSH防暴力破解五种方法

 

什么是暴力破解,简单来说就是对一个服务器进行无数次尝试登陆,并用不同的密码进行登陆直到可以登陆成功。暴力破解的基本步骤可以分为以下几步:

  1. 找到对应的linux服务器 Ip地址
  2. 扫描端口号:22 nmap扫描端口
  3. 开始暴力破解 : 一般root 破解你的密码 登录你的机器 破坏 盗取你的重要的数据

对于这种情况我们有以下5种解决办法:

    1. 将密码设置复杂,长度大于8位或者最好大于14位,密码的复杂度:由大小写字母以及字符和数字组成。 0-9 a-z A-Z
      @!#$%*. 等等。
    2. 更改端口号,默认的端口是sshd(22),修改默认端口号。
    3. 不用root用户登陆(禁止root用户登陆),使用其他用户登陆并且拥有root用户权限。
    4. sshd服务,直接编写脚本检查/var/log/secure 内登录失败次数超过某个阈值的ip并将它添加到/etc/hosts.deny(fail2ban的优点更多)
    5. 使用fail2ban,起到登录失败多次后直接禁止某个时间段此ip登陆。

方法一

收集 /var/log/secure 里面的信息,若是某个IP 链接次数超过一定次数 ,则把此ip记录到/etc/hosts.deny里面。
先把始终允许的IP填入 /etc/hosts.allow这很重要!比如:
sshd:19.16.18.1:allow
sshd:19.16.18.2:allow

vi /usr/local/bin/secure_ssh.sh

创建脚本

#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /usr/local/bin/black.list
for i in `cat  /usr/local/bin/black.list`
do
  IP=`echo $i |awk -F= '{print $1}'`
  NUM=`echo $i|awk -F= '{print $2}'`
  if [ ${#NUM} -gt 1 ]; then
    grep $IP /etc/hosts.deny > /dev/null
    if [ $? -gt 0 ];then
      echo "sshd:$IP:deny" >> /etc/hosts.deny
    fi
  fi
done

通过crontab来执行,每天的1点1分执行一次。

crontab -e
1 * * * *  sh /usr/local/bin/secure_ssh.sh

方法二

denyhosts类似file2ban

Denyhosts是一个由Linux系统管理员运行,用来阻止SSH服务器攻击的python脚本(参考:Denyhosts官网http://denyhosts.sourceforge.net/)。

  在服务器安全日志(Centos:/var/log/secure;Ubutun:/var/log/auth.log)里,可以查看到访问服务器的记录。在受到不明IP多次访问时,我们可以通过将允许访问的IP添加至系统白名单(/etc/hosts.allow),或者将禁止的IP添加到黑名单(/etc/hosts.deny),来限制访问服务器的IP;但是攻击者一般都是通过不同IP对服务器进行访问,这样就对阻止攻击造成很大的麻烦。Dneyhosts就是一个自动查看分析安全日志,将符合设定禁止条件的IP添加到/etc/hosts.deny的脚本程序。

下载后安装:

python setup.py install

 

源码里面有个README.md 文件说明了用法。

vim  /etc/denyhosts.conf

SECURE_LOG = /var/log/secure ( denyhosts.conf默认不是这个,我们用的centos要修改这行)
#ssh 日志文件,它是根据这个文件来判断的。

HOSTS_DENY = /etc/hosts.deny
#控制用户登陆的文件

# never purge:
PURGE_DENY = (默认是这个,我们改成下面的)

PURGE_DENY = 10m
#过 多久后清除已经禁止的

#
# 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
#

 


BLOCK_SERVICE  = sshd
#禁止 的服务名

DENY_THRESHOLD_INVALID = 1
#允许无 效用户失败的次数

DENY_THRESHOLD_VALID = 10
#允 许普通用户登陆失败的次数

DENY_THRESHOLD_ROOT = 5
#允 许root登陆失败的次数

HOSTNAME_LOOKUP=NO
#是 否做域名反解

ADMIN_EMAIL = iakuf@163.com
#管 理员邮件地址,它会给管理员发邮件

DAEMON_LOG = /var/log/denyhosts
#自己的日志文件

 

Next, if you intend to run DenyHosts in daemon mode (recommended)
copy the sample daemon-control.dist script as such:

# cp daemon-control-dist daemon-control

Edit the daemon-control file. You should only need to edit this section
near the top:

###############################################
#### Edit these to suit your configuration ####
###############################################

DENYHOSTS_BIN = "/usr/bin/denyhosts.py"
DENYHOSTS_LOCK = "/var/lock/subsys/denyhosts"
DENYHOSTS_CFG = "/etc/denyhosts.conf"


These defaults should be reasonable for many systems. You
should customize these settings to match your particular
system.

Once you have edited the configuration and daemon control files
make sure that the daemon control script it executable (by root).

# chown root daemon-control

# chmod 700 daemon-control


Starting DenyHosts Manually
===========================

Assuming you have configured DenyHosts to run as a daemon, you
can use the daemon-control script to control it:

# daemon-control start

You should refer to the daemon log (typically /var/log/denyhosts)
to ensure that DenyHosts is running successfully. If you
notice any problems you may wish to consult the FAQ at
http://www.denyhosts.net/faq.html

If you wish to run DenyHosts from cron rather than as a
daemon, please refer to the FAQ.


Starting DenyHosts Automatically
================================

Method 1 (preferred)
--------------------

Create a symbolic link from /etc/init.d such as:

# cd /etc/init.d
# ln -s /usr/share/denyhosts/daemon-control denyhosts

If you have chkconfig installed you can then use it to
ensure that DenyHosts runs at boot time:

# chkconfig --add denyhosts

If you do not have chkconfig (or similar) installed you can either manually
create the symlinks in /etc/rc2.d, /etc/rc3.d, /etc/rc5.d but that is beyond
the scope of this document.

 

我们在上面的继续操作:

chkconfig denyhosts on

 chkconfig --list 可以看到右denyHosts说明成功了。

 

启动:

service denyhost start
可以看看/etc/hosts.deny内是否有禁止的IP,有的话说明已经成功了。

 我运行了一下,看到了一个最近尝试登陆被禁止的ip:

cat /etc/hosts.deny

#
# hosts.deny This file contains access rules which are used to
# deny connections to network services that either use
# the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# The rules in this file can also be set up in
# /etc/hosts.allow with a 'deny' option instead.
#
# See 'man 5 hosts_options' and 'man 5 hosts_access'
# for information on rule syntax.
# See 'man tcpd' for information on tcp_wrappers
#
sshd: 121.46.1.145
~

 (简单部署的几行命令:

mv /usr/bin/denyhosts.py /usr/sbin/denyhosts

mv /usr/bin/daemon-control-dist /etc/init.d/denyhosts

cd /etc/init.d

chkconfig --add denyhosts 

chkconfig   denyhosts  on

vim /etc/denyhosts.conf    修改SECURE_LOG位置

 service denyhosts start

 

denyhost检测进程是否在运行写的非常好,可以借鉴:

#!/usr/bin/python
# denyhosts     Bring up/down the DenyHosts daemon
#
# chkconfig: 2345 98 02
# description: Activates/Deactivates the
#    DenyHosts daemon to block ssh attempts
#
###############################################

###############################################
#### Edit these to suit your configuration ####
###############################################

DENYHOSTS_BIN   = "/usr/sbin/denyhosts"
DENYHOSTS_LOCK  = "/run/denyhosts.pid"
DENYHOSTS_CFG   = "/etc/denyhosts.conf"

PYTHON_BIN      = "/usr/bin/env python"

###############################################
####         Do not edit below             ####
###############################################

DENYHOSTS_BIN = "%s %s" % (PYTHON_BIN, DENYHOSTS_BIN)

import os, sys, signal, time

# make sure 'ps' command is accessible (which should be
# in either /usr/bin or /bin.  Modify the PATH so
# popen can find it
env = os.environ.get('PATH', "")
os.environ['PATH'] = "/usr/bin:/bin:%s" % env

STATE_NOT_RUNNING = -1
STATE_LOCK_EXISTS = -2

def usage():
    print "Usage: %s {start [args...] | stop | restart [args...] | status | debug | condrestart [args...] }" % sys.argv[0]
    print
    print "For a list of valid 'args' refer to:"
    print "$ denyhosts.py --help"
    print
    sys.exit(0)


def getpid():
    try:
        fp = open(DENYHOSTS_LOCK, "r")
        pid = int(fp.readline().rstrip())
        fp.close()
    except Exception, e:
        return STATE_NOT_RUNNING


    if not sys.platform.startswith('freebsd') and os.access("/proc", os.F_OK):
        # proc filesystem exists, look for pid
        if os.access(os.path.join("/proc", str(pid)), os.F_OK):
            return pid
        else:
            return STATE_LOCK_EXISTS
    else:
        # proc filesystem doesn't exist (or it doesn't contain PIDs), use 'ps'
        p = os.popen("ps -p %d" % pid, "r")
        p.readline() # get the header line
        pid_running = p.readline()
        # pid_running will be '' if no process is found
        if pid_running:
            return pid
        else:
            return STATE_LOCK_EXISTS


def start(*args):
    cmd = "%s --daemon " % DENYHOSTS_BIN
    if args: cmd += ' '.join(args)

    print "starting DenyHosts:   ", cmd

    os.system(cmd)


def stop():
    pid = getpid()
    if pid >= 0:
        os.kill(pid, signal.SIGTERM)
        print "sent DenyHosts SIGTERM"
    else:
        print "DenyHosts is not running"

def debug():
    pid = getpid()
    if pid >= 0:
        os.kill(pid, signal.SIGUSR1)
        print "sent DenyHosts SIGUSR1"
    else:
        print "DenyHosts is not running"

def status():
    pid = getpid()
    if pid == STATE_LOCK_EXISTS:
        print "%s exists but DenyHosts is not running" % DENYHOSTS_LOCK
    elif pid == STATE_NOT_RUNNING:
        print "Denyhosts is not running"
    else:
        print "DenyHosts is running with pid = %d" % pid


def condrestart(*args):
    pid = getpid()
    if pid >= 0:
        restart(*args)


def restart(*args):
    stop()
    time.sleep(1)
    start(*args)


if __name__ == '__main__':
    cases = {'start':       start,
             'stop':        stop,
             'debug':       debug,
             'status':      status,
             'condrestart': condrestart,
             'restart':     restart}

    try:
        args = sys.argv[2:]
    except Exception:
        args = []

    try:
        # arg 1 should contain one of the cases above
        option = sys.argv[1]
    except Exception:
        # try to infer context (from an /etc/init.d/ script, perhaps)
        procname = os.path.basename(sys.argv[0])
        infer_dict = {'K': 'stop',
                      'S': 'start'}
        option = infer_dict.get(procname[0])
        if not option:
            usage()

    try:
        if option in ('start', 'restart', 'condrestart'):
            anystartswith = lambda prefix, xs: any(map(lambda x: x.startswith(prefix), xs))
            if not anystartswith('--config', args) and '-c' not in args:
                args.append("--config=%s" % DENYHOSTS_CFG)

        cmd = cases[option]
        apply(cmd, args)
    except Exception:
        usage()

 

denyhosts 解锁ip:

命令帮助中提供了denyhosts.py --purgeip命令,看含义应该是解封指定Ip。但运行命令会报错:[Errno 2] No such file or directory

 

 

需要先切换到/var/lib/denyhosts/这个文件夹下,

查找出当前文件夹以及子目录中,哪些文件包含有字符串内容。

然后在vim打开后,找到所在行,dd删除所在行。

 

cd /var/lib/denyhosts/

grep -rn "目标ip" *

然后用sed命令删除。

 也要把/var/log/secure中的ip删除。

sed命令常用到的两个选项:
-i : 直接在文件上编辑 (edit files in place)
-e[默认选项]:只在命令行输出,而文件不改变
(add the script to the commands to be executed)
注:使用sed命令可以使用 -i 或者 -e 选项(以下例子仅以-i举例)

sed命令删除包含特定字符行
删除包含"xxx"的行
sed -i '/xxx/d' filename

 

会把查找到xxx都删除所在行。

1 sed -i '/ip/d'  `ls` 

2 sed -i '/ip/d'   /var/log/secure

 

 

denyhosts彻底解禁步骤:

1. 删除/etc/hosts.deny对应行

2. 进入/var/lib/denyhosts/这个文件夹,

执行: sed -i '/ip/d'   /var/log/secure 这个ip换成解禁的对应的ip

3. 清空 /var/log/secure

4。如果上面步骤还不行,重启系统,有一次就是没有重启系统,按照上面步骤做了几次都不行,结果重启下就可以了。