// Uncategorized

如何对Linux VPS服务器进行安全加固

一份不断发展的Linux服务器安全指南,持续更新,希望也能教你一些关于安全及其重要性的知识。

目录

(目录是用nGitHubTOC制作的)

简介

导览目标

本指南的目的是教你如何保护Linux服务器的安全。

你可以做很多事情来保护Linux服务器的安全,本指南将尽量涵盖其中的全部。随着我学习或大家的贡献,会补充更多主题和材料。

本指南的 Ansible 操作手册可在 moltenbit 的《How To Secure A Linux Server With Ansible》中获取。

(目录)

为什么要保护你的服务器

我猜你用这份指南是因为你希望已经明白为什么良好的安全很重要。这是一个沉重的话题,详细分析超出本指南范围。如果你不知道这个问题的答案,我建议你先去研究一下。

从高层面看,一旦设备(如服务器)进入公共领域——即对外界可见——它就成为不良分子的目标。不安全的设备是恶意分子的游乐场,他们想要访问你的数据,或者将你的服务器作为大规模DDOS攻击的另一个节点。

更糟糕的是,没有良好的安全措施,你可能永远无法知道服务器是否被攻破。不法分子可能未经授权访问你的服务器,复制了你的数据却没有更改任何东西,所以你永远不会知道。或者你的服务器可能遭遇了DDOS攻击,而你却不知道。看看新闻中许多大规模数据泄露事件——这些公司往往是在不良行为者消失很久之后才发现数据泄露或入侵。

与普遍看法相反,不良行为者并不总是想为了钱而更改某些东西或锁定你的数据。有时他们只是想把你服务器上的数据用于他们的数据仓库(大数据有大笔资金),或者偷偷利用你的服务器做坏事。

(目录)

为什么又要找一个导游

这份指南可能看起来重复或多余,因为网上有无数文章告诉你如何保护Linux安全,但信息分散在不同的文章中,涵盖的内容和方式各不相同。谁有时间去翻阅数百篇文章?

在为我的Debian构建做研究时,我做了笔记。最后我意识到,除了我已经知道和正在学习的内容外,我已经有了写一本操作指南的雏形。我想把它放到网上,希望能帮助别人学习节省时间

我从未找到过涵盖所有内容的指南——这份指南是我尝试的。

本指南中涵盖的许多内容可能相当基础或琐碎,但我们大多数人并不每天都安装Linux,这些基础知识很容易被遗忘。

(目录)

其他向导

专家、行业领袖以及发行版本身提供了许多指南。包含这些指南中的所有内容既不切实际,有时也违反版权。我建议你在开始本指南前先看看他们。

(目录)

待办事项 / 添加

(目录)

指南概述

关于本指南

这个向导……

  • 在进行中。
  • 专注于家庭Linux服务器。这里所有的概念和建议都适用于更大型或专业的环境,但这些用例需要更高级和专业化的配置,而这些配置不在本指南的范围内。
  • 它不会教你关于Linux的知识,也不会教你如何安装Linux,也不会教你如何使用它。如果你是Linux新手,可以 https://linuxjourney.com/ 看看。
  • 旨在Linux发行版无关
  • 它没有教你所有安全知识,也没有涵盖系统/服务器安全的各个方面。例如,物理安全不在本指南的讨论范围内。
  • 没有讲述程序或工具的工作原理,也没有深入挖掘它们的细节。本指南提到的大多数程序/工具都非常强大且高度可配置。目标是满足最基本的需求——足够激发你的食欲,让你渴望去学习更多。
  • 旨在通过提供可复制粘贴的代码,使操作变得简单。你可能需要修改命令再粘贴,所以请随身携带你喜欢的文本编辑器
  • 我认为合理的顺序组织——即在安装防火墙前先保护SSH。因此,本指南应按呈现顺序遵循,但并非非得如此。只是如果顺序不一样要小心——有些章节需要完成之前的章节。

(目录)

我的使用场景

服务器有多种类型和不同的使用场景。虽然我希望这份指南尽可能通用,但有些内容可能不适用于所有或其他使用场景。阅读本指南时请用你的判断力。

为了帮助理解本指南中涉及的许多主题,我的使用场景/配置是:

  • 一台台桌面级电脑……
  • 只有一个网卡……
  • 连接到消费级路由器……
  • 获取ISP提供的动态WAN IP……
  • 在IPV4上的WAN+LAN……
  • 还有使用NAT的局域网……
  • 我希望能够从未知的电脑和未知地点(比如朋友家)远程SSH连接到。

(目录)

编辑配置文件——为懒人准备

我很懒,如果不需要,不喜欢手动编辑文件。我也假设其他人和我一样。:)

因此,在可能的情况下,我提供了片段,方便快速完成所需操作,比如添加或更改配置文件中的一行。code

这些片段使用了基本命令,如 、 、 、 和 。具体片段的工作原理,比如每个命令/部分的作用,这不属于本指南范围——页面是你的好朋友。codeechocatsedawkgrepcodeman

注意:这些摘要并不验证/验证变更是否通过——即该行确实被添加或更改。我把核实部分交给你了。本指南中的步骤包括备份所有将要更改的文件。code

并非所有更改都能通过片段自动实现。这些改动需要传统的手工编辑。例如,你不能仅仅在INI类型文件中附加一行。用你最喜欢的Linux文本编辑器。code

(目录)

贡献

我想把这份指南放到GitHub上,方便协作。贡献的人越多,本指南就越完善、越完整。

你可以分叉并提交拉取请求,或者提交新议题

(目录)

开始之前

明确你的原则

在开始之前,你需要明确你的原则是什么。你的威胁模型是什么?需要考虑的一些事情:

  • 你为什么想保护你的服务器安全?
  • 你想要多少安全感,或者不想要多少保障?
  • 你愿意为了安全牺牲多少便利,反之亦然?
  • 你想防范哪些威胁?你的具体情况是什么?例如:
    • 对服务器/网络的物理访问可能成为攻击途径吗?
    • 你会在路由器上打开端口,这样你就能在家外访问服务器吗?
    • 你会在服务器上托管一个文件共享,然后挂载在桌面类机器上吗?桌面电脑被感染,进而感染服务器的可能性有多大?
  • 如果你的安全措施把你锁在自己的服务器之外,你有办法恢复吗?比如,你禁用了root登录或有密码保护的GRUB。

这些只是一些需要考虑的事情。在开始保护服务器安全之前,你需要了解你想要防范什么以及为什么要保护,这样你才知道需要做什么。

(目录)

选择Linux发行版

本指南旨在与发行版无关,用户可以选择任何发行版。话虽如此,有几点需要注意:

你想要一个……

  • 稳定。除非你喜欢凌晨2点调试问题,否则你不希望无人值守升级或手动软件包/系统更新导致服务器无法使用。但这也意味着你不用用最新、最先进的软件。
  • 保持安全补丁的最新更新。你可以在服务器上保护所有东西,但如果你运行的核心操作系统或应用存在已知漏洞,你永远不会安全。
  • 你很熟悉。如果你不了解Linux,我建议你先试试看,再决定是否要保护它。你应该对它感到熟悉,熟悉流程,比如怎么安装软件、配置文件放哪儿等等……
  • 支持力强。即使是最有经验的管理员偶尔也需要帮助。有个求助的地方能保护你的理智。

(目录)

安装Linux

安装Linux不在本指南范围内,因为每个发行版的安装方式不同,安装说明通常都有详细文档。如果你需要帮助,可以先查你发行版的文档。无论分布如何,高层过程通常如下:

  1. 下载ISO
  2. 刻录/复制/传输到你的安装介质(比如光盘或U盘)
  3. 从安装介质启动服务器
  4. 按照提示安装

如果适用,使用专家安装选项,这样你能更严格地控制服务器上运行的内容。只安装你绝对需要的设备。我个人只安装SSH系统。另外,勾选磁盘加密选项。

(目录)

安装前后要求

  • 如果你在路由器上打开端口以便从外部访问服务器,请在系统正常运行和安全之前关闭端口转发。
  • 除非你所有操作都物理连接服务器,否则你需要远程访问,所以一定要确保SSH能正常工作。
  • 保持系统更新(即 在基于Debian的系统上)。sudo apt update && sudo apt upgrade
  • 确保你完成任何与你设备相符的任务,比如:
    • 网络配置
    • 配置挂载点/etc/fstab
    • 创建初始用户账户
    • 安装核心软件时,你会想要的man
    • 等等……
  • 你的服务器需要能够发送电子邮件,以便你能接收重要的安全警报。如果你不搭建邮件服务器,可以检查Gmail和Exim4作为带有隐式TLS的MTA
  • 我还建议你在开始这本指南之前先阅读CIS基准测试,以便消化和理解它们的观点。我的建议是先看这份指南(你正在读的那个),然后再看CIS的指南。这样他们的推荐就能胜过本指南中的任何内容。

(目录)

其他重要说明

  • 本指南正在Debian上编写和测试。以下大多数内容应该能在其他发行版上使用。如果你发现了不符合的,请联系。区分每个发行版的主要因素是它的包管理系统。因为我用的是Debian,我会提供适用于所有基于Debian的发行版的相应命令。如果有人愿意为其他发行版提供相应的命令,我会添加。apt
  • 文件路径和设置也可能略有不同——如果有问题,请查阅你发行版的文档。
  • 开始前请阅读完整指南。你的用例和/或原则可能会要求你不做某件事或改变顺序。
  • 不要盲目复制粘贴,除非你在粘贴什么。有些命令需要根据你的需求进行修改才能生效——比如用户名。

(目录)

使用 Ansible playbook 来保护你的 Linux 服务器安全

本指南的 Ansible 操作手册可在《如何用 Ansible 保护 Linux 服务器》中获取。

确保根据你的需求编辑变量,提前阅读所有任务,确认它不会破坏你的系统。运行剧本后,确保所有设置都按照你的需求配置好!

  1. 安装 Ansible
  2. git 克隆 如何用 Ansible 保护 Linux 服务器
  3. 创建SSH公钥/私钥
ssh-keygen -t ed25519
  1. 根据你的需求,group_vars/variables.yml中的所有变量都变更。
  2. 在运行 Playbook 前启用 SSH root 权限:
nano /etc/ssh/sshd_config
[...]
PermitRootLogin yes
[...]
  1. 建议:在你的系统上配置静态IP地址。
  2. 把你的系统IP地址添加到hosts.yml

用安装服务器时指定的根密码运行需求手册:

ansible-playbook --inventory hosts.yml --ask-pass requirements-playbook.yml

用你在variables.yml文件中指定的新用户密码运行主操作手册:

ansible-playbook --inventory hosts.yml --ask-pass main-playbook.yml

如果你需要多次运行这些Playbook,记得用SSH密钥和新的SSH端口:

ansible-playbook --inventory hosts.yml -e ansible_ssh_port=SSH_PORT --key-file /PATH/TO/SSH/KEY main-playbook.yml

(目录)

SSH 服务器

在你更改SSH之前,有个重要提示

强烈建议你在更改和应用SSH配置之前,先保持第二个终端对服务器开放。这样即使你锁定了第一个终端会话,仍然有一个会话连接着,可以修复它。

感谢Sonnenbrand提出这个想法

SSH 公钥/私钥

为什么

使用 SSH 公私钥比使用密码更安全。这也让连接服务器变得更简单快捷,因为你无需输入密码。

工作原理

请查看下面的参考文献了解更多细节,但从高层次来看,公私钥是通过一对密钥来验证身份的。

  1. 其中一把密钥,公钥,只能加密数据,不能解密
  2. 另一个密钥,私钥,可以解密数据

对于SSH,客户端创建公钥和私钥。你需要确保两个密钥都安全,尤其是私钥。尽管公钥本应是公开的,但明智的做法是确保两把密鑰都不落入错误之手。

当你连接到SSH服务器时,SSH会寻找与你连接服务器文件中客户端匹配的公钥。注意文件在你试图连接的ID的主文件夹里。所以,创建公钥后,你需要将其附加到。一种方法是把它复制到U盘,然后物理传输到服务器上。另一种方法是使用 ssh-copy-id 传输并附加公钥。~/.ssh/authorized_keys~/.ssh/authorized_keys

在创建好密钥并附加公钥到主机后,SSH使用公钥和私钥验证身份,然后建立安全连接。身份验证过程很复杂,但Digital Ocean有一篇非常详细的说明。在高层次上,身份由服务器用公钥加密挑战消息,然后发送给客户端来验证。如果客户端无法用私钥解密挑战消息,身份无法验证,连接也无法建立。~/.ssh/authorized_keys

它们被认为更安全,因为建立SSH连接需要私钥。如果你在 /etc/ssh/sshd_config 设置了 PasswordAuthentication no ,那么 SSH 就不允许你在没有私钥的情况下连接。

你还可以为密钥设置密码短语,这需要你在使用公钥/私钥连接时输入密钥密码。请记住,这样做意味着你无法用密钥进行自动化,因为你无法在脚本中发送密码短语。 是一个被许多Linux发行版预发(通常已经运行)的程序,允许你在可配置的时间内将未加密的私钥保存在内存中。只需运行,它就会提示你输入密码。在可配置的时长结束之前,你不会再次被提示输入密码短语。ssh-agentssh-add

我们将使用Ed25519密钥,根据 https://linux-audit.com/

它采用椭圆曲线签名方案,安全性优于ECDSA和DSA。同时,它的性能也不错。

目标

  • Ed25519 公/私 SSH 密钥:
    • 客户端的私钥
    • 服务器上的公钥

注释

  • 你需要对每台连接服务器的电脑和账户都做这个步骤。

参考文献

步骤

  1. 你用来连接服务器的电脑,客户端(不是服务器本身)创建一个 Ed25519 密钥,格式为:ssh-keygenssh-keygen -t ed25519Generating public/private ed25519 key pair. Enter file in which to save the key (/home/user/.ssh/id_ed25519): Created directory '/home/user/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_ed25519. Your public key has been saved in /home/user/.ssh/id_ed25519.pub. The key fingerprint is: SHA256:F44D4dr2zoHqgj0i2iVIHQ32uk/Lx4P+raayEAQjlcs user@client The key's randomart image is: +--[ED25519 256]--+ |xxxx x | |o.o +. . | | o o oo . | |. E oo . o . | | o o. o S o | |... .. o o | |.+....+ o | |+.=++o.B.. | |+..=**=o=. | +----[SHA256]-----+ 注意:如果你设置了密码短语,每次用这个密钥连接服务器时都需要输入,除非你用的是 。ssh-agent
  2. 现在你需要把客户端的公钥附加到服务器上的文件上。既然我们大概还在局域网,应该能避免MIM攻击,所以我们会用来传输并附加公钥:~/.ssh/id_ed25519.pub~/.ssh/authorized_keysssh-copy-idssh-copy-id user@server/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/user/.ssh/id_ed25519.pub" The authenticity of host 'host (192.168.1.96)' can't be established. ECDSA key fingerprint is SHA256:QaDQb/X0XyVlogh87sDXE7MR8YIK7ko4wS5hXjRySJE. Are you sure you want to continue connecting (yes/no)? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys user@host's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'user@host'" and check to make sure that only the key(s) you wanted were added.

现在是执行你设备中特定任务的好时机。

(目录)

为AllowGroups创建SSH组

为什么

这样就能轻松控制谁能SSH到服务器。通过使用组,我们可以快速添加或移除账户,从而快速允许或拒绝对服务器的SSH访问。

工作原理

我们将在 SSH 配置文件 /etc/ssh/sshd_config 中使用 AllowGroups 选项,告诉 SSH 服务器只允许 SSH 用户在属于某个 UNIX 组时使用 SSH。组外的人无法SSH登录。

目标

注释

参考文献

  • man groupadd
  • man usermod

步骤

  1. 创建小组:sudo groupadd sshusers
  2. 添加账户到群组:sudo usermod -a -G sshusers user1 sudo usermod -a -G sshusers user2 sudo usermod -a -G sshusers …你需要对服务器上每个需要SSH访问的账户都这样做。

(目录)

安全/etc/ssh/sshd_config

为什么

SSH就像是通往你服务器的一扇门。如果你在路由器上开端口,以便从家庭网络外通过SSH连接到服务器,这一点尤其适用。如果安全设置不当,不法分子可能会利用它对你的系统进行未经授权的访问。

工作原理

/etc/ssh/sshd_config是SSH服务器使用的默认配置文件。我们将用这个文件来判断SSH服务器应使用哪些选项。

目标

  • 一种安全的SSH配置

注释

参考文献

步骤

  1. 备份OpenSSH服务器配置文件并删除注释,以便阅读:/etc/ssh/sshd_configsudo cp –archive /etc/ssh/sshd_config /etc/ssh/sshd_config-COPY-$(date +”%Y%m%d%H%M%S”) sudo sed -i -r -e ‘/^#|^$/ d’ /etc/ssh/sshd_config
  2. 编辑,然后找到并编辑或添加这些设置,无论你的配置如何都应该应用:/etc/ssh/sshd_config注意:SSH 不喜欢重复矛盾的设置。例如,如果你有 和 ,则 ,SSH 会尊重第一个,忽略第二个。你的文件里可能已经包含了下面的一些设置或行。为了避免问题,你需要手动检查你的文件,处理任何重复的矛盾设置。KbdInteractiveAuthentication noKbdInteractiveAuthentication yes/etc/ssh/sshd_config/etc/ssh/sshd_config注:如果你运行的是OpenSSH 9.1或更高版本,请在下方配置中取消注释。这强制要求最低RSA密钥大小为3072位,并在认证时拒绝较小的RSA密钥。这只影响RSA密钥。如果你使用ED25519或ECDSA密钥,则不受影响。你可以用 检查密钥类型和大小。在较旧的OpenSSH版本中,去除注释的那句话,因为这会阻止sshd启动。RequiredRSASize 3072ssh-keygen -l -f ~/.ssh/id_rsa######################################################################################################## # start settings from https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67 as of 2019-01-01 ######################################################################################################## # Supported HostKey algorithms by order of preference. HostKey /etc/ssh/ssh_host_ed25519_key HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_ecdsa_key KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256 Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com # LogLevel VERBOSE logs user's key fingerprint on login. Needed to have a clear audit track of which key was using to log in. LogLevel VERBOSE # Use kernel sandbox mechanisms where possible in unprivileged processes # Systrace on OpenBSD, Seccomp on Linux, seatbelt on MacOSX/Darwin, rlimit elsewhere. # Note: This setting is deprecated in OpenSSH 7.5 (https://www.openssh.com/txt/release-7.5) # UsePrivilegeSeparation sandbox ######################################################################################################## # end settings from https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67 as of 2019-01-01 ######################################################################################################## # don't let users set environment variables PermitUserEnvironment no # Log sftp level file access (read/write/etc.) that would not be easily logged otherwise. Subsystem sftp internal-sftp -f AUTHPRIV -l INFO # disable X11 forwarding as X11 is very insecure # you really shouldn't be running X on a server anyway X11Forwarding no # disable port forwarding AllowTcpForwarding no AllowStreamLocalForwarding no GatewayPorts no PermitTunnel no # don't allow login if the account has an empty password PermitEmptyPasswords no # ignore .rhosts and .shosts IgnoreRhosts yes # verify hostname matches IP UseDNS yes Compression no # TCP keepalive is spoofable (runs outside the encrypted channel) # Use ClientAlive instead (runs inside the encrypted channel) TCPKeepAlive no AllowAgentForwarding no PermitRootLogin no # don't allow .rhosts or /etc/hosts.equiv HostbasedAuthentication no # OpenSSH 9.1 and later # Enforce a minimum RSA key size of 3072 bits # https://www.keylength.com/en/compare/ # RequiredRSASize 3072
  3. 然后找到并编辑或添加这些设置,并根据你的需求设置数值:背景设定有效价值观示例描述注释AllowGroups本地UNIX组名称AllowGroups sshusers允许SSH访问的组客户活计数最大人数ClientAliveCountMax 3发送的最大客户端活消息数量且无响应ClientAliveInterval秒数ClientAliveInterval 15在响应请求前几秒钟内超时收听地址空格分隔的本地地址列表
    • ListenAddress 0.0.0.0
    • ListenAddress 192.168.1.100
    本地地址应收听sshd重要细节请参见问题#1登录恩惠时间秒数LoginGraceTime 30登录超时前的秒数MaxAuthTries人数MaxAuthTries 2允许的最大登录尝试次数MaxSessions人数MaxSessions 2最大开放场次MaxStartups数字或start:rate:fullMaxStartups 10:30:60最大未认证SSH连接数密码认证yesnoPasswordAuthentication no如果允许使用密码登录移植任何开放/可用的端口号Port 22应该会听的端口sshd查看这些设置的具体含义。man sshd_config
  4. 确保没有重复的设置相互矛盾。下面的命令不应该有任何输出。awk ‘NF && $1!~/^(#|HostKey)/{print $1}’ /etc/ssh/sshd_config | sort | uniq -c | grep -v ‘ 1 ‘
  5. 在重启前验证 OpenSSH 服务器配置:sudo sshd -t
  6. 重启 ssh:sudo service ssh restart
  7. 你可以检查,验证可用的配置,并验证输出:sshd -Tsudo sshd -Tport 22 addressfamily any listenaddress [::]:22 listenaddress 0.0.0.0:22 usepam yes logingracetime 30 x11displayoffset 10 maxauthtries 2 maxsessions 2 clientaliveinterval 15 clientalivecountmax 3 streamlocalbindmask 0177 permitrootlogin no ignorerhosts yes ignoreuserknownhosts no hostbasedauthentication no ... subsystem sftp internal-sftp -f AUTHPRIV -l INFO maxstartups 2:30:2 permittunnel no ipqos lowdelay throughput rekeylimit 0 0 permitopen any

(目录)

移除短 Diffie-Hellman 键

为什么

根据 Mozilla 为 OpenSSH 6.7+ 制定的指南,“所有使用的 Diffie-Hellman 模数长度应至少为 3072 位”。

SSH使用Diffie-Hellman算法建立安全连接。模数(密钥大小)越大,加密越强。

目标

  • 移除所有长度小于3072位的Diffie-Hellman密钥

参考文献

步骤

  1. 备份SSH的模文件:/etc/ssh/modulisudo cp –archive /etc/ssh/moduli /etc/ssh/moduli-COPY-$(date +”%Y%m%d%H%M%S”)
  2. 去除短模量:sudo awk ‘$5 >= 3071’ /etc/ssh/moduli | sudo tee /etc/ssh/moduli.tmp sudo mv /etc/ssh/moduli.tmp /etc/ssh/moduli

(目录)

SSH 的双重认证/多重身份验证

为什么

尽管SSH在门窗上是相当不错的安保,但它仍然是一扇明显的门,坏人可以看到并试图暴力破门而入。Fail2ban会监控这些暴力破解尝试,但安全性并不高。要求两个因素,增加了额外的安全保障。

使用双因素认证(2FA)/多因素认证(MFA)要求任何进入者都必须拥有把密钥,这使得恶意行为者更难进入。这两个关键点是:

  1. 他们的密码
  2. 一个每30秒更换一次的6位数令牌

没有两把钥匙,他们进不去。

为什么不呢

许多人可能会觉得这种体验繁琐或烦人。而且,访问你的系统取决于生成代码的配套认证应用。

工作原理

在 Linux 上,PAM 负责认证。PAM有四个任务,你可以在 https://en.wikipedia.org/wiki/Linux_PAM 上阅读。本节讨论认证任务。

当你登录服务器,无论是直接从控制台登录还是通过SSH,你通过的门都会将请求发送给PAM的认证任务,PAM会要求并验证你的密码。你可以自定义每个门使用的规则。例如,你可以在直接从控制台登录时使用一套规则,而在通过 SSH 登录时则有一套规则。

本节将修改通过SSH登录时的认证规则,要求同时输入密码和6位数验证码。

我们将使用谷歌的libpam-google-authenticator PAM模块来创建并验证TOTP密钥。https://fastmail.blog/2016/07/22/how-totp-authenticator-apps-work/ 和 https://jemurai.com/2018/10/11/how-it-works-totp-based-mfa/ 对TOTP的工作原理有很好的介绍。

我们会告诉服务器的SSH PAM配置,先向用户输入密码,然后输入数字令牌。PAM会验证用户密码,如果密码正确,就会将认证请求路由到libpam-google-authenticator,后者会要求并验证你的6位令牌。只有当一切正常时,认证才会成功,用户才会被允许登录。

目标

  • 所有SSH连接都启用了2FA/MFA

注释

  • 在你做这件事之前,你应该对双重认证/多重身份验证(MFA)的工作原理有个了解,并且你需要手机上的身份验证器应用来继续使用。
  • 我们会用 google-authenticator-libpam
  • 根据以下配置,用户只有在使用密码登录时才需要输入2FA/MFA代码,而使用SSH公私钥无需。如果你希望公钥认证也要求TOTP码,可以配置为要求。AuthenticationMethodskeyboard-interactivepublickey
  • 该选项允许没有文件的用户无需代码登录。如果每个账户都必须强制多重身份验证,那么在所有预期SSH用户注册后移除。nullok~/.google_authenticatornullok

参考文献

步骤

  1. 安装它 libpam-google-authenticator。在基于 Debian 的系统上:sudo apt install libpam-google-authenticator
  2. 确保你登录的是你想启用2FA/MFA的ID执行以创建必要的令牌数据:google-authenticatorgoogle-authenticatorDo you want authentication tokens to be time-based (y/n) y https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/user@host%3Fsecret%3DR4ZWX34FQKZROVX7AGLJ64684Y%26issuer%3Dhost ... Your new secret key is: R3NVX3FFQKZROVX7AGLJUGGESY Your verification code is 751419 Your emergency scratch codes are: 12345678 90123456 78901234 56789012 34567890 Do you want me to update your "/home/user/.google_authenticator" file (y/n) y Do you want to disallow multiple uses of the same authentication token? This restricts you to one login about every 30s, but it increases your chances to notice or even prevent man-in-the-middle attacks (y/n) Do you want to disallow multiple uses of the same authentication token? This restricts you to one login about every 30s, but it increases your chances to notice or even prevent man-in-the-middle attacks (y/n) y By default, tokens are good for 30 seconds. In order to compensate for possible time-skew between the client and the server, we allow an extra token before and after the current time. If you experience problems with poor time synchronization, you can increase the window from its default size of +-1min (window size of 3) to about +-4min (window size of 17 acceptable tokens). Do you want to do so? (y/n) y If the computer that you are logging into isn't hardened against brute-force login attempts, you can enable rate-limiting for the authentication module. By default, this limits attackers to no more than 3 login attempts every 30s. Do you want to enable rate-limiting (y/n) y 注意这不是以根程序运行的。选择默认选项(大多数情况下是y),所有问题都选择,并记得保存紧急的刮刮码。
  3. 备份PAM的SSH配置文件:/etc/pam.d/sshdsudo cp –archive /etc/pam.d/sshd /etc/pam.d/sshd-COPY-$(date +”%Y%m%d%H%M%S”)
  4. 现在我们需要通过在 SSH 中添加这行来启用它作为 SSH 的认证方法:/etc/pam.d/sshdauth required pam_google_authenticator.so nullok 注意:请点击这里了解具体含义。nullok给懒人:echo -e “\nauth required pam_google_authenticator.so nullok # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/pam.d/sshd
  5. 告诉SSH通过添加或编辑这行来利用它:/etc/ssh/sshd_configKbdInteractiveAuthentication yes 给懒人:sudo sed -i -r -e “s/^(kbdinteractiveauthentication|challengeresponseauthentication)( .*)$/# \1\2 # commented by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/I” /etc/ssh/sshd_config echo -e “\nKbdInteractiveAuthentication yes # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/ssh/sshd_config
  6. 在重启前验证 OpenSSH 服务器配置:sudo sshd -t
  7. 重启 ssh:sudo service ssh restart

(目录)

基础知识

限制谁可以使用sudo。

为什么

Sudo 允许账户像其他账户一样运行命令,包括 root。我们希望只有我们想要的账号才能使用sudo。

目标

  • SUDO 权限仅限于我们指定的组内人员

注释

  • 你的安装可能已经做过这些操作,或者已经有专门的组专门用于此目的,所以先确认一下。
    • Debian创建了sudo组。要查看属于该组的用户(因此拥有sudo权限):cat /etc/group | grep "sudo"
    • RedHat 创建轮组
  • 参见#39,了解一些发行版的说明,使其实现时不需要密码。感谢sbrl的分享。sudo

步骤

  1. 创建小组:sudo groupadd sudousers
  2. 添加账户到群组:sudo usermod -a -G sudousers user1 sudo usermod -a -G sudousers user2 sudo usermod -a -G sudousers …你需要对服务器上每个需要sudo权限的账户都这样做。
  3. 备份sudo配置文件:/etc/sudoerssudo cp –archive /etc/sudoers /etc/sudoers-COPY-$(date +”%Y%m%d%H%M%S”)
  4. 编辑sudo的配置文件:/etc/sudoerssudo visudo
  5. 如果没有这行,请告诉 sudo 只允许群组内用户使用 sudo:sudousers%sudousers ALL=(ALL:ALL) ALL

(目录)

限制谁可以使用 su

为什么

Su 还允许账号像其他账号一样运行命令,包括 root。我们希望只有我们想要的账户才能使用su。

目标

  • 我们指定的群体中,特权限制

参考文献

步骤

  1. 创建小组:sudo groupadd suusers
  2. 添加账户到群组:sudo usermod -a -G suusers user1 sudo usermod -a -G suusers user2 sudo usermod -a -G suusers …你需要对服务器上每个需要sudo权限的账户都这样做。
  3. 只允许该组内的用户执行:/bin/susudo dpkg-statoverride –update –add root suusers 4750 /bin/su

(目录)

用 FireJail 在沙盒中运行应用程序

为什么

对于许多应用来说,运行在沙盒中绝对更好。

强烈建议使用浏览器(尤其是闭源浏览器)和电子邮件客户端。

目标

  • 将应用程序限制在监狱中(少数安全的目录),并阻止对系统其余部分的访问

参考文献

步骤

  1. 安装软件:sudo apt install firejail firejail-profiles注意:对于Debian 10稳定版,建议使用官方回移植:sudo apt install -t buster-backports firejail firejail-profiles
  2. 允许应用(安装在 或 中)仅在沙箱中运行(见下面几个示例):/usr/bin/binsudo ln -s /usr/bin/firejail /usr/local/bin/google-chrome-stable sudo ln -s /usr/bin/firejail /usr/local/bin/firefox sudo ln -s /usr/bin/firejail /usr/local/bin/chromium sudo ln -s /usr/bin/firejail /usr/local/bin/evolution sudo ln -s /usr/bin/firejail /usr/local/bin/thunderbird
  3. 像平常一样运行该应用(通过终端或启动器),并检查它是否在监狱中运行:firejail –list
  4. 允许沙箱应用恢复运行(例如:Firefox)sudo rm /usr/local/bin/firefox

(目录)

NTP 客户端

为什么

许多安全协议都利用了这段时间。如果你的系统时间不准确,可能会对服务器产生负面影响。NTP客户端可以通过保持系统时间与全局NTP服务器同步来解决这个问题

工作原理

NTP代表网络时间协议(Network Time Protocol)。在本指南的背景下,服务器端的NTP客户端用于更新服务器时间,更新官方服务器获取的时间。请查看 https://www.pool.ntp.org/en/ 所有公共NTP服务器。

注:从 Debian 13(Trixie)开始,经典软件包被移除。运行时会失败,提示“Package ntp are no installation candidate”。由于本指南仅将 NTP 作为客户端(同步服务器时钟),Debian 13+ 推荐的方法是使用 ,该软件已预装,无需额外包。请参见下方的 Debian 13+ 步骤ntpsudo apt install ntpsystemd-timesyncd

目标

  • NTP客户端安装并保持服务器时间同步

参考文献

步骤

Debian 13(Trixie)及以后版本:systemd-timesyncd

systemd-timesyncd是一个已经包含在 Debian 中的轻量级 SNTP 客户端。与完整守护进程不同,它不监听任何端口,因此攻击面较小。就本指南而言——保持服务器时钟同步——这就足够了。ntpd

  1. 启用NTP同步:sudo timedatectl set-ntp true
  2. 确认它是否正常工作:timedatectl status你应该能看到输出。NTP service: activeSystem clock synchronized: yes
  3. 配置受信任的NTP服务器。备份配置文件后再编辑:sudo cp –archive /etc/systemd/timesyncd.conf /etc/systemd/timesyncd.conf-COPY-$(date +”%Y%m%d%H%M%S”)编辑并取消评论/设置该部分:/etc/systemd/timesyncd.conf[Time][Time] NTP=pool.ntp.org FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 给懒人:sudo sed -i -r -e “s/^#?NTP=.*$/NTP=pool.ntp.org # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/” /etc/systemd/timesyncd.conf sudo sed -i -r -e “s/^#?FallbackNTP=.*$/FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/” /etc/systemd/timesyncd.conf
  4. 重启服务以应用更改:sudo systemctl restart systemd-timesyncd
  5. 检查同步状态:timedatectl timesync-status Server: 108.61.56.35 (pool.ntp.org) Poll interval: 32s (min: 32s; max: 34min 8s) Leap: normal Version: 4 Stratum: 2 Reference: C342F10A Precision: 1us (2^0) Root distance: 24.054ms (max: 5s) Offset: +2.156ms Delay: 48.567ms Jitter: 1.452ms Packet count: 3
Debian 12(Bookworm)及更早版本:ntp 包

注:这些步骤仅适用于 Debian 12 及更早版本。在 Debian 13+ 上,该软件包已不再提供——请使用上面提到的 systemd-timesyncd 步骤ntp

  1. 安装NTP。在基于 Debian 的系统上:sudo apt install ntp
  2. 备份NTP客户端配置文件:/etc/ntp.confsudo cp –archive /etc/ntp.conf /etc/ntp.conf-COPY-$(date +”%Y%m%d%H%M%S”)
  3. 至少在Debian上,默认配置已经相当安全了。我们唯一要确认的是我们是指令,而不是任何指令。该指令允许NTP客户端在服务器无响应或执行不良时间时停止使用该服务器。请通过评论所有指令并添加以下内容来实现。poolserverpoolserver/etc/ntp.confpool pool.ntp.org iburst 给懒人:sudo sed -i -r -e “s/^((server|pool).*)/# \1 # commented by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/” /etc/ntp.conf echo -e “\npool pool.ntp.org iburst # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/ntp.conf示例 /etc/ntp.confdriftfile /var/lib/ntp/ntp.drift statistics loopstats peerstats clockstats filegen loopstats file loopstats type day enable filegen peerstats file peerstats type day enable filegen clockstats file clockstats type day enable restrict -4 default kod notrap nomodify nopeer noquery limited restrict -6 default kod notrap nomodify nopeer noquery limited restrict 127.0.0.1 restrict ::1 restrict source notrap nomodify noquery pool pool.ntp.org iburst # added by user on 2019-03-09 @ 10:23:35
  4. 重启ntp:sudo service ntp restart
  5. 查看NTP服务状态:sudo systemctl status ntp● ntp.service - LSB: Start NTP daemon Loaded: loaded (/etc/init.d/ntp; generated; vendor preset: enabled) Active: active (running) since Sat 2019-03-09 15:19:46 EST; 4s ago Docs: man:systemd-sysv-generator(8) Process: 1016 ExecStop=/etc/init.d/ntp stop (code=exited, status=0/SUCCESS) Process: 1028 ExecStart=/etc/init.d/ntp start (code=exited, status=0/SUCCESS) Tasks: 2 (limit: 4915) CGroup: /system.slice/ntp.service └─1038 /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 108:113 Mar 09 15:19:46 host ntpd[1038]: Listen and drop on 0 v6wildcard [::]:123 Mar 09 15:19:46 host ntpd[1038]: Listen and drop on 1 v4wildcard 0.0.0.0:123 Mar 09 15:19:46 host ntpd[1038]: Listen normally on 2 lo 127.0.0.1:123 Mar 09 15:19:46 host ntpd[1038]: Listen normally on 3 enp0s3 10.10.20.96:123 Mar 09 15:19:46 host ntpd[1038]: Listen normally on 4 lo [::1]:123 Mar 09 15:19:46 host ntpd[1038]: Listen normally on 5 enp0s3 [fe80::a00:27ff:feb6:ed8e%2]:123 Mar 09 15:19:46 host ntpd[1038]: Listening on routing socket on fd #22 for interface updates Mar 09 15:19:47 host ntpd[1038]: Soliciting pool server 108.61.56.35 Mar 09 15:19:48 host ntpd[1038]: Soliciting pool server 69.89.207.199 Mar 09 15:19:49 host ntpd[1038]: Soliciting pool server 45.79.111.114
  6. 查看NTP的状态:sudo ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== pool.ntp.org .POOL. 16 p - 64 0 0.000 0.000 0.000 *lithium.constan 198.30.92.2 2 u - 64 1 19.900 4.894 3.951 ntp2.wiktel.com 212.215.1.157 2 u 2 64 1 48.061 -0.431 0.104

(目录)

确保 /proc

为什么

引用 https://linux-audit.com/linux-system-hardening-adding-hidepid-to-proc/ 的话:

浏览时你会发现许多文件和目录。其中许多只是数字,代表关于特定工艺编号(PID)的信息。默认情况下,Linux系统部署时允许所有本地用户查看所有相关信息。这包括来自其他用户的流程信息。这可能包括你不愿与其他用户分享的敏感信息。通过对文件系统配置进行调整,我们可以改变这种行为,提升系统的安全性。/proc

注意:部分系统可能会损坏。更多信息请参见#37。感谢nlgranger的分享。systemd

目标

  • /proc通过 SO 挂载,用户只能看到关于其进程的信息hidepid=2

参考文献

步骤

  1. 备份:/etc/fstabsudo cp –archive /etc/fstab /etc/fstab-COPY-$(date +”%Y%m%d%H%M%S”)
  2. 将这条线加到安装 :/etc/fstab/prochidepid=2proc /proc proc defaults,hidepid=2 0 0 给懒人:echo -e “\nproc /proc proc defaults,hidepid=2 0 0 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/fstab
  3. 重启系统:sudo reboot now注意:另外,你也可以用/procsudo mount -o remount,hidepid=2 /proc

(目录)

强制账户使用安全密码

为什么

默认情况下,账户可以使用任何密码,包括错误的密码。PWoquality/pam_pwquality通过“配置系统密码默认密码质量要求”以及“通过系统词典和一套识别不良选项的规则来验证其强度”来弥补这一安全漏洞。

工作原理

在 Linux 上,PAM 负责认证。PAM有四个任务,你可以在 https://en.wikipedia.org/wiki/Linux_PAM 上阅读。本节讲的是密码任务。

当需要设置或更改账户密码时,PAM的密码任务会处理该请求。在本节中,我们将告诉PAM的密码任务将请求的新密码传递给libpam-pwquality,以确保它符合我们的要求。如果满足要求,则会被使用/设定;如果不符合要求,它会出错并告知用户。

目标

  • 强制强密码

步骤

  1. 安装libpam-pwquality。在基于 Debian 的系统上:sudo apt install libpam-pwquality
  2. 备份PAM的密码配置文件:/etc/pam.d/common-passwordsudo cp –archive /etc/pam.d/common-password /etc/pam.d/common-password-COPY-$(date +”%Y%m%d%H%M%S”)
  3. 告诉PAM使用libpam-pwquality来强制强密码,方法是编辑文件并更改开头的行:/etc/pam.d/common-passwordpassword requisite pam_pwquality.so 对此表示:password requisite pam_pwquality.so retry=3 minlen=10 difok=3 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 maxrepeat=3 gecoscheck=1 上述选项包括:
    • retry=3= 提示用户三次后返回错误。
    • minlen=10= 密码的最小长度,考虑这些中的任何信用(或借方):
      • dcredit=-1= 必须至少有一个数字
      • ucredit=-1= 必须至少有一个大写字母
      • lcredit=-1= 必须至少有一个小写字母
      • ocredit=-1= 必须至少包含一个非字母数字字符
    • difok=3= 新密码中至少3个字符不能出现在旧密码中
    • maxrepeat=3= 允许最多重复3个字符
    • gecoscheck=1= 不允许使用带有账户名称的密码
    给懒人:sudo sed -i -r -e “s/^(password\s+requisite\s+pam_pwquality.so)(.*)$/# \1\2 # commented by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)\n\1 retry=3 minlen=10 difok=3 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 maxrepeat=3 gecoscheck=1 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/” /etc/pam.d/common-password

(目录)

自动安全更新与警报

为什么

保持服务器更新最新的关键安全补丁和更新非常重要。否则,你就面临已知的安全漏洞,恶意分子可能会利用这些漏洞非法访问你的服务器。

除非你打算每天都检查服务器,否则你需要一个自动更新系统和/或收到关于可用更新的邮件的方法。

你不想做所有更新,因为每次更新都有出问题的风险。关键更新很重要,但其他的都可以等你有时间手动完成。

为什么不呢

自动且无人值守的更新可能会损坏你的系统,而你可能不在服务器附近无法修复。如果这破坏了你的SSH访问,那就更麻烦了。

注释

  • 每个发行版管理包和更新方式不同。到目前为止,我只掌握了基于Debian系统的步骤。
  • 你的服务器需要有办法发送电子邮件才能实现

目标

  • 自动、无人值守地更新关键安全补丁
  • 自动发送剩余待处理更新的邮件

基于Debian的系统

工作原理

在基于Debian的系统上,你可以使用:

  • 无人值守升级,自动执行你想要的系统更新(即关键安全更新)
  • apt-listchanges,获取安装/升级前的软件包变更详情
  • Apticron 获取待处理的软件包更新邮件

我们将使用无人值守升级来应用关键的安全补丁。我们也可以应用稳定更新,因为这些更新已经被Debian社区彻底测试过。

参考文献

步骤

  1. 安装无人值守升级、apt-listchanges和apticron:sudo apt install unattended-upgrades apt-listchanges apticron
  2. 现在我们需要配置无人值守升级,以自动应用更新。这通常通过编辑由包创建的文件来完成。不过,由于这些文件可能会在未来的更新中被覆盖,我们将创建一个新文件。创建文件并添加以下内容:/etc/apt/apt.conf.d/20auto-upgrades/etc/apt/apt.conf.d/50unattended-upgrades/etc/apt/apt.conf.d/51myunattended-upgrades// Enable the update/upgrade script (0=disable) APT::Periodic::Enable "1"; // Do "apt-get update" automatically every n-days (0=disable) APT::Periodic::Update-Package-Lists "1"; // Do "apt-get upgrade --download-only" every n-days (0=disable) APT::Periodic::Download-Upgradeable-Packages "1"; // Do "apt-get autoclean" every n-days (0=disable) APT::Periodic::AutocleanInterval "7"; // Send report mail to root // 0: no report (or null string) // 1: progress report (actually any string) // 2: + command outputs (remove -qq, remove 2>/dev/null, add -d) // 3: + trace on APT::Periodic::Verbose "2"; APT::Periodic::Unattended-Upgrade "1"; // Automatically upgrade packages from these Unattended-Upgrade::Origins-Pattern { "origin=Debian,codename=${distro_codename},label=Debian"; "origin=Debian,codename=${distro_codename}-updates"; "origin=Debian,codename=${distro_codename},label=Debian-Security"; "origin=Debian,codename=${distro_codename}-security,label=Debian-Security"; }; // You can specify your own packages to NOT automatically upgrade here Unattended-Upgrade::Package-Blacklist { }; // Run dpkg --force-confold --configure -a if a unclean dpkg state is detected to true to ensure that updates get installed even when the system got interrupted during a previous run Unattended-Upgrade::AutoFixInterruptedDpkg "true"; //Perform the upgrade when the machine is running because we wont be shutting our server down often Unattended-Upgrade::InstallOnShutdown "false"; // Send an email to this address with information about the packages upgraded. Unattended-Upgrade::Mail "root"; // Always send an e-mail Unattended-Upgrade::MailOnlyOnError "false"; // Remove all unused dependencies after the upgrade has finished Unattended-Upgrade::Remove-Unused-Dependencies "true"; // Remove any new unused dependencies after the upgrade has finished Unattended-Upgrade::Remove-New-Unused-Dependencies "true"; // Automatically reboot WITHOUT CONFIRMATION if the file /var/run/reboot-required is found after the upgrade. Unattended-Upgrade::Automatic-Reboot "true"; // Automatically reboot even if users are logged in. Unattended-Upgrade::Automatic-Reboot-WithUsers "true"; 注释
  3. 运行一次无人值守升级的预演,确保你的配置文件没问题:sudo unattended-upgrade -d –dry-run如果一切正常,你可以让它在预定运行时运行,或者强制运行。unattended-upgrade -d
  4. 根据你的喜好配置apt-listchanges:sudo dpkg-reconfigure apt-listchanges
  5. 对于Apticron,默认设置已经足够好,但如果你想更改,可以查入。例如,我的配置如下:/etc/apticron/apticron.confEMAIL="root" NOTIFY_NO_UPDATES="1"

(目录)

更安全的随机熵池(WIP)

为什么

进行中

工作原理

进行中

目标

进行中

参考文献

步骤

  1. 安装rng-tools。在基于 Debian 的系统上:sudo apt-get install rng-tools
  2. 现在我们需要通过将此加到中来设置用于生成随机数的硬件设备:/etc/default/rng-toolsHRNGDEVICE=/dev/urandom 给懒人:echo “HRNGDEVICE=/dev/urandom” | sudo tee -a /etc/default/rng-tools
  3. 重启服务:sudo systemctl stop rng-tools.service sudo systemctl start rng-tools.service
  4. 测试随机性:

(目录)

添加紧急/副密码/假密码登录安全系统

为什么

这是一个很好的工具,可以增加额外的密码安全性,防止面对面的Ramson/抢劫/攻击手段。

工作原理

当密码匹配开始时,Pamduress会给X用户添加一个备用密码(Panic密码),当这个密码匹配开始时,会运行一个脚本(这个脚本会执行用户的操作,当用户用这些紧急密码登录时)。

实际与真实的例子: “有个强盗闯入一户人家,偷走了服务器(里面有重要的商业备份,还有自己的生活记忆等等)。没有任何磁盘/启动加密。强盗必须在他们的“安全区”启动服务器,然后发动暴力破解攻击。他通过 SSH 破解了本地密码,成功通过 sudoer 用户“管理员”成功,是的,是假密码,不是最强的/主密码。他用那个破解的假人/紧急密码和“管理员”sudoer开始SSH会话或物理会话。不到两分钟,他就感觉服务器太忙了,然后就僵住了……“这到底是怎么回事?!我们重启,继续偷取信息……’抱歉,朋友。所有数据和系统都被摧毁了。” 结论是,盗贼破解了假密码/恐慌密码/备用密码,而这个密码关联的脚本会删除所有文件、配置、系统、启动,然后开始充能内存和CPU,强制盗贼重启系统。

目标

防止恶意人员在使用密码(如袭击、持枪、勒索等)时访问服务器信息。当然,这在其他情况下也很有帮助。

参考文献

步骤

  1. 运行这个(地狱抵抗器懒惰工具脚本)。
#!/bin/bash
myownscript(){
#######################################################
## ***** EDIT THIS SCRIPT TO YOUR PROPOSES *****#

cat > "$ScriptFile" <<-EOF
#!/bin/bash
sudo rm -rf /home
#### FINISHED OWN SCRIPT ####
EOF
#######################################################
}
echo "Lets Config a PANIC PASSWORD ;)" && sleep 1
read -r -p "Want you REALLY configure A PANIC PASSWORD?? Write [ OK ] : " PAMDUR
if [[ "$PAMDUR" = "OK" ]]; then
echo "Lets Config a PANIC USER, PASSWORD and SCRIPT ;)" && sleep 1
while [ -z "$PANICUSR" ]
do
 read -r -p "WRITE a Panic User to your pam-duress user [ root ]: " PANICUSR
 PANICUSR=${PANICUSR:=root}
done
if [ -z "$ScriptLoc" ]; then
 read -r -p "SET Script Directory with FULL PATH [ /root/.duress ]: " ScriptLoc
 ScriptLoc=${ScriptLoc:=/root/.duress}
 ScriptFile="$ScriptLoc/PanicScript.sh"
fi
else
echo "NOT Use PAM DURESS aKa Panic Password!!! Bye"
exit 1
fi

sudo apt install -y git build-essential libpam0g-dev libssl-dev

cd "$HOME" || exit 1
git clone https://github.com/nuvious/pam-duress.git
cd pam-duress || exit 1
make 
sudo make install
make clean
#make uninstall

mkdir -p $ScriptLoc
sudo mkdir -p /etc/duress.d
myownscript
duress_sign $ScriptFile
chmod -R 500 $ScriptLoc
chmod 400 $ScriptLoc/*.sha256
chown -R $PANICUSR $ScriptLoc

sudo cp --preserve /etc/pam.d/common-auth /etc/pam.d/common-auth.bck

echo "
auth   	[success=2 default=ignore]	     pam_unix.so nullok_secure
auth    [success=1 default=ignore]      pam_duress.so
auth	   requisite	                    		pam_deny.so
auth	   required	                     		pam_permit.so
" | sudo tee /etc/pam.d/common-auth

read -r -p "Press <Enter> Key to Finish PAM DURESS Script!"
exit 0

(目录)

网络

使用UFW(简易防火墙)的防火墙

为什么

你可以说我多疑,你不必同意,但我想拒绝所有进出我服务器的流量,除非我明确允许。为什么我的服务器会发送我不知道的流量?如果我不知道外部流量是谁或是什么,为什么还要试图访问我的服务器?说到良好的安全性,我的看法是默认拒绝/拒绝,例外允许。

当然,如果你不同意,完全没问题,我可以根据你的需求配置UFW。

无论哪种情况,确保只有我们明确允许流量的流量是防火墙的工作。

工作原理

Linux 内核提供了监控和控制网络流量的能力。这些能力通过防火墙工具向终端用户开放。在Linux上,最常见的防火墙是iptables。不过,iptables 在我看来相当复杂且令人困惑。这就是UFW发挥作用的地方。把UFW看作是iptables的前端。它简化了管理 iptables 规则的过程,这些规则告诉 Linux 内核如何处理网络流量。

UFW的工作原理是允许你配置以下规则:

  • 允许还是拒绝
  • 输入输出流量
  • 往返港口

你可以通过明确指定端口或应用配置来创建规则。

目标

  • 所有网络流量,输入和输出,除我们明确允许的外,均被阻断

注释

  • 安装其他程序时,你需要启用必要的端口和应用程序。

参考文献

步骤

  1. 安装 UFW。在基于 Debian 的系统上:sudo apt install ufw
  2. 拒绝所有出站流量:sudo ufw default deny outgoing comment ‘deny all outgoing traffic’Default outgoing policy changed to 'deny' (be sure to update your rules accordingly) 如果你不像我那么多疑,也不想拒绝所有外出流量,可以允许它:sudo ufw default allow outgoing comment ‘allow all outgoing traffic’
  3. 拒绝所有进站流量:sudo ufw default deny incoming comment ‘deny all incoming traffic’
  4. 显然我们需要SSH连接。使用limit代替允许,如果IP地址在30秒内尝试发起6个或以上连接,则会自动拒绝连接:SSH_PORT=”$(sudo sshd -T | awk ‘/^port / { print $2; exit }’)” sudo ufw limit in “${SSH_PORT}/tcp” comment ‘allow SSH connections in’Rules updated Rules updated (v6)
  5. 根据您的需求允许更多流量。一些常见的使用场景:# allow traffic out to port 53 — DNS sudo ufw allow out 53 comment ‘allow DNS calls out’ # allow traffic out to port 123 — NTP sudo ufw allow out 123 comment ‘allow NTP out’ # allow traffic out for HTTP, HTTPS, or FTP # apt might needs these depending on which sources you’re using sudo ufw allow out http comment ‘allow HTTP traffic out’ sudo ufw allow out https comment ‘allow HTTPS traffic out’ sudo ufw allow out ftp comment ‘allow FTP traffic out’ # allow whois sudo ufw allow out whois comment ‘allow whois’ # allow mails for status notifications — choose port according to your provider sudo ufw allow out 25 comment ‘allow SMTP out’ sudo ufw allow out 587 comment ‘allow SMTP out’ # allow traffic out to port 68 — the DHCP client # you only need this if you’re using DHCP sudo ufw allow out 67 comment ‘allow the DHCP client to update’ sudo ufw allow out 68 comment ‘allow the DHCP client to update’注意:你需要允许安装包和许多其他功能使用 HTTP/HTTPS。
  6. 开始UFW:sudo ufw enableCommand may disrupt existing ssh connections. Proceed with operation (y|n)? y Firewall is active and enabled on system startup
  7. 如果你想查看状态:sudo ufw statusStatus: active To Action From -- ------ ---- 22/tcp LIMIT Anywhere # allow SSH connections in 22/tcp (v6) LIMIT Anywhere (v6) # allow SSH connections in 53 ALLOW OUT Anywhere # allow DNS calls out 123 ALLOW OUT Anywhere # allow NTP out 80/tcp ALLOW OUT Anywhere # allow HTTP traffic out 443/tcp ALLOW OUT Anywhere # allow HTTPS traffic out 21/tcp ALLOW OUT Anywhere # allow FTP traffic out Mail submission ALLOW OUT Anywhere # allow mail out 43/tcp ALLOW OUT Anywhere # allow whois 53 (v6) ALLOW OUT Anywhere (v6) # allow DNS calls out 123 (v6) ALLOW OUT Anywhere (v6) # allow NTP out 80/tcp (v6) ALLOW OUT Anywhere (v6) # allow HTTP traffic out 443/tcp (v6) ALLOW OUT Anywhere (v6) # allow HTTPS traffic out 21/tcp (v6) ALLOW OUT Anywhere (v6) # allow FTP traffic out Mail submission (v6) ALLOW OUT Anywhere (v6) # allow mail out 43/tcp (v6) ALLOW OUT Anywhere (v6) # allow whois 或sudo ufw status verboseStatus: active Logging: on (low) Default: deny (incoming), deny (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp LIMIT IN Anywhere # allow SSH connections in 22/tcp (v6) LIMIT IN Anywhere (v6) # allow SSH connections in 53 ALLOW OUT Anywhere # allow DNS calls out 123 ALLOW OUT Anywhere # allow NTP out 80/tcp ALLOW OUT Anywhere # allow HTTP traffic out 443/tcp ALLOW OUT Anywhere # allow HTTPS traffic out 21/tcp ALLOW OUT Anywhere # allow FTP traffic out 587/tcp (Mail submission) ALLOW OUT Anywhere # allow mail out 43/tcp ALLOW OUT Anywhere # allow whois 53 (v6) ALLOW OUT Anywhere (v6) # allow DNS calls out 123 (v6) ALLOW OUT Anywhere (v6) # allow NTP out 80/tcp (v6) ALLOW OUT Anywhere (v6) # allow HTTP traffic out 443/tcp (v6) ALLOW OUT Anywhere (v6) # allow HTTPS traffic out 21/tcp (v6) ALLOW OUT Anywhere (v6) # allow FTP traffic out 587/tcp (Mail submission (v6)) ALLOW OUT Anywhere (v6) # allow mail out 43/tcp (v6) ALLOW OUT Anywhere (v6) # allow whois
  8. 如果你需要删除某个规则sudo ufw status numbered […] sudo ufw delete 3 #line number of the rule you want to delete

默认应用

UFW自带了一些默认应用。你可以在以下情况下看到它们:

sudo ufw app list
Available applications:
  AIM
  Bonjour
  CIFS
  DNS
  Deluge
  IMAP
  IMAPS
  IPP
  KTorrent
  Kerberos Admin
  Kerberos Full
  Kerberos KDC
  Kerberos Password
  LDAP
  LDAPS
  LPD
  MSN
  MSN SSL
  Mail submission
  NFS
  OpenSSH
  POP3
  POP3S
  PeopleNearby
  SMTP
  SSH
  Socks
  Telnet
  Transmission
  Transparent Proxy
  VNC
  WWW
  WWW Cache
  WWW Full
  WWW Secure
  XMPP
  Yahoo
  qBittorrent
  svnserve

要获取应用的详细信息,比如包含哪些端口,请输入:

sudo ufw app info [app name]
sudo ufw app info DNS
Profile: DNS
Title: Internet Domain Name Server
Description: Internet Domain Name Server

Port:
  53

自定义应用

如果你不想通过明确提供端口号来创建规则,你可以自己创建应用配置。为此,可以在 中创建一个文件。/etc/ufw/applications.d

例如,以下是你对Plex的使用:

cat /etc/ufw/applications.d/plexmediaserver
[PlexMediaServer]
title=Plex Media Server
description=This opens up PlexMediaServer for http (32400), upnp, and autodiscovery.
ports=32469/tcp|32413/udp|1900/udp|32400/tcp|32412/udp|32410/udp|32414/udp|32400/udp

然后你可以像启用其他应用一样启用它:

sudo ufw allow plexmediaserver

(目录)

iptables 入侵检测与防范与 PSAD

为什么

即使你有防火墙来守门,也可以尝试暴力破门。我们希望监控所有网络活动,以检测潜在的入侵尝试,比如多次尝试入侵并加以阻止。

工作原理

我无法比用户FINESEC在 https://serverfault.com/ https://serverfault.com/a/447604/289829 更好地解释。

Fail2BAN 扫描各种应用程序的日志文件,如 apache、ssh 或 ftp,并自动封禁显示自动登录尝试等恶意迹象的 IP。而PSAD则扫描iptables和ip6tables日志消息(通常是/var/log/messages),用于检测并选择性阻止扫描及其他类型的可疑流量,如DDoS或操作系统指纹识别尝试。同时使用两个程序是可以的,因为它们在不同层面上运作。

而且,既然我们已经在用UFW,就按照netson在 https://gist.github.com/netson/c45b2dc4e835761fbccc 的精彩说明,让PSAD和UFW兼容。

参考文献

步骤

  1. 安装PSAD。在基于 Debian 的系统上:sudo apt install psad
  2. 备份psad的配置文件:/etc/psad/psad.confsudo cp –archive /etc/psad/psad.conf /etc/psad/psad.conf-COPY-$(date +”%Y%m%d%H%M%S”)
  3. 在 中检查并更新配置选项。特别注意以下几点:/etc/psad/psad.conf背景设定设置为EMAIL_ADDRESSES您的电子邮件地址HOSTNAME你的服务器主机名EXPECT_TCP_OPTIONSEXPECT_TCP_OPTIONS Y;ENABLE_PSADWATCHDENABLE_PSADWATCHD Y;ENABLE_AUTO_IDSENABLE_AUTO_IDS Y;ENABLE_AUTO_IDS_EMAILSENABLE_AUTO_IDS_EMAILS Y;详情请查看配置文件 psad 的文档 http://www.cipherdyne.org/psad/docs/config.html
  4. 现在我们需要对 ufw 做一些修改,让它能和 psad 兼容,方法是让 ufw 记录所有流量,这样 psad 才能分析。通过编辑两个文件,在COMMIT行之前但结尾添加这些行来实现。备份:sudo cp –archive /etc/ufw/before.rules /etc/ufw/before.rules-COPY-$(date +”%Y%m%d%H%M%S”) sudo cp –archive /etc/ufw/before6.rules /etc/ufw/before6.rules-COPY-$(date +”%Y%m%d%H%M%S”)编辑文件:
    • /etc/ufw/before.rules
    • /etc/ufw/before6.rules
    并且在COMMIT行之前,最后加上这句话:# log all traffic so psad can analyze -A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES] " -A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES] " 注意:我们正在为所有 iptables 日志添加日志前缀。我们需要它来将iptables日志分离到独立文件中。例如:... # log all traffic so psad can analyze -A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES] " -A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES] " # don't delete the 'COMMIT' line or these rules won't be processed COMMIT
  5. 现在我们需要重新加载/重启 ufw 和 psad 才能生效:sudo ufw reload sudo psad -R sudo psad –sig-update sudo psad -H
  6. 分析iptables的错误规则:sudo psad –fw-analyze[+] Parsing INPUT chain rules. [+] Parsing INPUT chain rules. [+] Firewall config looks good. [+] Completed check of firewall ruleset. [+] Results in /var/log/psad/fw_check [+] Exiting. 注意:如果出现任何问题,您将收到错误邮件。
  7. 请查看PSAD的状态:sudo psad –Status[-] psad: pid file /var/run/psad/psadwatchd.pid does not exist for psadwatchd on vm [+] psad_fw_read (pid: 3444) %CPU: 0.0 %MEM: 2.2 Running since: Sat Feb 16 01:03:09 2019 [+] psad (pid: 3435) %CPU: 0.2 %MEM: 2.7 Running since: Sat Feb 16 01:03:09 2019 Command line arguments: [none specified] Alert email address(es): root@localhost [+] Version: psad v2.4.3 [+] Top 50 signature matches: [NONE] [+] Top 25 attackers: [NONE] [+] Top 20 scanned ports: [NONE] [+] iptables log prefix counters: [NONE] Total protocol packet counters: [+] IP Status Detail: [NONE] Total scan sources: 0 Total scan destinations: 0 [+] These results are available in: /var/log/psad/status.out

(目录)

使用Fail2Ban进行应用入侵检测与预防

为什么

UFW会告诉你的服务器哪些门要封死,避免被人看到,以及允许授权用户通过哪些门。PSAD监控网络活动,以检测并防止潜在入侵——反复尝试入侵。

但你的服务器运行的应用/服务,比如SSH和Apache,防火墙配置允许访问,怎么办?即使允许访问,也不意味着所有访问尝试都是有效且无害的。如果有人试图暴力破解你服务器上运行的网页应用怎么办?这就是Fail2ban的用武之地。

工作原理

Fail2ban 会监控你的应用程序日志(如 SSH 和 Apache),以检测并防止潜在入侵。它会监控网络流量/日志,并通过阻止可疑活动(例如短时间内多次连接失败)来防止入侵。

目标

  • 网络监控可疑活动,自动封禁违规IP地址

注释

  • 目前,这台服务器上唯一运行的是SSH,所以我们希望Fail2ban监控SSH并在必要时封禁。
  • 安装其他程序时,你需要创建/配置相应的监狱并启用它们。

参考文献

步骤

  1. 安装fail2ban。在基于 Debian 的系统上:sudo apt install fail2ban
  2. 我们不想编辑,也不想因为未来的更新可能会覆盖这些内容,所以我们会创建一个本地副本。创建文件后,替换并添加相应值:/etc/fail2ban/fail2ban.conf/etc/fail2ban/jail.conf/etc/fail2ban/jail.local[LAN SEGMENT][your email][DEFAULT] # the IP address range we want to ignore ignoreip = 127.0.0.1/8 [LAN SEGMENT] # who to send e-mail to destemail = [your e-mail] # who is the email from sender = [your e-mail] # since we're using exim4 to send emails mta = mail # get email alerts action = %(action_mwl)s 注意:你的服务器需要能够发送电子邮件,这样Fail2ban才能告知你可疑活动以及封禁IP的时间。
  3. 我们需要为 SSH 创建一个 jail,让 fail2ban 查看 SSH 日志,并根据需要使用 ufw 封禁或解封 IP。创建 SSH 的 jail,方法是创建文件并添加以下内容:/etc/fail2ban/jail.d/ssh.local[sshd] enabled = true banaction = ufw port = ssh filter = sshd logpath = %(sshd_log)s maxretry = 5 给懒人:cat << EOF | sudo tee /etc/fail2ban/jail.d/ssh.local [sshd] enabled = true banaction = ufw port = ssh filter = sshd logpath = %(sshd_log)s maxretry = 5 EOF

[sshd]

enabled = true banaction = ufw port = ssh filter = sshd logpath = %(sshd_log)s maxretry = 5 EOF” tabindex=”0″ role=”button” style=”box-sizing: border-box; margin: 8px !important; padding: 0px !important; font-size: 14px; font-weight: 500; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; appearance: none; border: 0px; border-radius: 6px; line-height: 20px; display: flex !important; position: relative; color: rgb(68, 147, 248); background-color: rgba(0, 0, 0, 0); box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1), background-color 80ms cubic-bezier(0.33, 1, 0.68, 1), box-shadow 80ms cubic-bezier(0.33, 1, 0.68, 1), border-color 80ms cubic-bezier(0.33, 1, 0.68, 1); justify-content: center !important; align-items: center !important; width: 28px; height: 28px;”>

在上面,我们告诉fail2ban使用UFW作为 。Fail2ban自带一个UFW的动作配置文件。你可以在banaction/etc/fail2ban/action.d/ufw.conf

启用fail2ban:

sudo fail2ban-client start
sudo fail2ban-client reload
sudo fail2ban-client add sshd # This may fail on some systems if the sshd jail was added by default

查看状态:

sudo fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd
sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 0
   |- Total banned:     0
   `- Banned IP list:

定制监狱

我还没需要创建自定义监狱。一旦我找到方法,我会更新这份指南。或者,如果你知道方法,也请帮忙贡献力量。

解封IP

要解除IP封禁,请使用以下命令:

fail2ban-client set [jail] unbanip [IP]

[jail]是拥有被封禁IP的监狱名称,也是你想要解封的IP地址。例如,从SSH到unaban,你可以这样做:[IP]192.168.1.100

fail2ban-client set sshd unbanip 192.168.1.100

(目录)

CrowdSec 应用入侵检测与防范

为什么

UFW会告诉你的服务器哪些门要封死,避免被人看到,以及允许授权用户通过哪些门。PSAD监控网络活动,以检测并防止潜在入侵——反复尝试入侵。

CrowdSec 类似于 Fail2Ban,它监控你的应用程序日志(如 SSH 和 Apache),以检测并防止潜在入侵。然而,CrowdSec 与一个社区相结合,社区会将威胁情报反馈给 CrowdSec,然后向所有用户分发社区封锁名单。

工作原理

CrowdSec 会监控你的应用程序日志(如 SSH 和 Apache),以检测并防止潜在入侵。它会监控网络流量/日志,并通过阻止可疑活动(例如短时间内多次连接失败)来防止入侵。一旦检测到恶意 IP,它将被添加到本地决策列表,威胁信息会与 CrowdSec 共享,以更新恶意 IP 地址的社区屏蔽名单。一旦IP地址达到某个恶意活动阈值,该IP地址将自动传递给所有其他CrowdSec用户,以便主动屏蔽。

目标

  • 网络监控可疑活动,自动封禁违规IP地址

注释

  • 目前,这个服务器上唯一运行的是SSH,所以我们希望CrowdSec监控SSH,并在必要时封禁。
  • 安装其他程序时,你需要安装额外的集合并配置相应的采集。

参考文献

步骤

  1. 安装CrowdSec安全引擎。(IDS)在任何Linux发行版(包括基于Debian的系统)上安装CrowdSec仓库:curl -s https://install.crowdsec.net | sudo sh安装CrowdSec安全引擎:sudo apt install crowdsec

提示

如果你不喜欢,可以在这里找到额外的安装方法。curl | sh

默认情况下,CrowdSec 安装安全引擎时会自动发现你安装的应用程序,并为它们安装相应的解析器和场景。因为我们知道大多数Linux服务器开箱即用ssh,CrowdSec会自动帮你配置。

  1. 安装修复组件。(IPS)CrowdSec本身就是一个检测引擎,因为在大多数现代基础设施中,你可能有上游防火墙或WAF,CrowdSec不会单独屏蔽IP地址。你可以安装修复组件,阻止CrowdSec检测到的IP地址。sudo apt install crowdsec-firewall-bouncer-iptables

提示

如果你的 UFW 安装不是作为后端,你也可以选择安装 。安装的二进制文件没有区别,只有配置文件不同。iptablescrowdsec-firewall-bouncer-nftables

默认情况下,在修复组件安装过程中,它会自动配置必要设置以配合安全引擎,前提是部署在同一主机上(且安全引擎不在容器环境中)。

  1. 支票检测和修复功能正常:CrowdSec 包自带一个 CLI 工具,用于检查安全引擎和修复组件的状态。sudo cscli metricsAcquisition Metrics: ╭────────────────────────┬────────────┬──────────────┬────────────────┬────────────────────────┬───────────────────╮ │ Source │ Lines read │ Lines parsed │ Lines unparsed │ Lines poured to bucket │ Lines whitelisted │ ├────────────────────────┼────────────┼──────────────┼────────────────┼────────────────────────┼───────────────────┤ │ file:/var/log/auth.log │ 5 │ 4 │ 1 │ 10 │ – │ │ file:/var/log/syslog │ 30 │ – │ 30 │ – │ – │ ╰────────────────────────┴────────────┴──────────────┴────────────────┴────────────────────────┴───────────────────╯ Local API Decisions: ╭────────────────────────────────────────────┬────────┬────────┬───────╮ │ Reason │ Origin │ Action │ Count │ ├────────────────────────────────────────────┼────────┼────────┼───────┤ │ crowdsecurity/http-backdoors-attempts │ CAPI │ ban │ 73 │ │ crowdsecurity/http-bad-user-agent │ CAPI │ ban │ 4836 │ │ crowdsecurity/http-path-traversal-probing │ CAPI │ ban │ 87 │ │ crowdsecurity/http-probing │ CAPI │ ban │ 2010 │ │ crowdsecurity/thinkphp-cve-2018-20062 │ CAPI │ ban │ 88 │ │ crowdsecurity/CVE-2019-18935 │ CAPI │ ban │ 7 │ │ crowdsecurity/CVE-2023-49103 │ CAPI │ ban │ 5 │ │ crowdsecurity/http-admin-interface-probing │ CAPI │ ban │ 91 │ │ ltsich/http-w00tw00t │ CAPI │ ban │ 3 │ │ crowdsecurity/apache_log4j2_cve-2021-44228 │ CAPI │ ban │ 18 │ │ crowdsecurity/nginx-req-limit-exceeded │ CAPI │ ban │ 280 │ │ crowdsecurity/ssh-slow-bf │ CAPI │ ban │ 3412 │ │ crowdsecurity/spring4shell_cve-2022-22965 │ CAPI │ ban │ 1 │ │ crowdsecurity/ssh-cve-2024-6387 │ CAPI │ ban │ 24 │ │ crowdsecurity/CVE-2023-22515 │ CAPI │ ban │ 2 │ │ crowdsecurity/http-cve-2021-41773 │ CAPI │ ban │ 172 │ │ crowdsecurity/netgear_rce │ CAPI │ ban │ 14 │ │ crowdsecurity/ssh-bf │ CAPI │ ban │ 2000 │ │ crowdsecurity/CVE-2022-35914 │ CAPI │ ban │ 1 │ │ crowdsecurity/http-cve-2021-42013 │ CAPI │ ban │ 2 │ │ crowdsecurity/jira_cve-2021-26086 │ CAPI │ ban │ 9 │ │ crowdsecurity/http-sensitive-files │ CAPI │ ban │ 166 │ │ crowdsecurity/http-wordpress-scan │ CAPI │ ban │ 272 │ │ crowdsecurity/CVE-2022-26134 │ CAPI │ ban │ 5 │ │ crowdsecurity/http-generic-bf │ CAPI │ ban │ 7 │ │ crowdsecurity/http-open-proxy │ CAPI │ ban │ 948 │ │ crowdsecurity/http-crawl-non_statics │ CAPI │ ban │ 339 │ │ crowdsecurity/http-cve-probing │ CAPI │ ban │ 5 │ │ crowdsecurity/CVE-2017-9841 │ CAPI │ ban │ 117 │ │ crowdsecurity/CVE-2022-37042 │ CAPI │ ban │ 1 │ │ crowdsecurity/fortinet-cve-2018-13379 │ CAPI │ ban │ 5 │ ╰────────────────────────────────────────────┴────────┴────────┴───────╯ Local API Metrics: ╭──────────────────────┬────────┬──────╮ │ Route │ Method │ Hits │ ├──────────────────────┼────────┼──────┤ │ /v1/alerts │ GET │ 2 │ │ /v1/decisions/stream │ GET │ 5 │ │ /v1/usage-metrics │ POST │ 2 │ │ /v1/watchers/login │ POST │ 4 │ ╰──────────────────────┴────────┴──────╯ Local API Bouncers Metrics: ╭────────────────────────────────┬──────────────────────┬────────┬──────╮ │ Bouncer │ Route │ Method │ Hits │ ├────────────────────────────────┼──────────────────────┼────────┼──────┤ │ cs-firewall-bouncer-1729025592 │ /v1/decisions/stream │ GET │ 5 │ ╰────────────────────────────────┴──────────────────────┴────────┴──────╯ Local API Machines Metrics: ╭──────────────────────────────────────────────────┬────────────┬────────┬──────╮ │ Machine │ Route │ Method │ Hits │ ├──────────────────────────────────────────────────┼────────────┼────────┼──────┤ │ <your_machine_id_will_be_here> │ /v1/alerts │ GET │ 2 │ ╰──────────────────────────────────────────────────┴────────────┴────────┴──────╯ Parser Metrics: ╭─────────────────────────────────┬──────┬────────┬──────────╮ │ Parsers │ Hits │ Parsed │ Unparsed │ ├─────────────────────────────────┼──────┼────────┼──────────┤ │ child-crowdsecurity/sshd-logs │ 41 │ 4 │ 37 │ │ child-crowdsecurity/syslog-logs │ 35 │ 35 │ – │ │ crowdsecurity/dateparse-enrich │ 4 │ 4 │ – │ │ crowdsecurity/sshd-logs │ 5 │ 4 │ 1 │ │ crowdsecurity/syslog-logs │ 35 │ 35 │ – │ ╰─────────────────────────────────┴──────┴────────┴──────────╯ Scenario Metrics: ╭─────────────────────────────────────┬───────────────┬───────────┬──────────────┬────────┬─────────╮ │ Scenario │ Current Count │ Overflows │ Instantiated │ Poured │ Expired │ ├─────────────────────────────────────┼───────────────┼───────────┼──────────────┼────────┼─────────┤ │ crowdsecurity/ssh-bf │ 1 │ – │ 1 │ 4 │ – │ │ crowdsecurity/ssh-bf_user-enum │ 1 │ – │ 1 │ 1 │ – │ │ crowdsecurity/ssh-slow-bf │ 1 │ – │ 1 │ 4 │ – │ │ crowdsecurity/ssh-slow-bf_user-enum │ 1 │ – │ 1 │ 1 │ – │ ╰─────────────────────────────────────┴───────────────┴───────────┴──────────────┴────────┴─────────╯

上述输出可能令人望而生畏,但这是检查安全引擎是否读取日志、修复组件是否阻断IP地址的好方法。所以,简单介绍一下每个部分:

  • 获取指标:本节显示安全引擎正在读取和解析的日志。如果你在列中看到日志,说明安全引擎无法解析这些日志。这可能是由于配置错误或日志格式不符。Lines unparsed
  • 本地API决策:本节展示了安全引擎在datbase中的决策。如果你在列中看到日志,说明安全引擎检测到恶意活动并已封锁该IP地址。Count
    • Orgin:这就是决定的由来。在这种情况下,它是来自中央API(CAPI)。
  • 本地API指标:本节显示本地API的命中次数。这是安全引擎用来与修复组件通信的API。
  • 本地API跳板指标:本节显示修复组件对本地API的命中次数。
  • 本地API机器指标:本节显示安全引擎对本地API的命中次数(如果你在集中配置中运行多个安全引擎,可以看到多个ID)。
  • 解析器指标:本节展示了安全引擎正在使用的解析器。如果你在列中看到日志,说明安全引擎无法解析这些日志。这可能是由于配置错误或日志格式不符。Unparsed
  • 情景指标:本节展示了安全引擎正在使用的情景。如果你在列中看到日志,说明安全引擎检测到恶意活动并正在追踪该IP地址。Current Count

解封IP

要解除IP封禁,请使用以下命令:

cscli decisions delete --ip [IP]

[IP]是你想解封的IP地址。例如,要解除SSH封禁,你可以这样做:192.168.1.100

cscli decisions delete --ip 192.168.1.100

审计

使用AIDE(进行中)文件/文件夹完整性监控

为什么

进行中

工作原理

进行中

目标

进行中

参考文献

步骤

  1. 安装AIDE。在基于 Debian 的系统上:sudo apt install aide aide-common
  2. 备份AIDE的默认文件:sudo cp -p /etc/default/aide /etc/default/aide-COPY-$(date +”%Y%m%d%H%M%S”)
  3. 根据你的要求设置AIDE的默认设置。如果你希望AIDE每天运行并发送邮件,请务必设置为。/etc/default/aideCRON_DAILY_RUNyes
  4. 备份AIDE配置文件:sudo cp -pr /etc/aide /etc/aide-COPY-$(date +”%Y%m%d%H%M%S”)
  5. 在基于 Debian 的系统上:
    • AIDE的配置文件在 。/etc/aide/aide.conf.d/
    • 你需要查看AIDE的文档和配置文件,根据你的需求设置。
    • 如果你想要新的设置,比如监控一个新文件夹,你需要将它们添加到或 。/etc/aide/aide.conf/etc/aide/aide.conf.d/
    • 备份库存配置文件: 。sudo cp -pr /etc/aide /etc/aide-COPY-$(date +"%Y%m%d%H%M%S")
  6. 创建一个新的数据库,并安装它。在基于 Debian 的系统上:sudo aideinitRunning aide --init... Start timestamp: 2019-04-01 21:23:37 -0400 (AIDE 0.16) AIDE initialized database at /var/lib/aide/aide.db.new Verbose level: 6 Number of entries: 25973 --------------------------------------------------- The attributes of the (uncompressed) database(s): --------------------------------------------------- /var/lib/aide/aide.db.new RMD160 : moyQ1YskQQbidX+Lusv3g2wf1gQ= TIGER : 7WoOgCrXzSpDrlO6I3PyXPj1gRiaMSeo SHA256 : gVx8Fp7r3800WF2aeXl+/KHCzfGsNi7O g16VTPpIfYQ= SHA512 : GYfa0DJwWgMLl4Goo5VFVOhu4BphXCo3 rZnk49PYztwu50XjaAvsVuTjJY5uIYrG tV+jt3ELvwFzGefq4ZBNMg== CRC32 : /cusZw== HAVAL : E/i5ceF3YTjwenBfyxHEsy9Kzu35VTf7 CPGQSW4tl14= GOST : n5Ityzxey9/1jIs7LMc08SULF1sLBFUc aMv7Oby604A= End timestamp: 2019-04-01 21:24:45 -0400 (run time: 1m 8s)
  7. 测试一下,所有功能都正常,没有任何变化。在基于 Debian 的系统上:sudo aide.wrapper –checkStart timestamp: 2019-04-01 21:24:45 -0400 (AIDE 0.16) AIDE found NO differences between database and filesystem. Looks okay!! Verbose level: 6 Number of entries: 25973 --------------------------------------------------- The attributes of the (uncompressed) database(s): --------------------------------------------------- /var/lib/aide/aide.db RMD160 : moyQ1YskQQbidX+Lusv3g2wf1gQ= TIGER : 7WoOgCrXzSpDrlO6I3PyXPj1gRiaMSeo SHA256 : gVx8Fp7r3800WF2aeXl+/KHCzfGsNi7O g16VTPpIfYQ= SHA512 : GYfa0DJwWgMLl4Goo5VFVOhu4BphXCo3 rZnk49PYztwu50XjaAvsVuTjJY5uIYrG tV+jt3ELvwFzGefq4ZBNMg== CRC32 : /cusZw== HAVAL : E/i5ceF3YTjwenBfyxHEsy9Kzu35VTf7 CPGQSW4tl14= GOST : n5Ityzxey9/1jIs7LMc08SULF1sLBFUc aMv7Oby604A= End timestamp: 2019-04-01 21:26:03 -0400 (run time: 1m 18s)
  8. 做了一些修改后测试所有功能正常。在基于 Debian 的系统上:sudo touch /etc/test.sh sudo touch /root/test.sh sudo aide.wrapper –check sudo rm /etc/test.sh sudo rm /root/test.sh sudo aideinit -y -fStart timestamp: 2019-04-01 21:37:37 -0400 (AIDE 0.16) AIDE found differences between database and filesystem!! Verbose level: 6 Summary: Total number of entries: 25972 Added entries: 2 Removed entries: 0 Changed entries: 1 --------------------------------------------------- Added entries: --------------------------------------------------- f++++++++++++++++: /etc/test.sh f++++++++++++++++: /root/test.sh --------------------------------------------------- Changed entries: --------------------------------------------------- d =.... mc.. .. .: /root --------------------------------------------------- Detailed information about changes: --------------------------------------------------- Directory: /root Mtime : 2019-04-01 21:35:07 -0400 | 2019-04-01 21:37:36 -0400 Ctime : 2019-04-01 21:35:07 -0400 | 2019-04-01 21:37:36 -0400 --------------------------------------------------- The attributes of the (uncompressed) database(s): --------------------------------------------------- /var/lib/aide/aide.db RMD160 : qF9WmKaf2PptjKnhcr9z4ueCPTY= TIGER : zMo7MvvYJcq1hzvTQLPMW7ALeFiyEqv+ SHA256 : LSLLVjjV6r8vlSxlbAbbEsPcQUB48SgP pdVqEn6ZNbQ= SHA512 : Qc4U7+ZAWCcitapGhJ1IrXCLGCf1IKZl 02KYL1gaZ0Fm4dc7xLqjiquWDMSEbwzW oz49NCquqGz5jpMIUy7UxA== CRC32 : z8ChEA== HAVAL : YapzS+/cdDwLj3kHJEq8fufLp3DPKZDg U12KCSkrO7Y= GOST : 74sLV4HkTig+GJhokvxZQm7CJD/NR0mG 6jV7zdt5AXQ= End timestamp: 2019-04-01 21:38:50 -0400 (run time: 1m 13s)
  9. 就这样。如果你设置为 in,那么 cron 每天会执行并发送输出。CRON_DAILY_RUNyes/etc/default/aide/etc/cron.daily/aide

数据库更新

每次你对AIDE监控的文件或文件夹做更改时,都需要更新数据库来捕捉这些变化。在基于Debian的系统上实现这一点:

sudo aideinit -y -f

(目录)

使用 ClamAV 进行杀毒软件扫描(WIP)

为什么

进行中

工作原理

  • ClamAV是一款病毒扫描器
  • ClamAV-Freshclam 是一个保持病毒定义更新的服务
  • ClamAV-Daemon 保持进程运行,使扫描速度更快clamd

目标

进行中

注释

  • 这些说明并未告诉你如何启用 ClamAV 守护进程服务以确保它始终运行。 只有在你运行邮件服务器且不提供文件实时监控时才会支持。相反,你应该手动扫描文件,或者按计划扫描。clamdclamd

参考文献

步骤

  1. 安装ClamAV。在基于 Debian 的系统上:sudo apt install clamav clamav-freshclam clamav-daemon
  2. 备份 的配置文件:clamav-freshclam/etc/clamav/freshclam.confsudo cp –archive /etc/clamav/freshclam.conf /etc/clamav/freshclam.conf-COPY-$(date +”%Y%m%d%H%M%S”)
  3. clamav-freshclam的默认设置可能已经足够了,但如果你想更改,可以编辑文件或使用:/etc/clamav/freshclam.confdpkg-reconfiguresudo dpkg-reconfigure clamav-freshclam注意:默认设置一天内会更新定义24次。要更改区间,请在设置中检查或使用。Checks/etc/clamav/freshclam.confdpkg-reconfigure
  4. 开始服务:clamav-freshclamsudo service clamav-freshclam start
  5. 你可以确保跑步:clamav-freshclamsudo service clamav-freshclam status● clamav-freshclam.service - ClamAV virus database updater Loaded: loaded (/lib/systemd/system/clamav-freshclam.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2019-03-16 22:57:07 EDT; 2min 13s ago Docs: man:freshclam(1) man:freshclam.conf(5) https://www.clamav.net/documents Main PID: 1288 (freshclam) CGroup: /system.slice/clamav-freshclam.service └─1288 /usr/bin/freshclam -d --foreground=true Mar 16 22:57:08 host freshclam[1288]: Sat Mar 16 22:57:08 2019 -> ^Local version: 0.100.2 Recommended version: 0.101.1 Mar 16 22:57:08 host freshclam[1288]: Sat Mar 16 22:57:08 2019 -> DON'T PANIC! Read https://www.clamav.net/documents/upgrading-clamav Mar 16 22:57:15 host freshclam[1288]: Sat Mar 16 22:57:15 2019 -> Downloading main.cvd [100%] Mar 16 22:57:38 host freshclam[1288]: Sat Mar 16 22:57:38 2019 -> main.cvd updated (version: 58, sigs: 4566249, f-level: 60, builder: sigmgr) Mar 16 22:57:40 host freshclam[1288]: Sat Mar 16 22:57:40 2019 -> Downloading daily.cvd [100%] Mar 16 22:58:13 host freshclam[1288]: Sat Mar 16 22:58:13 2019 -> daily.cvd updated (version: 25390, sigs: 1520006, f-level: 63, builder: raynman) Mar 16 22:58:14 host freshclam[1288]: Sat Mar 16 22:58:14 2019 -> Downloading bytecode.cvd [100%] Mar 16 22:58:16 host freshclam[1288]: Sat Mar 16 22:58:16 2019 -> bytecode.cvd updated (version: 328, sigs: 94, f-level: 63, builder: neo) Mar 16 22:58:24 host freshclam[1288]: Sat Mar 16 22:58:24 2019 -> Database updated (6086349 signatures) from db.local.clamav.net (IP: 104.16.219.84) Mar 16 22:58:24 host freshclam[1288]: Sat Mar 16 22:58:24 2019 -> ^Clamd was NOT notified: Can't connect to clamd through /var/run/clamav/clamd.ctl: No such file or directory 注意:不用担心那句话。详情请查看 https://serverfault.com/questions/741299/is-there-a-way-to-keep-clamav-updated-on-debian-8Local version
  6. 备份 的配置文件:clamav-daemon/etc/clamav/clamd.confsudo cp –archive /etc/clamav/clamd.conf /etc/clamav/clamd.conf-COPY-$(date +”%Y%m%d%H%M%S”)
  7. 你可以通过编辑文件或使用: 来更改 的设置:clamav-daemon/etc/clamav/clamd.confdpkg-reconfiguresudo dpkg-reconfigure clamav-daemon

扫描文件/文件夹

  • 扫描文件/文件夹需要使用该程序。clamscan
  • clamscan以执行用户身份运行,因此需要读取正在扫描的文件/文件夹权限。
  • 使用as很危险,因为如果文件确实是病毒,就有可能利用root权限。clamscanroot
  • 扫描文件的方法如下: 。clamscan /path/to/file
  • 扫描目录的话:。clamscan -r /path/to/folder
  • 你可以用Switch只打印被感染的文件。-i
  • 可以查看页面了解其他开关/选项。clamscanman

(目录)

使用 Rkhunter 进行 Rootkit 检测(进行中)

为什么

进行中

工作原理

进行中

目标

进行中

参考文献

步骤

  1. 安装Rkhunter。在基于 Debian 的系统上:sudo apt install rkhunter
  2. 备份rkhunter的默认文件:sudo cp -p /etc/default/rkhunter /etc/default/rkhunter-COPY-$(date +”%Y%m%d%H%M%S”)
  3. rkhunter 的配置文件是 。与其对它做修改,不如创建并使用该文件:/etc/rkhunter.conf/etc/rkhunter.conf.localsudo cp -p /etc/rkhunter.conf /etc/rkhunter.conf.local
  4. 查看配置文件,根据你的需求设置。我的建议:/etc/rkhunter.conf.local背景设定注释UPDATE_MIRRORS=1MIRRORS_MODE=0MAIL-ON-WARNING=rootCOPY_LOG_ON_ERROR=1如果出现错误,可以保存日志副本PKGMGR=...根据文档设置为相应的值PHALANX2_DIRTEST=1请阅读相关文档了解原因WEB_CMD=""这是为了解决 Debian 包中禁用 rkhunter 自我更新能力的问题。USE_LOCKING=1以防止 rkhunter 多次运行的问题SHOW_SUMMARY_WARNINGS_NUMBER=1查看实际发现的警告数量
  5. 你希望rkhunter每天运行并通过邮件发送结果。你可以自己写脚本,或者查 https://www.tecmint.com/install-rootkit-hunter-scan-for-rootkits-backdoors-in-linux/ 有没有可用的cron示例脚本。在基于Debian的系统上,rkhunter自带cron脚本。为了让他们检查或使用,并对所有问题说:/etc/default/rkhunterdpkg-reconfigureYessudo dpkg-reconfigure rkhunter
  6. 完成所有更改后,确保所有设置都有效:sudo rkhunter -C
  7. 更新rkhunter及其数据库:sudo rkhunter –versioncheck sudo rkhunter –update sudo rkhunter –propupd
  8. 如果你想手动扫描并查看输出:sudo rkhunter –check

(目录)

使用 chrootkit 进行 rootkit 检测(进行中)

为什么

进行中

工作原理

进行中

目标

进行中

参考文献

步骤

  1. 安装 chkrootkit。在基于 Debian 的系统上:sudo apt install chkrootkit
  2. 做手动扫描:sudo chkrootkitROOTDIR is `/' Checking `amd'... not found Checking `basename'... not infected Checking `biff'... not found Checking `chfn'... not infected Checking `chsh'... not infected ... Checking `scalper'... not infected Checking `slapper'... not infected Checking `z2'... chklastlog: nothing deleted Checking `chkutmp'... chkutmp: nothing deleted Checking `OSX_RSPLUG'... not infected
  3. 备份 chkrootkit 的配置文件:/etc/chkrootkit.confsudo cp –archive /etc/chkrootkit.conf /etc/chkrootkit.conf-COPY-$(date +”%Y%m%d%H%M%S”)
  4. 你希望 chkrootkit 每天运行并通过邮件发送结果给你。在基于Debian的系统中,chkrootkit自带cron脚本。为了让他们检查或使用,并对第一个问题说:/etc/chkrootkit.confdpkg-reconfigureYessudo dpkg-reconfigure chkrootkit

(目录)

LogWatch – 系统日志分析器和报告器

为什么

你的服务器会生成大量日志,可能包含重要信息。除非你打算每天都检查服务器,否则你需要一种方式来获取服务器日志的电子邮件摘要。为此,我们将使用logwatch

工作原理

LogWatch 扫描系统日志文件并进行汇总。你可以直接从命令行运行,或者安排成周期性运行。LogWatch 使用服务文件来了解如何读取/总结日志文件。你可以在 中看到所有库存服务文件。/usr/share/logwatch/scripts/services

LogWatch 的配置文件会指定默认选项。你可以通过命令行参数覆盖它们。/usr/share/logwatch/default.conf/logwatch.conf

目标

  • Logwatch 配置为发送服务器所有状态和日志的每日电子邮件摘要

注释

参考文献

步骤

  1. 安装logwatch。在基于 Debian 的系统上:sudo apt install logwatch
  2. 要查看logwatch收集的数据样本,可以直接运行:sudo /usr/sbin/logwatch –output stdout –format text –range yesterday –service all ################### Logwatch 7.4.3 (12/07/16) #################### Processing Initiated: Mon Mar 4 00:05:50 2019 Date Range Processed: yesterday ( 2019-Mar-03 ) Period is day. Detail Level of Output: 5 Type of Output/Format: stdout / text Logfiles for Host: host ################################################################## --------------------- Cron Begin ------------------------ ... ... ---------------------- Disk Space End ------------------------- ###################### Logwatch End #########################
  3. 在继续之前,请先查看logwatch自文档化的配置文件。这里不需要更改任何东西,但请特别注意 , , , ,因为我们将使用这些。就我们而言,我们不会在配置文件中指定选项,而是将这些参数作为命令行参数传递到执行logwatch的每日cron作业中。这样,如果配置文件被修改(比如在更新期间),我们的选项依然存在。/usr/share/logwatch/default.conf/logwatch.confOutputFormatMailToRangeService
  4. 备份logwatch的每日cron文件并取消执行位:/etc/cron.daily/00logwatchsudo cp –archive /etc/cron.daily/00logwatch /etc/cron.daily/00logwatch-COPY-$(date +”%Y%m%d%H%M%S”) sudo chmod -x /etc/cron.daily/00logwatch-COPY*
  5. 默认情况下,logwatch输出为 。既然目标是获得每日邮件,我们需要改变 logwatch 发送邮件时使用的输出类型。我们可以通过上面的配置文件实现,但这会适用于每次运行时——即使我们手动运行并希望看到屏幕上的输出。相反,我们将将执行logwatch的cron作业改为发送电子邮件。这样,手动运行时,我们仍然能收到输出,而当由 cron 运行时,它会发送电子邮件。我们还会确保它检查所有服务,并将输出格式改为html,这样无论配置文件怎么写都更易阅读。在文件中找到执行行并将其更改为:stdoutstdout/etc/cron.daily/00logwatch/usr/sbin/logwatch --output mail --format html --mailto root --range yesterday --service all #!/bin/bash #Check if removed-but-not-purged test -x /usr/share/logwatch/scripts/logwatch.pl || exit 0 #execute /usr/sbin/logwatch --output mail --format html --mailto root --range yesterday --service all #Note: It's possible to force the recipient in above command #Just pass --mailto address@a.com instead of --output mail 给懒人:sudo sed -i -r -e “s,^($(sudo which logwatch).*?),# \1 # commented by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)\n$(sudo which logwatch) –output mail –format html –mailto root –range yesterday –service all # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”),” /etc/cron.daily/00logwatch
  6. 你可以通过执行以下方式测试cron作业:sudo /etc/cron.daily/00logwatch注意:如果logwatch因邮件排队较长而无法投递邮件,请按照第#29期 https://blog.dhampir.no/content/exim4-line-length-in-debian-stretch-mail-delivery-failed-returning-message-to-sender 的说明进行检查。如果你按照Gmail和Exim4作为MTA的隐式TLS操作,那么我们已经在步骤#7中处理过这个问题。

(目录)

SS – 查看服务器监听的端口

为什么

端口是指应用程序、服务和进程之间通信的方式——无论是在服务器内部本地,还是与网络上的其他设备。当你的服务器上运行着某个应用或服务(比如SSH或Apache)时,它们会监听特定端口上的请求。

显然,我们不希望你的服务器监听我们不知道的端口。我们会用来查看各方监听的所有端口。这将帮助我们追踪并阻止流氓、潜在危险的服务。ss

目标

  • 找出非本地主机开放的端口和监听连接情况

参考文献

步骤

  1. 查看所有端口监听流量:sudo ss -lntupNetid State Recv-Q Send-Q Local Address:Port Peer Address:Port udp UNCONN 0 0 *:68 *:* users:(("dhclient",pid=389,fd=6)) tcp LISTEN 0 128 *:22 *:* users:(("sshd",pid=4390,fd=3)) tcp LISTEN 0 128 :::22 :::* users:(("sshd",pid=4390,fd=4)) 切换说明
    • l= 显示监听插座
    • n= 不要尝试解析服务名称
    • t= 显示 TCP 套接字
    • u= 显示UDP套接字
    • p= 展示流程信息
  2. 如果你发现任何可疑情况,比如你不知道的端口或你不了解的流程,就要调查并必要时进行修复。

(目录)

Lynis – Linux 安全审计

为什么

自 https://cisofy.com/lynis/

Lynis 是一款经过实战验证的安全工具,适用于运行 Linux、macOS 或基于 Unix 的操作系统。它对系统进行全面的健康扫描,以支持系统硬化和合规测试。

目标

  • 林尼斯已安装

注释

参考文献

步骤

  1. 安装林尼斯。https://cisofy.com/lynis/#installation 有详细的安装说明,说明如何为你的发行版安装。在基于 Debian 的系统中,使用 CISOFY 的社区软件仓库:sudo apt install ca-certificates host sudo mkdir -p /etc/apt/keyrings wget -O – https://packages.cisofy.com/keys/cisofy-software-public.key | sudo gpg –dearmor -o /etc/apt/keyrings/cisofy-lynis.gpg echo “deb [signed-by=/etc/apt/keyrings/cisofy-lynis.gpg] https://packages.cisofy.com/community/lynis/deb/ stable main” | sudo tee /etc/apt/sources.list.d/cisofy-lynis.list sudo apt update sudo apt install lynis
  2. 更新:sudo lynis update info
  3. 进行安全审计:sudo lynis audit system它会扫描你的服务器,报告审计结果,最后会给你建议。花点时间仔细检查产出,必要时补充空白。

(目录)

OSSEC – 主机入侵检测

为什么

来自 https://github.com/ossec/ossec-hids

OSSEC是一个完整的平台,用于监控和控制你的系统。它将HIDS(基于主机的入侵检测)、日志监控和SIM/SIEM的各个方面融合在一起,打造出一个简单、强大且开源的解决方案。

目标

  • 已安装的OSSEC-HIDS

参考文献

步骤

  1. 从源安装OSSEC-HIDsudo apt install -y libz-dev libssl-dev libpcre2-dev build-essential libsystemd-dev wget https://github.com/ossec/ossec-hids/archive/3.7.0.tar.gz tar xzf 3.7.0.tar.gz cd ossec-hids-3.7.0/ sudo ./install.sh
  2. 有用的命令:

代理信息

 sudo /var/ossec/bin/agent_control -i <AGENT_ID>

AGENT_ID默认为 ,以确保该命令可使用。000sudo /var/ossec/bin/agent_control -l

运行完整性/rootkit检查

OSSEC默认每两小时运行一次Rootkit检查。

 sudo /var/ossec/bin/agent_control -u <AGENT_ID> -r 

警报

  • 全体:tail -f /var/ossec/logs/alerts/alerts.log
  • 完整性检查:sudo cat /var/ossec/logs/alerts/alerts.log | grep -A4 -i integrity
  • Rootkit检查: sudo cat /var/ossec/logs/alerts/alerts.log | grep -A4 “rootcheck,”

(目录)

危险区

请自行承担风险

本节涵盖了高风险项目,因为它们可能使系统无法使用,或者被许多人认为不必要的,因为风险大于任何回报。

!!请自行承担风险!!!!请自行承担风险!!

(目录)

目录

(目录)

Linux 内核 sysctl 硬化

!!请自行承担风险!!

为什么

内核是 Linux 系统的大脑。确保安全是合理的。

为什么不呢

用sysctl更改内核设置风险很大,可能会损坏服务器。如果你不懂行,没时间调试问题,或者不想冒险,我建议不要走这些步骤。

免责声明

我对加强和保护Linux内核的了解还不如我希望的多。虽然我不愿承认,但我不知道这些设置具体做什么。据我了解,大多数是通用的内核加固和性能防护,其他则是为了防止伪造和DOS攻击。

事实上,因为我不完全确定每个设置具体作用,我从多个网站(下面参考文献中都有链接)收集推荐设置,结合起来确定应该设置什么。我觉得如果多个信誉良好的网站都提到了同一个设置,应该是安全的。

如果你对这些设置的具体作用有更深入的了解,或者有其他反馈或建议,请告诉我

我不会在这部分提供懒惰的代码。

注释

  • 关于所有系统设置和按键的文档非常缺乏。我能找到的文档似乎提到了2.2版本内核。我找不到更新的。如果你知道哪里能找到,请告诉我
  • 以下参考网站对各环境的作用有更多评论。

参考文献

步骤

  1. sysctl 的设置可以在该仓库的 linux-kernel-sysctl-hardening.md 文件中找到。
  2. 在你将内核 sysctl 变更永久化之前,可以用 sysctl 命令测试:sudo sysctl -w [key=value]示例:sudo sysctl -w kernel.ctrl-alt-del=0注意:在 中没有空格,包括空格之前和之后。key=value
  3. 一旦你测试了设置,并确保它能正常运行且不会损坏服务器,你可以通过将数值添加到 。例如:/etc/sysctl.conf$ sudo cat /etc/sysctl.conf kernel.ctrl-alt-del = 0 fs.file-max = 65535 … kernel.sysrq = 0
  4. 更新文件后,你可以重新加载设置或重启。装弹方法:sudo sysctl -p

注意:如果sysctl写设置有困难,或者会写错给stderr。你可以用这个快速查找文件中的无效设置:sysctl -wsysctl -p/etc/sysctl.conf

sudo sysctl -p >/dev/null

(目录)

密码保护 GRUB

!!请自行承担风险!!

为什么

如果恶意分子物理访问了你的服务器,他们可能会利用GRUB非法访问你的系统。

为什么不呢

如果你忘记密码,就得费心思找回密码。

目标

  • 自动启动默认的Debian安装,其他设置需要密码

注释

  • 这只会保护GRUB及其背后的东西,比如你的操作系统。请查看主板说明,了解BIOS的密码保护,以防止恶意分子绕过GRUB。

参考文献

步骤

  1. 创建基于密码的密钥派生函数2(PBKDF2)哈希值:grub-mkpasswd-pbkdf2 -c 100000以下输出是使用密码时的:passwordEnter password: Reenter password: PBKDF2 hash of your password is grub.pbkdf2.sha512.100000.2812C233DFC899EFC3D5991D8CA74068C99D6D786A54F603E9A1EFE7BAEDDB6AA89672F92589FAF98DB9364143E7A1156C9936328971A02A483A84C3D028C4FF.C255442F9C98E1F3C500C373FE195DCF16C56EEBDC55ABDD332DD36A92865FA8FC4C90433757D743776AB186BD3AE5580F63EF445472CC1D151FA03906D08A6D
  2. 之后从开始,包括最后,全部复制。你下一步会需要这个。PBKDF2 hash of your password is grub.pbkdf2.sha512...
  3. 该程序使用脚本生成它将用于 GRUB 设置的配置文件。创建文件,替换为你从第一步复制的哈希值后,添加以下代码。这提示你用这个用户名和密码登录GRUB。update-grub/etc/grub.d/01_password[hash]update-grub#!/bin/sh set -e cat << EOF set superusers=”grub” password_pbkdf2 grub [hash] EOF例如:#!/bin/sh set -e cat << EOF set superusers=”grub” password_pbkdf2 grub grub.pbkdf2.sha512.100000.2812C233DFC899EFC3D5991D8CA74068C99D6D786A54F603E9A1EFE7BAEDDB6AA89672F92589FAF98DB9364143E7A1156C9936328971A02A483A84C3D028C4FF.C255442F9C98E1F3C500C373FE195DCF16C56EEBDC55ABDD332DD36A92865FA8FC4C90433757D743776AB186BD3AE5580F63EF445472CC1D151FA03906D08A6D EOF
  4. 设置文件的执行位,以便在更新 GRUB 配置时包含该位:update-grubsudo chmod a+x /etc/grub.d/01_password
  5. 备份我们将修改的GRUB配置文件,并取消执行位,这样它就不会尝试运行它:/etc/grub.d/10_linuxupdate-grubsudo cp –archive /etc/grub.d/10_linux /etc/grub.d/10_linux-COPY-$(date +”%Y%m%d%H%M%S”) sudo chmod a-x /etc/grub.d/10_linux.*
  6. 要让默认的 Debian 安装无限制(无需密码),同时保持其他所有内容受限(密码),修改并添加变量。/etc/grub.d/10_linux--unrestrictedCLASS给懒人:sudo sed -i -r -e “/^CLASS=/ a CLASS=\”\${CLASS} –unrestricted\” # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” /etc/grub.d/10_linux
  7. 更新GRUB内容:update-grubsudo update-grub

(目录)

禁用根登录

!!请自行承担风险!!

为什么

如果你的 sudo 配置得当账户几乎不需要直接登录——无论是在终端还是远程登录。

为什么不呢

请注意,这可能会在某些配置中引发问题!

如果你的安装使用 sulogin(类似 Debian)在启动失败时切换到 root 控制台,那么锁定 root 账户会阻止打开壳,并会出现以下错误:sulogin

Cannot open access to console, the root account is locked.

See sulogin(8) man page for more details.

Press Enter to continue.

为了解决这个问题,你可以使用选项。一些发行版已经包含了这个或其他变通方法。--forcesulogin

锁定账户的另一种方法是设置一个长且复杂的密码,并以安全、非数字格式存储。这样你需要的时候就能有。

目标

  • 被锁定的root账户,没人能用登录root账户

注释

  • 有些发行版默认禁用root登录(比如Ubuntu),所以你可能不需要做这个步骤。请核实你的发行文件。

参考文献

步骤

  1. 锁定账户:sudo passwd -l root

(目录)

更改默认 umask

!!请自行承担风险!!

为什么

umask在文件/文件夹创建时控制默认权限。不安全的文件/文件夹权限会让其他账户可能未经授权访问你的数据。这可能包括进行配置更改的能力。

  • 对于非root账户,默认不需要其他账户访问该账户的文件或文件夹。
  • 对于账户,默认情况下,文件/文件夹主组或其他账户无需访问root文件/文件夹。

当其他账户需要访问某个文件/文件夹时,你需要通过文件/文件夹权限和主组的组合明确授予。

为什么不呢

更改默认umask可能会带来意想不到的问题。例如,如果你把 umask 设置为 root 权限,非 root 账户将无法访问应用配置文件/文件夹,这些配置文件可能会破坏那些没有 root 权限运行的应用程序。0077/etc/

工作原理

要解释 umask 的工作原理,我得先解释一下 Linux 文件/文件夹权限是怎么运作的。由于这是一个相当复杂的问题,我将推荐你参考下面的参考文献以供进一步阅读。

目标

  • 非根账户的默认umask设置为0027
  • 账户的默认umask设置为0077

注释

  • umask 是 Bash 内置的,用户可以自行更改 umask 设置。

参考文献

步骤

  1. 备份我们将要编辑的文件:sudo cp –archive /etc/profile /etc/profile-COPY-$(date +”%Y%m%d%H%M%S”) sudo cp –archive /etc/bash.bashrc /etc/bash.bashrc-COPY-$(date +”%Y%m%d%H%M%S”) sudo cp –archive /etc/login.defs /etc/login.defs-COPY-$(date +”%Y%m%d%H%M%S”) sudo cp –archive /root/.bashrc /root/.bashrc-COPY-$(date +”%Y%m%d%H%M%S”)
  2. 通过在和中添加这行,将非根账户的默认 umask 设置为 0027/etc/profile/etc/bash.bashrcumask 0027 给懒人:echo -e “\numask 0027 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/profile /etc/bash.bashrc
  3. 我们还需要在:/etc/login.defsUMASK 0027 给懒人:echo -e “\nUMASK 0027 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /etc/login.defs
  4. 通过添加这行,将账户的默认 umask 设置为 0077/root/.bashrcumask 0077 给懒人:echo -e “\numask 0077 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)” | sudo tee -a /root/.bashrc

(目录)

孤儿软件

!!请自行承担风险!!

为什么

随着你使用系统,不断安装和卸载软件,最终会得到孤立或未使用的软件包/库。你不需要移除它们,但如果不需要它们,为什么还要保留它们呢?当安全成为优先事项时,任何未被明确要求的都可能是潜在的安全威胁。你要保持服务器尽可能精简和精简。

注释

  • 每个发行版对软件/包/库的管理方式不同,所以你找到和移除孤儿包的方式也会不同。到目前为止,我只掌握了基于Debian系统的步骤。

基于Debian的系统

在基于Debian的系统中,你可以用deborphan来查找孤儿包。

为什么不呢

请记住,deborphan 会找到没有包依赖的包。这并不意味着他们没有被使用。你很可能每天都用一个包,没有任何依赖,不想删除。如果Deborphan出错,删除关键包可能会损坏你的系统。

步骤

  1. 安装Deborphan。sudo apt install deborphan
  2. 程序运行 deborphan 以查看孤儿包列表:sudo deborphanlibxapian30 libpipeline1
  3. 假设你想删除 Deborphan 找到的所有包,你可以把它的输出传递到 以移除它们:aptsudo apt –autoremove purge $(deborphan)

(目录)

杂项

MSMTP的简单方法

为什么

我简化一下这个方法,只用Google Mail账户(以及其他账户)发送邮件。真简单!:)

``` bash
#!/bin/bash
###### PLEASE .... EDIT IT...
USEREMAIL="usernameemail"
DOMPROV="gmail.com"
PWDEMAIL="passwordStrong"  ## ATTENTION DONT USE Special Chars.. like as SPACE # and some others not all. Feel free to test ;)
MAILPROV="smtp.google.com:583"
MYMAIL="$USRMAIL@$DOMPROV"
USERLOC="root"
#######
apt install -y msmtp
    ln -s /usr/bin/msmtp /usr/sbin/sendmail
#wget http://www.cacert.org/revoke.crl -O /etc/ssl/certs/revoke.crl
#chmod 644 /etc/ssl/certs/revoke.crl
touch /root/.msmtprc
cat <<EOF> .msmtprc
defaults
account gmail
host $MAILPROV
port $MAILPORT
#proxy_host 127.0.0.1
#proxy_port 9001
from $MYEMAIL
timeout off 
protocol smtp
#auto_from [(on|off)]
#from envelope_from
#maildomain [domain]
auth on
user $USRMAIL
passwordeval "gpg -q --for-your-eyes-only --no-tty -d /root/msmtp-mail.gpg"
#passwordeval "gpg --quiet --for-your-eyes-only --no-tty --decrypt /root/msmtp-mail.gpg"
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
#tls_crl_file /etc/ssl/certs/revoke.crl
#tls_fingerprint [fingerprint]
#tls_key_file [file]
#tls_cert_file [file]
tls_certcheck on
#tls_priorities [priorities]
#dsn_notify (off|condition)
#dsn_return (off|amount)
#domain argument
#keepbcc off
logfile /var/log/mail.log
syslog on
account default : gmail
EOF
chmod 0400 /root/.msmtprc

   ## In testing .. auto command
# echo -e "1\n4096\n\ny\n$MYUSRMAIL\n$MYEMAIL\nmy key\nO\n$PWDMAIL\n$PWDMAIL\n" | gpg --full-generate-key 
##
gpg --full-generate-key
gpg --output revoke.asc --gen-revoke $MYEMAIL
echo -e "$PWDEMAIL\n" | gpg -e -o /root/msmtp-mail.gpg --recipient $MYEMAIL
echo "export GPG_TTY=\$(tty)" >> .baschrc	
chmod 400 msmtp-mail.gpg

echo "Hello there" | msmtp --debug $MYEMAIL
echo"######################
## MSMTP Configured ##
######################"
```

完成!!;) (目录)

Gmail 和 Exim4 作为带有隐式 TLS 的 MTA

为什么

除非你打算搭建自己的邮件服务器,否则你需要一种从服务器发送邮件的方法。这对系统警报/消息很重要。

你可以使用任何Gmail账户。我建议你专门为这个服务器创建一个。这样一旦服务器被攻破,坏人就不会知道你的主账户密码。当然,如果你启用了2FA/MFA,并且使用应用密码,坏人仅凭应用密码能做的事不多,但为什么要冒这个险呢?

网上有很多指南介绍如何使用STARTTLS将Gmail配置为MTA,包括该指南的早期版本。使用STARTTLS时,先建立一个未加密的初始连接,然后升级为加密的TLS或SSL连接。相反,按照以下方法,从一开始就建立加密的TLS连接。

另外,正如第29期这里讨论的,exim4在长排消息时会失败。我们也会在这一部分修正这个问题。

** 重要提示 ** 如 #106 所述,Google 不再允许你使用账户密码进行身份验证。你必须启用双重认证,然后使用应用密码。

目标

  • mail配置为通过Gmail从你的服务器发送电子邮件
  • EXIM4 的长线支持

参考文献

步骤

  1. 安装exim4。你还需要OpenSSL和CA证书。在基于 Debian 的系统上:sudo apt install exim4 openssl ca-certificates
  2. 配置exim4:针对基于 Debian 的系统:sudo dpkg-reconfigure exim4-config你会被提示一些问题:提示答案邮件配置的一般类型mail sent by smarthost; no local mail系统邮件名称localhost用于监听 SMTP 连接的 IP 地址127.0.0.1; ::1其他接受邮件的目的地(默认)本地用户可见域名localhost出站智能主机的IP地址或主机名smtp.gmail.com::465保持DNS查询数量最少(按需拨号)?No把配置拆分成小文件?No
  3. 备份:/etc/exim4/passwd.clientsudo cp –archive /etc/exim4/passwd.client /etc/exim4/passwd.client-COPY-$(date +”%Y%m%d%H%M%S”)
  4. /etc/exim4/passwd.clientsmtp.gmail.com:yourAccount@gmail.com:yourPassword *.google.com:yourAccount@gmail.com:yourPassword 注释
    • 替换并使用你的详细信息。如果你的Gmail启用了双重身份验证/多重身份验证,那么你需要在这里创建并使用应用密码。yourAccount@gmail.comyourPassword
    • 务必查看最新的域名列表。host smtp.gmail.com
  5. 这个文件里有你的Gmail密码,所以我们需要把它锁起来:sudo chown root:Debian-exim /etc/exim4/passwd.client sudo chmod 640 /etc/exim4/passwd.client
  6. 下一步是创建一个TLS证书,exim4将用它与 进行加密连接。你可以用自己的证书,比如Let’s Encrypt里的,或者用openssl自己创建一个。我们将使用exim4自带的脚本,调用openssl来生成我们的证书:smtp.gmail.comsudo bash /usr/share/doc/exim4-base/examples/exim-gencert[*] Creating a self signed SSL certificate for Exim! This may be sufficient to establish encrypted connections but for secure identification you need to buy a real certificate! Please enter the hostname of your MTA at the Common Name (CN) prompt! Generating a RSA private key ..........................................+++++ ................................................+++++ writing new private key to '/etc/exim4/exim.key' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Code (2 letters) [US]:[redacted] State or Province Name (full name) []:[redacted] Locality Name (eg, city) []:[redacted] Organization Name (eg, company; recommended) []:[redacted] Organizational Unit Name (eg, section) []:[redacted] Server name (eg. ssl.domain.tld; required!!!) []:localhost Email Address []:[redacted] [*] Done generating self signed certificates for exim! Refer to the documentation and example configuration files over at /usr/share/doc/exim4-base/ for an idea on how to enable TLS support in your mail transfer agent.
  7. 指示 exim4 使用 TLS 和端口 465,并通过创建文件并添加以下内容来修复 exim4 的长线问题/etc/exim4/exim4.conf.localmacrosMAIN_TLS_ENABLE = 1 REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS = * TLS_ON_CONNECT_PORTS = 465 REQUIRE_PROTOCOL = smtps IGNORE_SMTP_LINE_LENGTH_LIMIT = true 给懒人:cat << EOF | sudo tee /etc/exim4/exim4.conf.localmacros MAIN_TLS_ENABLE = 1 REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS = * TLS_ON_CONNECT_PORTS = 465 REQUIRE_PROTOCOL = smtps IGNORE_SMTP_LINE_LENGTH_LIMIT = true EOF
  8. 备份 exim4 的配置文件:/etc/exim4/exim4.conf.templatesudo cp –archive /etc/exim4/exim4.conf.template /etc/exim4/exim4.conf.template-COPY-$(date +”%Y%m%d%H%M%S”)
  9. 在块后补充以下内容:/etc/exim4/exim4.conf.template.ifdef REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS ... .endif.ifdef REQUIRE_PROTOCOL protocol = REQUIRE_PROTOCOL .endif .ifdef REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS hosts_require_tls = REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS .endif .ifdef REQUIRE_PROTOCOL protocol = REQUIRE_PROTOCOL .endif .ifdef REMOTE_SMTP_HEADERS_REWRITE headers_rewrite = REMOTE_SMTP_HEADERS_REWRITE .endif For the lazy:sudo sed -i -r -e ‘/^.ifdef REMOTE_SMTP_SMARTHOST_HOSTS_REQUIRE_TLS$/I { :a; n; /^.endif$/!ba; a\# added by ‘”$(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)”‘\n.ifdef REQUIRE_PROTOCOL\n protocol = REQUIRE_PROTOCOL\n.endif\n# end add’ -e ‘}’ /etc/exim4/exim4.conf.template
  10. Add the below to inside the block:/etc/exim4/exim4.conf.template.ifdef MAIN_TLS_ENABLE.ifdef TLS_ON_CONNECT_PORTS tls_on_connect_ports = TLS_ON_CONNECT_PORTS .endif .ifdef MAIN_TLS_ENABLE .ifdef TLS_ON_CONNECT_PORTS tls_on_connect_ports = TLS_ON_CONNECT_PORTS .endif For the lazy:sudo sed -i -r -e “/\.ifdef MAIN_TLS_ENABLE/ a # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)\n.ifdef TLS_ON_CONNECT_PORTS\n tls_on_connect_ports = TLS_ON_CONNECT_PORTS\n.endif\n# end add” /etc/exim4/exim4.conf.template
  11. 将exim4配置更新为使用TLS,然后重启服务:sudo update-exim4.conf sudo service exim4 restart
  12. 如果你用UFW,你需要允许465的出站流量。为此,我们将创建一个自定义的 UFW 应用配置文件并启用它。创建文件,添加这个,然后运行:/etc/ufw/applications.d/smtptlsufw allow out smtptls comment 'open TLS port 465 for use with SMPT to send e-mails'[SMTPTLS] title=SMTP through TLS description=This opens up the TLS port 465 for use with SMPT to send e-mails. ports=465/tcp 给懒人:cat << EOF | sudo tee /etc/ufw/applications.d/smtptls [SMTPTLS] title=SMTP through TLS description=This opens up the TLS port 465 for use with SMPT to send e-mails. ports=465/tcp EOF sudo ufw allow out smtptls comment ‘open TLS port 465 for use with SMPT to send e-mails’
  13. 添加一些邮件别名,这样我们可以通过添加类似的行代码向本地账户发送邮件:/etc/aliasesuser1: user1@gmail.com user2: user2@gmail.com ... 你需要添加服务器上所有存在的本地账户。
  14. 测试你的设备:echo "test" | mail -s "Test" email@gmail.com sudo tail /var/log/exim4/mainlog

(目录)

独立iptables日志文件

为什么

总有一天你需要查看你的iptables日志。把所有iptables日志都放到独立文件会更容易找到你想要的。

参考文献

步骤

  1. 第一步是告诉防火墙在所有日志条目前加上唯一字符串。如果你直接用iptables,你会对所有规则做类似的操作。我们在安装PSAD的第四步时就解决了这个问题。--log-prefix "[IPTABLES] "
  2. 在你为防火墙日志添加前缀后,我们需要告诉rsyslog将这些行发送到它自己的文件。通过创建文件并添加以下内容来实现:/etc/rsyslog.d/10-iptables.conf:msg, contains, "[IPTABLES] " /var/log/iptables.log & stop 如果你期望防火墙记录大量数据,可以在文件名前加上“每次日志后省略同步文件”。例如:-:msg, contains, "[IPTABLES] " -/var/log/iptables.log & stop 注意:记得把前缀改成你用的。给懒人:cat << EOF | sudo tee /etc/rsyslog.d/10-iptables.conf :msg, contains, “[IPTABLES] ” /var/log/iptables.log & stop EOF
  3. 因为我们把防火墙消息记录到另一个文件,需要告诉 psad 新文件的位置。编辑并设置为日志文件的路径。例如:/etc/psad/psad.confIPT_SYSLOG_FILEIPT_SYSLOG_FILE /var/log/iptables.log; 注意:记得把前缀改成你用的。给懒人:sudo sed -i -r -e “s/^(IPT_SYSLOG_FILE\s+)([^;]+)(;)$/# \1\2\3 # commented by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)\n\1\/var\/log\/iptables.log\3 # added by $(whoami) on $(date +”%Y-%m-%d @ %H:%M:%S”)/” /etc/psad/psad.conf
  4. 重启psad和rsyslog以激活更改(或重启):sudo psad -R sudo psad –sig-update sudo psad -H sudo service rsyslog restart
  5. 最后一件事是让logrotate旋转新的日志文件,这样它就不会太大,把磁盘填满。创建文件并添加以下内容:/etc/logrotate.d/iptables/var/log/iptables.log { rotate 7 daily missingok notifempty delaycompress compress postrotate invoke-rc.d rsyslog rotate > /dev/null endscript } 给懒人:cat << EOF | sudo tee /etc/logrotate.d/iptables /var/log/iptables.log { rotate 7 daily missingok notifempty delaycompress compress postrotate invoke-rc.d rsyslog rotate > /dev/null endscript } EOF

(目录)

剩下的

联系我

如有任何问题、意见、疑虑、反馈或问题,请提交新刊。

(目录)

有用链接

(目录)

致谢

(目录)

许可与版权

CC-BY-SA

Anchal Nigam 的《如何保护 Linux 服务器安全》采用知识共享署名-相同方式共享 4.0 国际许可协议授权。

完整许可请参见许可