From 5b9b466cb905f64ea773348c3de2f2cf839936bf Mon Sep 17 00:00:00 2001 From: midoks Date: Thu, 13 Apr 2023 14:39:18 +0800 Subject: [PATCH] =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=8A=A0=E5=9B=BA=E6=94=BE?= =?UTF-8?q?=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 - plugins/system_safe/.gitignore | 162 +++ plugins/system_safe/LICENSE | 73 ++ plugins/system_safe/README.md | 19 + plugins/system_safe/conf/config.json | 958 ++++++++++++++ plugins/system_safe/ico.png | Bin 0 -> 812 bytes plugins/system_safe/index.html | 24 + plugins/system_safe/info.json | 20 + .../init.d/system_safe.service.tpl | 15 + plugins/system_safe/init.d/system_safe.tpl | 94 ++ plugins/system_safe/install.sh | 47 + plugins/system_safe/js/app.js | 606 +++++++++ plugins/system_safe/system_safe.py | 1140 +++++++++++++++++ route/templates/default/config.html | 4 +- 14 files changed, 3160 insertions(+), 3 deletions(-) create mode 100644 plugins/system_safe/.gitignore create mode 100644 plugins/system_safe/LICENSE create mode 100644 plugins/system_safe/README.md create mode 100755 plugins/system_safe/conf/config.json create mode 100644 plugins/system_safe/ico.png create mode 100755 plugins/system_safe/index.html create mode 100755 plugins/system_safe/info.json create mode 100644 plugins/system_safe/init.d/system_safe.service.tpl create mode 100644 plugins/system_safe/init.d/system_safe.tpl create mode 100755 plugins/system_safe/install.sh create mode 100644 plugins/system_safe/js/app.js create mode 100755 plugins/system_safe/system_safe.py diff --git a/.gitignore b/.gitignore index a79627090..466df64ae 100644 --- a/.gitignore +++ b/.gitignore @@ -161,7 +161,6 @@ plugins/own_* plugins/my_* plugins/l2tp plugins/openlitespeed -plugins/system_safe plugins/tamper_proof plugins/tamper_proof_* plugins/cryptocurrency_trade diff --git a/plugins/system_safe/.gitignore b/plugins/system_safe/.gitignore new file mode 100644 index 000000000..5d381cc48 --- /dev/null +++ b/plugins/system_safe/.gitignore @@ -0,0 +1,162 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/plugins/system_safe/LICENSE b/plugins/system_safe/LICENSE new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/plugins/system_safe/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/plugins/system_safe/README.md b/plugins/system_safe/README.md new file mode 100644 index 000000000..18671a83b --- /dev/null +++ b/plugins/system_safe/README.md @@ -0,0 +1,19 @@ +# plugins_system_safe + +系统加固插件 + +# DEBUG +``` + +https://code_hosting_007.midoks.me/midoks/plugins_system_safe + +ln -s /www/git/midoks/plugins_system_safe /www/server/mdserver-web/plugins/system_safe + +ln -s /www/wwwroot/midoks/plugins_system_safe /www/server/mdserver-web/plugins/system_safe + + +python3 /www/server/mdserver-web/plugins/system_safe/index.py bg_start + +systemctl daemon-reload +``` + diff --git a/plugins/system_safe/conf/config.json b/plugins/system_safe/conf/config.json new file mode 100755 index 000000000..85c35c00e --- /dev/null +++ b/plugins/system_safe/conf/config.json @@ -0,0 +1,958 @@ +{ + "open": false, + "service": { + "open": true, + "name": "服务加固", + "ps": "保护系统服务,开启后将无法添加和删除服务,部分软件无法安装!", + "paths": [ + { + "path": "/etc/rc.d", + "chattr": "i", + "s_mode": 509, + "d_mode": 509 + }, + { + "path": "/etc/rc.d/init.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc0.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc1.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc2.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc3.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc4.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc5.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc6.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc.d/rc.local", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/init.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc0.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc1.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc2.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc3.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc4.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc5.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rc6.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/rcS.d", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/etc/systemd", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + }, + { + "path": "/lib/systemd", + "chattr": "i", + "s_mode": 493, + "d_mode": 493 + } + ] + }, + "home": { + "open": true, + "name": "环境变量加固", + "ps": "保护用户环境变量不被修改,开启后无法自定义用户环境变量!", + "paths": [ + { + "path": "/root/.bash_history", + "chattr": "a", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/root/.bashrc", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/root/.bash_logout", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/root/.bash_profile", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/root/.profile", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/profile", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/bash.bashrc", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/sysctl.conf", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/sysctl.d", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + } + ] + }, + "user": { + "open": true, + "name": "用户加固", + "ps": "保护用户,开启后将无法添加删除用户和修改用户密码!", + "paths": [ + { + "path": "/etc/passwd", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/group", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/usr/sbin/groupadd", + "chattr": "i", + "s_mode": 488, + "d_mode": 420 + }, + { + "path": "/usr/sbin/useradd", + "chattr": "i", + "s_mode": 488, + "d_mode": 420 + }, + { + "path": "/usr/bin/passwd", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + } + ] + }, + "bin": { + "open": true, + "name": "关键目录加固", + "ps": "保护系统关键文件不被修改替换!", + "paths": [ + { + "path": "/usr/bin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + }, + { + "path": "/usr/sbin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + }, + { + "path": "/etc/bashrc", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/usr/local/bin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + }, + { + "path": "/usr/local/sbin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + }, + { + "path": "/sbin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + }, + { + "path": "/bin", + "chattr": "i", + "s_mode": 365, + "d_mode": 365 + } + ] + }, + "cron": { + "open": true, + "name": "计划任务加固", + "ps": "保护计划任务不被篡改,开启后无法添加删除计划任务!", + "paths": [ + { + "path": "/usr/bin/crontab", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + }, + { + "path": "/etc/crontab", + "chattr": "i", + "s_mode": 420, + "d_mode": 420 + }, + { + "path": "/etc/cron.d", + "chattr": "i", + "s_mode": 509, + "d_mode": 509 + }, + { + "path": "/etc/cron.daily", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + }, + { + "path": "/etc/cron.hourly", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + }, + { + "path": "/etc/cron.monthly", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + }, + { + "path": "/etc/cron.weekly", + "chattr": "i", + "s_mode": 509, + "d_mode": 420 + }, + { + "path": "/etc/anacrontab", + "chattr": "i", + "s_mode": 384, + "d_mode": 384 + }, + { + "path": "/var/spool/cron", + "chattr": "i", + "s_mode": 448, + "d_mode": 448 + }, + { + "path": "/var/spool/cron/root", + "chattr": "i", + "s_mode": 384, + "d_mode": 384 + }, + { + "path": "/var/spool/anacron", + "chattr": "i", + "s_mode": 509, + "d_mode": 509 + } + ] + }, + "ssh": { + "open": true, + "name": "SSH服务加固", + "ps": "保护SSH不被暴力破解,记录用户登录日志", + "cycle": 120, + "limit": 3600, + "limit_count": 3 + }, + "process": { + "open": true, + "name": "异常进程监控", + "ps": "监控服务器进程列表,发现异常的进程后立即结束", + "process_white": [ + "pip", + "pip3", + "yum", + "apt-get", + "apt", + "redis-cli", + "memcached", + "sshd", + "vm", + "vim", + "htop", + "top", + "sh", + "bash", + "zip", + "gzip", + "rsync", + "tar", + "unzip", + "rar", + "unrar", + "php", + "composer", + "pkill", + "mongo", + "mongod", + "php-fpm", + "php-fpm5.6", + "php-fpm7.0", + "php-fpm7.1", + "php-fpm7.2", + "php-fpm7.3", + "php-fpm7.4", + "php-fpm8.1", + "php-fpm8.2", + "nginx", + "httpd", + "lsof", + "ps", + "vi", + "vim", + "redis-server", + "mysqld", + "mysqld_safe", + "mysql", + "pure-ftpd", + "sparse_dd", + "stunnel", + "squeezed", + "vncterm", + "awk", + "ruby", + "postgres", + "mpathalert", + "vncterm", + "multipathd", + "fe", + "elasticsyslog", + "syslogd", + "v6d", + "xapi", + "screen", + "runsvdir", + "svlogd", + "java", + "udevd", + "ntpd", + "irqbalance", + "qmgr", + "wpa_supplicant", + "mysqld_safe", + "sftp-server", + "lvmetad", + "gitlab-web", + "pure-ftpd", + "auditd", + "master", + "dbus-daemon", + "tapdisk", + "init", + "ksoftirqd", + "kworker", + "kmpathd", + "kmpath_handlerd", + "python", + "kdmflush", + "bioset", + "crond", + "kthreadd", + "migration", + "rcu_sched", + "kjournald", + "gcc", + "gcc++", + "nginx", + "mysqld", + "php-cgi", + "login", + "firewalld", + "iptables", + "systemd", + "network", + "dhclient", + "systemd-journald", + "chrony", + "chronyd", + "chronyc", + "NetworkManager", + "systemd-logind", + "systemd-udevd", + "polkitd", + "tuned", + "rsyslogd", + "AliYunDunUpdate", + "AliYunDun", + "du", + "sendmail", + "gunicorn", + "python2", + "python3", + "python34", + "python2.6", + "runsv", + "dd", + "mkfs", + "fdisk", + "systemd-resolve", + "rpm", + "cc1", + "cc1plus", + "as", + "acme.sh", + "cc", + "du", + "grep", + "awk", + "sed", + "cut", + "free", + "df", + "firewall-cmd", + "ufw", + "echo", + "ls", + "cp", + "mv", + "rm", + "diff", + "ln", + "cat", + "more", + "wtmp", + "date", + "e2fsck", + "gunzip", + "ifconfig", + "ip", + "route", + "ping", + "scp", + "telnet", + "cd", + "comm", + "touch", + "man", + "w", + "who", + "last", + "clock", + "uname", + "su", + "uptime", + "vmstat", + "mount", + "umount", + "mkdir", + "mkswap", + "swapon", + "e2fsck", + "tune2fs", + "groupadd", + "useradd", + "passwd", + "userdel", + "chown", + "chmod", + "chgrp", + "id", + "mail", + "gzip", + "bzip2", + "bunzip2", + "networking", + "ssh", + "find", + "locate", + "slocate", + "dir", + "vdir", + "pwd", + "rename", + "rmdir", + "updatedb", + "whereis", + "which", + "compress", + "ar", + "arj", + "gzexe", + "bzip2", + "cksum", + "cmp", + "col", + "colrm", + "csplit", + "diff3", + "emacs", + "join", + "head", + "sort", + "wc", + "uniq", + "tail", + "sum", + "ulimit", + "pkill", + "kill", + "killall", + "pidof", + "pstree", + "watch", + "pgrep", + "dumpe2fs", + "mke2fs", + "sync", + "lsyncd", + "tune2fs", + "basename", + "file", + "locate/slocate", + "ls/dir/vdir", + "bzcat", + "bzip2recover", + "bzless/bzmore", + "cpio", + "dump", + "lha", + "resotre", + "unarj", + "uncompress", + "zcat", + "zforce", + "zipinfo", + "znew", + "diffstat", + "ed", + "ex", + "expand", + "fmt", + "fold", + "grep/egrep/fgrep", + "ispell", + "jed", + "joe", + "less", + "look", + "od", + "paste", + "pico", + "spell", + "split", + "tac", + "tee", + "tr", + "unexpand", + "alias", + "bg", + "bind", + "declare", + "dirs", + "enable", + "eval", + "exec", + "exit", + "export", + "fc", + "fg", + "hash", + "history", + "jobs", + "logout", + "popd", + "pushd", + "set", + "shopt", + "umask", + "unalias", + "unset", + "accept", + "cancel", + "disable", + "lp", + "lpadmin", + "lpc", + "lpq", + "lpr", + "lprm", + "lpstat", + "pr", + "reject", + "bc", + "cal", + "clear", + "consoletype", + "ctrlaltdel", + "dircolors", + "eject", + "halt", + "hostid", + "hwclock", + "info", + "md5sum", + "letsencrypt", + "mandb", + "mesg", + "mtools", + "mtoolstest", + "poweroff", + "reboot", + "shutdown", + "sleep", + "stat", + "talk", + "wall", + "whatis", + "whoami", + "write", + "cmsgoagent.linu", + "yes", + "chfn", + "chsh", + "finger", + "gpasswd", + "groupdel", + "groupmod", + "groups", + "grpck", + "grpconv", + "grpunconv", + "logname", + "pwck", + "pwconv", + "dd", + "mariadbd", + "pwunconv", + "usermod", + "users", + "nice", + "nohup", + "renice", + "badblocks", + "blockdev", + "chattr", + "convertquota", + "e2image", + "e2label", + "edquota", + "fail2ban-server", + "findfs", + "fsck", + "grub", + "hdparm", + "lilo", + "lsattr", + "mkbootdisk", + "mkinitrd", + "mkisofs", + "mknod", + "mktemp", + "parted", + "quota", + "quotacheck", + "xargs", + "bcm-agent", + "bcm-si", + "quotaoff", + "quotaon", + "quotastat", + "repquota", + "swapoff", + "depmod", + "dmesg", + "insmod", + "iostat", + "ipcs", + "kernelversion", + "lsmod", + "modinfo", + "modprobe", + "mpstat", + "rmmod", + "sar", + "slabtop", + "sysctl", + "tload", + "startx", + "xauth", + "xhost", + "xinit", + "xlsatoms", + "xlsclients", + "xlsfonts", + "xset", + "chroot", + "nmap", + "ntfs-3g", + "sftp", + "slogin", + "sudo", + "awk/gawk", + "expr", + "gdb", + "ldd", + "make", + "nm", + "perl", + "test", + "arch", + "at", + "atq", + "atrm", + "batch", + "chkconfig", + "crontab", + "lastb", + "logrotate", + "logsave", + "logwatch", + "lsusb", + "patch", + "runlevel", + "service", + "telinit", + "dnsdomainname", + "domainname", + "hostname", + "ifcfg", + "ifdown", + "ifup", + "stmpd", + "nisdomainname", + "ypdomainname", + "arp", + "arping", + "arpwatch", + "dig", + "elinks", + "elm", + "ftp", + "host", + "ipcalc", + "lynx", + "ncftp", + "netstat", + "nslookup", + "pine", + "dhclient-script", + "rsh", + "tftp", + "tracepath", + "traceroute", + "wget", + "arptables", + "iptables-save", + "iptables-restore", + "tcpdump", + "ab", + "apachectl", + "exportfs", + "htdigest", + "htpasswd", + "mailq", + "mysqladmin", + "msqldump", + "mysqlimport", + "mysqlshow", + "nfsstat", + "showmount", + "smbclient", + "smbmount", + "smbpasswd", + "squid", + "pickup", + "local", + "localedef", + "bounce", + "smtp", + "smtpd", + "trivial-rewrite", + "xe-daemon", + "cleanup", + "nm-dispatcher", + "lsinitrd", + "barad_agent", + "stop.sh", + "YDService", + "agetty", + "systemctl", + "AliSecureCheckA", + "containerd", + "containerd-shim", + "certbot-auto", + "oneav", + "oneavd", + "oneav_service_m", + "s3fs", + "bosfs", + "cosfs", + "flock", + "raidcheck", + "run-parts", + "man-db.cron", + "YDLive", + "sgagent" + ], + "process_white_rule": [ + "vif", + "node", + "pm2", + "npm", + "yarn", + "qemu", + "scsi_eh", + "xcp", + "xen", + "docker", + "yunsuo", + "scsi", + "jbd2", + "ext4", + "xfs", + "aliyun", + "kswapd", + "PM2", + "yunsuo", + "mkfs", + "Ali", + "watchdog", + "kworker", + "ksoftirqd", + "migration", + "mysql", + "/www/server/", + "cmsgoagent", + "python", + "python3", + "ifdown", + "node" + ], + "process_exclude": [ + "php-fpm", + "mysqld", + "mongod", + "dockerd", + "docker-containerd", + "memcached", + "jsvc", + "jsvc.exec", + "nginx", + "node", + "pm2", + "npm", + "yarn", + "httpd", + "gunicorn", + "configure", + "make", + "curl", + "wget", + "anacron", + "mysqldump", + "node", + "php", + "mysql", + "netstat", + "redis", + "postfix" + ] + } +} \ No newline at end of file diff --git a/plugins/system_safe/ico.png b/plugins/system_safe/ico.png new file mode 100644 index 0000000000000000000000000000000000000000..e31c1b3bf452f4fb66a7cceadfd549e27ddd2846 GIT binary patch literal 812 zcmV+{1JnG8P)Px%=1D|BRA@u(neCAdK@^40Mt}^6V2J<`Ac7?VM1Tko0U}r;Km>>Y5s(4(sJ?IY z^!H5nyfdq||7_LnO!s;2?Y{T)?1?V;IJw~ZbqTO_2LJmET$l8H!zkaC^r^IdEdy^Q zooxt!cp$Q)1aL>vNB8CjNnei$Lgp=S4G0q#pW zcP~AX#8x`?@OMB~LoNdxT%!I>(#>Nl_tvv4{B~L3=VYV+9!h%So~l-XmErs<_(Ib2 z8o*UoHu(wdtCa<|Oiw@oLC-CBCJyg~8G!Iv%d8tc^G*^#NdPFnNFw@s9#kYM)4x$` zWP1jQ0Q}~$XW^5k>Sw^OyL$$hRK{=%{c*~v|544|kcxA8>ei_ zOChlHSR6*ADYZ?EcF9F1C%y;5-xb%w{*(gX0Mj()_5xo#jgW))*j6o8$0JO>S=WrX618Vh61DSgbtyh|Xg2P8{-3V=%tk(<*CtWFbo#M9Bkg|Pz$ z;XhXkkOj0Ez!pXXd#-ix9`NR&Qjr6KXUI;g*D`>nDim7jniXhD2mmtnD_27KeJ;XAy)}Rz%!!S*4CVkv*y<4($lB-{zzADC0w8OnYXBo` z^$38hjjjRM;yt!{1VGkC*8oP?>Jb208(jk!WvgeD`{bip8(jk!VXJ$^7j1M6fWPR$1oBZzEt3xL^bzC#|qMUGI`I0s$W{x^}eG$pTN6`*mw)gCLl;t~LkvGqQ%ntJyY qF8htD$8D}Dx_RzPfaXxG^x$9lkGU~>nW9So0000 +
+
+

服务

+

自启动

+

防护配置

+

封锁IP

+

日志审计

+

操作日志

+
+
+
+
+
+ + + + \ No newline at end of file diff --git a/plugins/system_safe/info.json b/plugins/system_safe/info.json new file mode 100755 index 000000000..e3e4df72e --- /dev/null +++ b/plugins/system_safe/info.json @@ -0,0 +1,20 @@ +{ + "sort": 1, + "ps": "提供灵活的系统加固功能,防止系统被植入木马,支持服务器日志审计功能", + "name": "system_safe", + "title": "系统加固", + "shell": "install.sh", + "versions":["1.0"], + "updates":["1.0"], + "tip": "soft", + "icon":"ico.png", + "checks": "server/system_safe", + "path": "server/system_safe", + "display": 1, + "author": "midoks", + "date": "2022-01-12", + "home": "", + "type": 0, + "pid": "4" + +} \ No newline at end of file diff --git a/plugins/system_safe/init.d/system_safe.service.tpl b/plugins/system_safe/init.d/system_safe.service.tpl new file mode 100644 index 000000000..707d60eb6 --- /dev/null +++ b/plugins/system_safe/init.d/system_safe.service.tpl @@ -0,0 +1,15 @@ +[Unit] +Description=system_safe server daemon +After=network.target + +[Service] +Type=forking +ExecStart={$SERVER_PATH}/init.d/system_safe start +ExecStop={$SERVER_PATH}/init.d/system_safe stop +ExecReload={$SERVER_PATH}/init.d/system_safe reload +ExecRestart={$SERVER_PATH}/init.d/system_safe restart +KillMode=process +Restart=on-failure + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/plugins/system_safe/init.d/system_safe.tpl b/plugins/system_safe/init.d/system_safe.tpl new file mode 100644 index 000000000..fd342de8b --- /dev/null +++ b/plugins/system_safe/init.d/system_safe.tpl @@ -0,0 +1,94 @@ +#!/bin/bash +# chkconfig: 2345 55 25 +# description:system_safe + +### BEGIN INIT INFO +# Provides: system_safe +# Required-Start: $all +# Required-Stop: $all +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: starts system_safe +# Description: starts the system_safe +### END INIT INFO + +PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin +mw_path={$SERVER_PATH} +rootPath=$(dirname "$mw_path") +PATH=$PATH:$mw_path/bin + +if [ -f $rootPath/mdserver-web/bin/activate ];then + source $rootPath/mdserver-web/bin/activate +fi + +sys_start() +{ + isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v '/bin/bash'|grep -v 'system_safe/index.py start' | grep -v 'system_safe/index.py reload' | grep -v 'system_safe/index.py restart' | grep -v systemctl | grep -v '/bin/sh' | awk '{print $2}'|xargs) + if [ "$isStart" == '' ];then + echo -e "Starting system_safe service... \c" + cd $rootPath/mdserver-web + nohup python3 plugins/system_safe/index.py bg_start &> $mw_path/service.log & + sleep 0.5 + isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|awk '{print $2}'|xargs) + if [ "$isStart" == '' ];then + echo -e "\033[31mfailed\033[0m" + echo '------------------------------------------------------' + cat $mw_path/service.log + echo '------------------------------------------------------' + echo -e "\033[31mError: system_safe service startup failed.\033[0m" + return; + fi + echo -e "\033[32mdone\033[0m" + else + echo "Starting system_safe service (pid $isStart) already running" + fi +} + +sys_stop() +{ + echo -e "Stopping system_safe service... \c"; + pids=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v '/bin/bash'|grep -v systemctl | grep -v 'system_safe/index.py bg_stop'|grep -v 'system_safe/index.py stop' | grep -v 'system_safe/index.py reload' | grep -v 'system_safe/index.py restart' |awk '{print $2}'|xargs) + arr=($pids) + for p in ${arr[@]} + do + kill -9 $p + done + cd $rootPath/mdserver-web + python3 plugins/system_safe/index.py bg_stop + echo -e "\033[32mdone\033[0m" +} + +sys_status() +{ + isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v systemctl|awk '{print $2}'|xargs) + if [ "$isStart" != '' ];then + echo -e "\033[32msystem_safe service (pid $isStart) already running\033[0m" + else + echo -e "\033[31msystem_safe service not running\033[0m" + fi +} + +case "$1" in + 'start') + sys_start + ;; + 'stop') + sys_stop + ;; + 'restart') + sys_stop + sleep 0.2 + sys_start + ;; + 'reload') + sys_stop + sleep 0.2 + sys_start + ;; + 'status') + sys_status + ;; + *) + echo "Usage: systemctl {start|stop|restart|reload} system_safe" + ;; +esac \ No newline at end of file diff --git a/plugins/system_safe/install.sh b/plugins/system_safe/install.sh new file mode 100755 index 000000000..df5e5f49a --- /dev/null +++ b/plugins/system_safe/install.sh @@ -0,0 +1,47 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH + +curPath=`pwd` +rootPath=$(dirname "$curPath") +rootPath=$(dirname "$rootPath") +serverPath=$(dirname "$rootPath") + +install_tmp=${rootPath}/tmp/mw_install.pl +SYSOS=`uname` +VERSION=$2 +APP_NAME=system_safe + +Install_App() +{ + echo '正在安装脚本文件...' > $install_tmp + mkdir -p $serverPath/system_safe + echo "$VERSION" > $serverPath/system_safe/version.pl + echo 'install complete' > $install_tmp + + #初始化 + cd ${serverPath}/mdserver-web && python3 plugins/system_safe/index.py start $VERSION + cd ${serverPath}/mdserver-web && python3 plugins/system_safe/index.py initd_install $VERSION +} + +Uninstall_App() +{ + + if [ -f /usr/lib/systemd/system/${APP_NAME}.service ] || [ -f /lib/systemd/system/${APP_NAME}.service ] ;then + systemctl stop ${APP_NAME} + systemctl disable ${APP_NAME} + rm -rf /usr/lib/systemd/system/${APP_NAME}.service + rm -rf /lib/systemd/system/${APP_NAME}.service + systemctl daemon-reload + fi + + rm -rf $serverPath/system_safe + echo "uninstall completed" > $install_tmp +} + +action=$1 +if [ "${1}" == 'install' ];then + Install_App +else + Uninstall_App +fi diff --git a/plugins/system_safe/js/app.js b/plugins/system_safe/js/app.js new file mode 100644 index 000000000..04aa5e5a9 --- /dev/null +++ b/plugins/system_safe/js/app.js @@ -0,0 +1,606 @@ +function ssPost(method,args,callback){ + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(toArrayObject(args)); + } else { + _args = JSON.stringify(args); + } + + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + + + + var req_data = {}; + req_data['name'] = 'system_safe'; + req_data['script'] = 'system_safe'; + req_data['func'] = method; + req_data['args'] = _args; + $.post('/plugins/run', req_data, function(data) { + layer.close(loadT); + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function ssAsyncPost(method,args){ + var _args = null; + if (typeof(args) == 'string'){ + _args = JSON.stringify(toArrayObject(args)); + } else { + _args = JSON.stringify(args); + } + return syncPost('/plugins/run', {name:'system_safe', func:method, args:_args}); +} + +function ssPostCallbak(method, args, callback){ + var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 }); + + var req_data = {}; + req_data['name'] = 'system_safe'; + req_data['func'] = method; + req_data['script'] = 'system_safe'; + args['version'] = '1.0'; + + + if (typeof(args) == 'string'){ + req_data['args'] = JSON.stringify(toArrayObject(args)); + } else { + req_data['args'] = JSON.stringify(args); + } + + $.post('/plugins/callback', req_data, function(data) { + layer.close(loadT); + if (!data.status){ + layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + + if(typeof(callback) == 'function'){ + callback(data); + } + },'json'); +} + +function getSafeConfigPathList(tag){ + ssPost('get_safe_data', {tag:tag}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + var slist = rdata.data.paths; + + var body = ''; + for (var i = 0; i < slist.length; i++) { + body += ""; + body += ""+slist[i]['path']+""; + + if (slist[i]['chattr'] == 'i'){ + body += "只读"; + } else if (slist[i]['chattr'] == 'a'){ + body += "追加"; + } else{ + body += "只读"; + } + + if (rdata.msg['open']){ + body += ""+slist[i]['d_mode']+""; + body += "已保护"; + } else { + body += ""+slist[i]['s_mode']+""; + body += "未保护"; + } + body += "删除"; + body += ""; + } + + $('#safe-file-table tbody').html(body); + $('.safe_path_delete').click(function(){ + var id = $(this).attr('row'); + ssPost('del_safe_path',{tag:tag,index:id}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + getSafeConfigPathList(tag); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + }); +} + +function setSafeConfigPath(tag, alist){ + + layer.open({ + type: 1, + area: ['700px','535px'], + title: '配置【'+alist['name']+'】', + content: "
\ +
\ + \ + \ + \ + \ + \ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
路径模式权限状态操作
\ +
\ +
\ +
    \ +
  • 【只读】无法修改、创建、删除文件和目录
  • \ +
  • 【追加】只能追加内容,不能删除或修改原有内容
  • \ +
  • 【权限】设置文件或目录在受保护状态下的权限(非继承),关闭保护后权限自动还原
  • \ +
  • 【如何填写权限】请填写Linux权限代号,如:644、755、600、555等,如果不填写,则使用文件原来的权限
  • \ +
\ +
", + success:function(){ + + $('.add_safe_config').click(function(){ + var path = $('input[name="s_path"]').val(); + var chattr = $('select[name="chattr"]').val(); + var d_mode = $('input[name="d_mode"]').val(); + ssPost('add_safe_path',{tag:tag,path:path,chattr:chattr,d_mode:d_mode}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + getSafeConfigPathList(tag); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + } + }); + getSafeConfigPathList(tag); + + +} + +function setSafeConfigSsh(tag, alist){ + + + function setSafeConfigSshData(){ + ssPost('get_ssh_data', {}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + var info = rdata.data; + + $('input[name="s_cycle"]').val(info['cycle']); + $('input[name="s_limit_count"]').val(info['limit_count']); + $('input[name="s_limit"]').val(info['limit']); + }); + } + layer.open({ + type: 1, + area: ['700px','210px'], + title: '配置【'+alist['name']+'】', + content: "
\ +
\ + 在(检测周期)\ + \ + 秒内,登录错误(检测阈值)\ + \ + 次,封锁(封锁时间)\ + \ + \ +
\ +
    \ +
  • 触发以上策略后,客户端IP将被封锁一段时间
  • \ +
  • 请在面板日志或操作日志中查看封锁记录
  • \ +
  • 请在面板日志或操作日志中查看SSH成功登录的记录
  • \ +
\ +
", + success:function(){ + setSafeConfigSshData(); + + $('.save_safe_ssh').click(function(){ + var cycle = $('input[name="s_cycle"]').val(); + var limit_count = $('input[name="s_limit_count"]').val(); + var limit = $('input[name="s_limit"]').val(); + ssPost('save_safe_ssh',{cycle:cycle,limit_count:limit_count,limit:limit}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + setSafeConfigSshData(); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + } + }); + +} + +function setSafeConfigProcessList(tag){ + ssPost('get_process_data', {}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + var slist = rdata.data.process_white; + + var body = ''; + for (var i = 0; i < slist.length; i++) { + body += "\ + "+slist[i]+"\ + 删除\ + "; + } + + $('#safe-file-table tbody').html(body); + $('.safe_path_delete').click(function(){ + var id = $(this).attr('row'); + ssPost('del_safe_proccess_name',{tag:tag,index:id}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + setSafeConfigProcessList(tag); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + }); +} + +function setSafeConfigProcess(tag, alist){ + layer.open({ + type: 1, + area: ['700px','535px'], + title: '配置【进程白名单】', + content: "
\ +
\ + \ + \ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ +
进程名称操作
\ +
\ +
\ +
    \ +
  • 【进程名称】请填写完整的进程名称,如: mysqld
  • \ +
  • 【说明】在白名单列表中的进程将不再检测范围,建议将常用软件的进程添加进白名单
  • \ +
\ +
", + success:function(){ + $('.add_process_white').click(function(){ + var process_name = $('input[name="s_name"]').val(); + ssPost('add_process_white',{process_name:process_name}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + setSafeConfigProcessList(tag); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + } + }); + + setSafeConfigProcessList(tag); + + +} + +function setSafeConfig(tag, alist){ + + if ($.inArray(tag, ['bin', 'service', 'home', 'user', 'bin', 'cron'])>-1){ + setSafeConfigPath(tag,alist); + } + + if ($.inArray(tag, ['ssh'])>-1){ + setSafeConfigSsh(tag,alist); + } + + if ($.inArray(tag, ['process'])>-1){ + setSafeConfigProcess(tag,alist); + } +} + +//设置安全状态 +function setSafeStatus(obj,tag){ + var o = $(obj).prev(); + var status = $(o).prop('checked'); + ssPost('set_safe_status', {tag:tag,status:!status}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + + if (!rdata.status){ + layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + $(o).prop('checked',status); + return; + } + layer.msg("配置成功!",{icon:1,time:2000,shade: [0.3, '#000']}); + }); +} + +function ssConfigList(){ + + ssPost('conf',{},function(rdata){ + var rdata = $.parseJSON(rdata.data); + var libs = rdata.data; + // console.log(libs); + var body = ''; + for (var i in libs) { + + if (i == 'open'){ + continue; + } + + var checked = ''; + if (libs[i].open){ + checked = 'checked'; + } + + body += '' + + '' + libs[i].name + '' + + '' + libs[i].ps + '' + + '\ +
\ + \ + \ +
\ + '+ + '配置' + + ''; + } + + var con = '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + body + '' + + '
名称描述状态操作
' + + '
' + + '
    \ +
  • 开启系统加固功能后,一些如软件安装等敏感操作将被禁止
  • \ +
  • 开启【SSH服务加固】之后,用户登录SSH的行为将受到监控,若连续多次登录失败,将采取封IP措施
  • \ +
  • 【异常进程监控】与【SSH服务加固】会占用一定服务器开销
  • \ +
  • 【注意】如果您需要安装软件或插件,请先将系统加固关闭!
  • \ +
'; + + $('.soft-man-con').html(con); + + $('#system_safe_list .service_switch').click(function(){ + var val = $(this).prev().attr('id'); + val = val.replace('sys_service_',''); + setSafeStatus(this,val); + }); + + $('.set_safe_config').click(function(){ + var name = $(this).attr('id'); + // console.log(name); + name = name.replace('conf_sys_service_',''); + setSafeConfig(name, libs[name]); + }); + + }); + +} + +function ssOpLogList(p){ + ssPost('op_log',{p:p},function(rdata){ + var rdata = $.parseJSON(rdata.data); + var plist = rdata.data.data; + + var body = ''; + for (var i = 0; i < plist.length; i++) { + body += "\ + " + plist[i].addtime + "\ + " + plist[i].log + "\ + "; + } + + $("#system_safe_log_list tbody").html(body); + $("#system_safe_log_page").html(rdata.data.page); + }); +} + +function ssOpLog(){ + var con = '
\ + \ + \ + \ +
时间详情
\ +
\ +
'; + $('.soft-man-con').html(con); + ssOpLogList(1); +} + + +function ssLogAuditList(){ + ssPost('get_sys_logfiles',{},function(rdata){ + var rdata = $.parseJSON(rdata.data); + var plist = rdata.data; + var option = ''; + // console.log(plist); + for (var i = 0; i < plist.length; i++) { + option += ''; + } + + $("#system_safe_log_audit").html(option); + var log_name = $('#system_safe_log_audit option:first').val(); + ssLogAuditFile(log_name); + + $('#system_safe_log_audit').change(function(){ + var log_name = $('#system_safe_log_audit option:selected').val(); + ssLogAuditFile(log_name); + }); + }); +} + +function ssLogAuditFileRenderString(data){ + + var tbody = ''; + $("#system_safe_log_audit_list").html(tbody); + var ob = document.getElementById('system_safe_log_audit_str'); + ob.scrollTop = ob.scrollHeight; + + $("#system_safe_log_audit_str").html(data); +} + +function ssLogAuditFileRenderObject(plist){ + + var pre_html = '\ + \ + \ +
时间角色事件
'; + $("#system_safe_log_audit_list").html(pre_html); + + if (plist.length>0){ + var tmp = plist[0]; + // console.log(tmp); + var thead = ''; + tbody += '' + for (var i in tmp) { + tbody+=''+ i + ''; + } + tbody += ''; + $("#system_safe_log_audit_list thead").html(tbody); + } + + + var tbody = ''; + for (var i = 0; i < plist.length; i++) { + tbody += ''; + for (var vv in plist[i]) { + tbody+= ''+ plist[i][vv] + '' + } + tbody += ''; + } + + $("#system_safe_log_audit_list tbody").html(tbody); +} + +function ssLogAuditFile(log_name){ + // ssPost('get_sys_log',{log_name:log_name},function(rdata){ + // try{ + // var rdata = $.parseJSON(rdata.data); + // if (typeof(rdata.data) == 'object'){ + + // if (!rdata.status){ + // layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + // return; + // } + // var plist = rdata.data; + // ssLogAuditFileRenderObject(plist); + // } + // }catch(e){ + // if (typeof(rdata.data) == 'string'){ + // ssLogAuditFileRenderString(rdata.data); + // } + // } + // }); + + ssPostCallbak('get_sys_log',{log_name:log_name},function(rdata){ + try{ + var rdata = $.parseJSON(rdata.data); + if (typeof(rdata.data) == 'object'){ + if (!rdata.status){ + layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']}); + return; + } + var plist = rdata.data; + ssLogAuditFileRenderObject(plist); + } + }catch(e){ + if (typeof(rdata.data) == 'string'){ + ssLogAuditFileRenderString(rdata.data); + } + } + }); +} + +function ssLogAudit(){ + var con = '\ +
'; + $('.soft-man-con').html(con); + ssLogAuditList(); +} + +function ssLockAddressList(){ + ssPost('get_ssh_limit_info',{},function(rdata){ + var rdata = $.parseJSON(rdata.data); + var libs = rdata.data; + var tbody = ''; + for (var i in libs) { + var end_time = libs[i].end; + var time_title = '手动解封'; + if (end_time != '0'){ + time_title = '自动解封时间:'+end_time; + } + tbody += '' + + '' + libs[i].address + '' + + ''+time_title+'' + + '立即解封' + + ''; + } + + $('#system_lock_address tbody').html(tbody); + $('#system_lock_address .remove_ssh_limit').click(function(){ + var address = $(this).attr('ip'); + ssPost('remove_ssh_limit', {ip:address}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + ssLockAddressList(); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + }); +} + +function ssLockAddress(){ + + var con = '
\ + \ + \ +
\ +
' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '
IP解封时间操作
' + + '
' + + '
    \ +
  • 【封锁IP】此处封锁的IP仅针对SSH服务,即被封锁的IP将无法连接SSH
  • \ +
  • 【添加】手动添加的IP封锁只能手动解封!
  • \ +
'; + + $('.soft-man-con').html(con); + + $('.add_lock_address').click(function(){ + var address = $('input[name="s_address"]').val(); + ssPost('add_ssh_limit', {ip:address}, function(rdata){ + var rdata = $.parseJSON(rdata.data); + showMsg(rdata.msg, function(){ + ssLockAddressList(); + },{icon:rdata.status?1:2,shade: [0.3, '#000']},2000); + }); + }); + ssLockAddressList(); +} \ No newline at end of file diff --git a/plugins/system_safe/system_safe.py b/plugins/system_safe/system_safe.py new file mode 100755 index 000000000..104ba3f52 --- /dev/null +++ b/plugins/system_safe/system_safe.py @@ -0,0 +1,1140 @@ +# coding:utf-8 + +import sys +import io +import os +import time +import json +import re +import psutil +from datetime import datetime + +sys.dont_write_bytecode = True +sys.path.append(os.getcwd() + "/class/core") +import mw + +app_debug = False +if mw.isAppleSystem(): + app_debug = True + + +class App: + + __deny = '/etc/hosts.deny' + __allow = '/etc/hosts.allow' + __state = {True: '开启', False: '关闭'} + __months = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', + 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Sept': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'} + __name = '系统加固' + __deny_list = None + + __config = None + __log_file = None + __last_ssh_time = 0 + __last_ssh_size = 0 + + def __init__(self): + if mw.isAppleSystem(): + self.__deny = self.getServerDir() + '/hosts.deny' + self.__allow = self.getServerDir() + '/hosts.allow' + + def getPluginName(self): + return 'system_safe' + + def getPluginDir(self): + return mw.getPluginDir() + '/' + self.getPluginName() + + def getServerDir(self): + return mw.getServerDir() + '/' + self.getPluginName() + + def getInitDFile(self): + if app_debug: + return '/tmp/' + self.getPluginName() + return '/etc/init.d/' + self.getPluginName() + + def getInitDTpl(self): + path = self.getPluginDir() + "/init.d/" + self.getPluginName() + ".tpl" + return path + + def getArgs(self): + args = sys.argv[2:] + tmp = {} + args_len = len(args) + + if args_len == 1: + t = args[0].strip('{').strip('}') + t = t.split(':') + tmp[t[0]] = t[1] + elif args_len > 1: + for i in range(len(args)): + t = args[i].split(':') + tmp[t[0]] = t[1] + + return tmp + + def checkArgs(self, data, ck=[]): + for i in range(len(ck)): + if not ck[i] in data: + return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!')) + return (True, mw.returnJson(True, 'ok')) + + def getServerConfPath(self): + return self.getServerDir() + "/config.json" + + def getConf(self): + cpath = self.getServerConfPath() + cpath_tpl = self.getPluginDir() + "/conf/config.json" + + if not os.path.exists(cpath): + t_data = mw.readFile(cpath_tpl) + t_data = json.loads(t_data) + t = json.dumps(t_data) + mw.writeFile(cpath, t) + return t_data + + t_data = mw.readFile(cpath) + t_data = json.loads(t_data) + return t_data + + def writeConf(self, data): + cpath = self.getServerConfPath() + tmp_conf = json.dumps(data) + mw.writeFile(cpath, tmp_conf) + + def initDreplace(self): + + file_tpl = self.getInitDTpl() + service_path = self.getServerDir() + + initD_path = service_path + '/init.d' + if not os.path.exists(initD_path): + os.mkdir(initD_path) + + # init.d + file_bin = initD_path + '/' + self.getPluginName() + if not os.path.exists(file_bin): + # initd replace + content = mw.readFile(file_tpl) + content = content.replace('{$SERVER_PATH}', service_path) + mw.writeFile(file_bin, content) + mw.execShell('chmod +x ' + file_bin) + + # systemd + # /usr/lib/systemd/system + systemDir = mw.systemdCfgDir() + systemService = systemDir + '/system_safe.service' + systemServiceTpl = self.getPluginDir() + '/init.d/system_safe.service.tpl' + if os.path.exists(systemDir) and not os.path.exists(systemService): + se_content = mw.readFile(systemServiceTpl) + se_content = se_content.replace('{$SERVER_PATH}', service_path) + mw.writeFile(systemService, se_content) + mw.execShell('systemctl daemon-reload') + + return file_bin + + def ssOp(self, method): + file = self.initDreplace() + + if not mw.isAppleSystem(): + data = mw.execShell('systemctl ' + method + + ' ' + self.getPluginName()) + if data[1] == '': + return 'ok' + return 'fail' + + data = mw.execShell(file + ' ' + method) + if data[1] == '': + return 'ok' + return 'fail' + + # def status(self): + # data = self.getConf() + # if not data['open']: + # return 'stop' + # return 'start' + + def status(self): + data = mw.execShell( + 'ps -ef|grep "system_safe/index.py bg_start" | grep -v grep | awk \'{print $2}\'') + if data[0] == '': + return 'stop' + return 'start' + + def start(self): + return self.ssOp('start') + + def writeLog(self, msg): + mw.writeDbLog(self.__name, msg) + + def getDenyList(self): + deny_file = self.getServerDir() + '/deny.json' + if not os.path.exists(deny_file): + mw.writeFile(deny_file, '{}') + self.__deny_list = json.loads(mw.readFile(deny_file)) + + # 存deny_list + def saveDeayList(self): + deny_file = self.getServerDir() + '/deny.json' + mw.writeFile(deny_file, json.dumps(self.__deny_list)) + + def get_ssh_limit(self): + data = self.getSshLimit() + return mw.returnJson(True, 'ok!', data) + + # 获取当前SSH禁止IP + def getSshLimit(self): + denyConf = mw.readFile(self.__deny) + if not denyConf: + mw.writeFile(self.__deny, '') + return [] + data = re.findall( + r"sshd:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):deny", denyConf) + return data + + def get_ssh_limit_info(self): + data = self.getSshLimitInfo() + return mw.returnJson(True, 'ok!', data) + + # 获取deny信息 + def getSshLimitInfo(self): + self.getDenyList() + conf_list = self.getSshLimit() + data = [] + for c_ip in conf_list: + tmp = {} + tmp['address'] = c_ip + tmp['end'] = 0 + if c_ip in self.__deny_list: + tmp['end'] = mw.getDataFromInt(self.__deny_list[c_ip]) + data.append(tmp) + return data + + def add_ssh_limit(self): + args = self.getArgs() + check = self.checkArgs(args, ['ip']) + if not check[0]: + return check[1] + ip = args['ip'] + return self.addSshLimit(ip) + + # 添加SSH目标IP + def addSshLimit(self, ip=None): + if ip == None: + ip = self.ip + + if ip in self.getSshLimit(): + return mw.returnJson(True, '指定IP黑名单已存在!') + denyConf = mw.readFile(self.__deny).strip() + while denyConf[-1:] == "\n" or denyConf[-1:] == " ": + denyConf = denyConf[:-1] + denyConf += "\nsshd:" + ip + ":deny\n" + mw.writeFile(self.__deny, denyConf) + if ip in self.getSshLimit(): + msg = u'添加IP[%s]到SSH-IP黑名单' % ip + self.writeLog(msg) + self.getDenyList() + if not ip in self.__deny_list: + self.__deny_list[ip] = 0 + self.saveDeayList() + return mw.returnJson(True, '添加成功!') + return mw.returnJson(False, '添加失败!') + + def remove_ssh_limit(self): + args = self.getArgs() + check = self.checkArgs(args, ['ip']) + if not check[0]: + return check[1] + ip = args['ip'] + return self.removeSshLimit(ip) + + # 删除IP黑名单 + def removeSshLimit(self, ip=None): + if ip == None: + ip = self.ip + + if not self.__deny_list: + self.getDenyList() + if ip in self.__deny_list: + del(self.__deny_list[ip]) + self.saveDeayList() + if not ip in self.getSshLimit(): + return mw.returnJson(True, '指定IP黑名单不存在!') + + denyConf = mw.readFile(self.__deny).strip() + while denyConf[-1:] == "\n" or denyConf[-1:] == " ": + denyConf = denyConf[:-1] + denyConf = re.sub("\n?sshd:" + ip + ":deny\n?", "\n", denyConf) + mw.writeFile(self.__deny, denyConf + "\n") + + msg = '从SSH-IP黑名单中解封[%s]' % ip + self.writeLog(msg) + return mw.returnJson(True, '解封成功!') + + def sshLoginTask(self): + if not self.__log_file: + log_file = '/var/log/secure' + if not os.path.exists(log_file): + log_file = '/var/log/auth.log' + if not os.path.exists(log_file): + return + self.__log_file = log_file + + if not self.__log_file: + return + + log_size = os.path.getsize(self.__log_file) + if self.__last_ssh_size == log_size: + return + self.__last_ssh_size = log_size + try: + config = self.__config + ssh_config = self.__config['ssh'] + line_num = ssh_config['limit_count'] * 20 + secure_logs = mw.getLastLine( + self.__log_file, line_num).split('\n') + + total_time = '/dev/shm/ssh_total_time.pl' + if not os.path.exists(total_time): + mw.writeFile(total_time, str(int(time.time()))) + + last_total_time = int(mw.readFile(total_time)) + now_total_time = int(time.time()) + + # print("last_total_time:", last_total_time) + # print("now_total_time:", now_total_time) + + self.getDenyList() + deny_list = list(self.__deny_list.keys()) + for i in range(len(deny_list)): + c_ip = deny_list[i] + if self.__deny_list[c_ip] > now_total_time or self.__deny_list[c_ip] == 0: + continue + self.ip = c_ip + self.removeSshLimit(None) + ip_total = {} + for log in secure_logs: + if log.find('Failed password for') != -1: + login_time = self.__to_date( + re.search(r'^\w+\s+\d+\s+\d+:\d+:\d+', log).group()) + if now_total_time - login_time >= ssh_config['cycle']: + continue + + client_ip = re.search(r'(\d+\.)+\d+', log).group() + if client_ip in self.__deny_list: + continue + if not client_ip in ip_total: + ip_total[client_ip] = 0 + ip_total[client_ip] += 1 + if ip_total[client_ip] <= ssh_config['limit_count']: + continue + self.__deny_list[ + client_ip] = now_total_time + ssh_config['limit'] + + self.saveDeayList() + self.ip = client_ip + + self.addSshLimit(None) + self.writeLog("[%s]在[%s]秒内连续[%s]次登录SSH失败,封锁[%s]秒" % ( + client_ip, ssh_config['cycle'], ssh_config['limit_count'], ssh_config['limit'])) + elif log.find('Accepted p') != -1: + login_time = self.__to_date( + re.search(r'^\w+\s+\d+\s+\d+:\d+:\d+', log).group()) + if login_time < last_total_time: + continue + client_ip = re.search(r'(\d+\.)+\d+', log).group() + login_user = re.findall(r"(\w+)\s+from", log)[0] + self.writeLog("用户[%s]成功登录服务器,用户IP:[%s],登录时间:[%s]" % ( + login_user, client_ip, time.strftime('%Y-%m-%d %X', time.localtime(login_time)))) + mw.writeFile(total_time, str(int(time.time()))) + except Exception as e: + print(mw.getTracebackInfo()) + return 'success' + + __limit = 30 + __vmsize = 1048576 * 100 + __wlist = None + __wslist = None + __elist = None + __last_pid_count = 0 + __last_return_time = 0 # 上次返回结果的时间 + __return_timeout = 360 + + def getSysProcess(self, get): + # 是否直接从属性中获取 + stime = time.time() + if stime - self.__last_return_time < self.__return_timeout: + if self.__sys_process: + return True + self.__last_return_time = stime + + # 本地是否存在系统进程白名单文件 + config_file = self.getServerDir() + '/sys_process.json' + is_force = False + if not os.path.exists(config_file): + mw.writeFile(config_file, json.dumps([])) + is_force = True + + data = json.loads(mw.readFile(config_file)) + self.__sys_process = data + return True + + # 取进程白名单列表 + def getProcessWhite(self, get): + data = self.getConf() + return data['process']['process_white'] + + # 取进程关键词 + def getProcessRule(self, get): + data = self.getConf() + return data['process']['process_white_rule'] + + # 取进程排除名单 + def getProcessExclude(self, get): + data = self.getConf() + return data['process']['process_exclude'] + + # 检查白名单 + def checkWhite(self, name): + if not self.__elist: + self.__elist = self.getProcessExclude(None) + if not self.__wlist: + self.__wlist = self.getProcessWhite(None) + if not self.__wslist: + self.__wslist = self.getProcessRule(None) + self.getSysProcess(None) + if name in ['mw', 'dnf', 'yum', + 'apt', 'apt-get', 'grep', + 'awk', 'python', 'node', 'php', 'mysqld', + 'httpd', 'openresty', 'wget', 'curl', 'openssl', + 'rspamd', 'supervisord', 'tlsmgr']: + return True + if name in self.__elist: + return True + if name in self.__sys_process: + return True + if name in self.__wlist: + return True + for key in self.__wslist: + if name.find(key) != -1: + return True + return False + + def checkMainProccess(self, pid): + if pid < 1100: + return + fname = '/proc/' + str(pid) + '/comm' + if not os.path.exists(fname): + return + name = mw.readFile(fname).strip() + is_num_name = re.match(r"^\d+$", name) + if not is_num_name: + if self.checkWhite(name): + return + try: + p = psutil.Process(pid) + percent = p.cpu_percent(interval=0.1) + vm = p.memory_info().vms + if percent > self.__limit or vm > self.__vmsize: + cmdline = ' '.join(p.cmdline()) + if cmdline.find('/www/server/cron') != -1: + return + if cmdline.find('/www/server') != -1: + return + if name.find('kworker') != -1 or name.find('mw_') == 0: + return + p.kill() + self.writeLog("已强制结束异常进程:[%s],PID:[%s],CPU:[%s],CMD:[%s]" % ( + name, pid, percent, cmdline)) + except: + print(mw.getTracebackInfo()) + return + + def checkMain(self): + pids = psutil.pids() + pid_count = len(pids) + if self.__last_pid_count == pid_count: + return + self.__last_pid_count = pid_count + + try: + for pid in pids: + self.checkMainProccess(pid) + except Exception as e: + print(mw.getTracebackInfo()) + + def processTask(self): + + if not self.__config: + self.__config = self.getConf() + if not self.__config: + return + + self.setOpen(1) + is_open = 0 + while True: + if self.__config['ssh']['open']: + is_open += 1 + self.sshLoginTask() + if self.__config['process']['open']: + is_open += 1 + self.checkMain() + + if is_open > 60: + self.__config = self.getConf() + is_open = 0 + time.sleep(1) + + def bg_start(self): + try: + self.processTask() + except Exception as e: + print(mw.getTracebackInfo()) + self.bg_stop() + self.writeLog('【{}】系统加固监控进程启动异常关闭'.format(mw.getDate())) + return 'ok' + + def bg_stop(self): + try: + self.setOpen(0) + except Exception as e: + print(mw.getTracebackInfo()) + print('【{}】系统加固监控进程停止异常关闭'.format(mw.getDate())) + return '' + + def stop(self): + return self.ssOp('stop') + + def restart(self): + return self.ssOp('restart') + + def reload(self): + return self.ssOp('reload') + + def initd_status(self): + if mw.isAppleSystem(): + return "Apple Computer does not support" + shell_cmd = 'systemctl status %s | grep loaded | grep "enabled;"' % ( + self.getPluginName()) + data = mw.execShell(shell_cmd) + if data[0] == '': + return 'fail' + return 'ok' + + def initd_install(self): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl enable ' + self.getPluginName()) + return 'ok' + + def initd_uninstall(self): + if mw.isAppleSystem(): + return "Apple Computer does not support" + + mw.execShell('systemctl disable ' + self.getPluginName()) + return 'ok' + + def __lock_path(self, info): + try: + if not os.path.exists(info['path']): + return False + if info['d_mode']: + os.chmod(info['path'], info['d_mode']) + if info['chattr']: + cmd = "chattr -R +%s %s" % (info['chattr'], info['path']) + mw.execShell(cmd) + return True + except Exception as e: + + return False + + def __unlock_path(self, info): + try: + if not os.path.exists(info['path']): + return False + if info['chattr']: + cmd = "chattr -R -%s %s" % (info['chattr'], info['path']) + mw.execShell(cmd) + + if info['s_mode']: + os.chmod(info['path'], info['s_mode']) + return True + except Exception as e: + mw.getTracebackInfo() + return False + + def __set_safe_state(self, paths, lock=False): + for path_info in paths: + if lock: + self.__lock_path(path_info) + else: + self.__unlock_path(path_info) + return True + + # 转换时间格式 + def __to_date(self, date_str): + tmp = re.split('\s+', date_str) + s_date = str(datetime.now().year) + '-' + \ + self.__months.get(tmp[0]) + '-' + tmp[1] + ' ' + tmp[2] + time_array = time.strptime(s_date, "%Y-%m-%d %H:%M:%S") + time_stamp = int(time.mktime(time_array)) + return time_stamp + + def conf(self): + data = self.getConf() + return mw.returnJson(True, 'ok', data) + + def setOpen(self, is_open=-1): + cpath = self.getServerConfPath() + data = self.getConf() + if is_open != -1: + if is_open == 0: + data['open'] = False + else: + data['open'] = True + + for s_name in data.keys(): + if type(data[s_name]) == bool: + continue + if not 'name' in data[s_name]: + continue + if not 'paths' in data[s_name]: + continue + s_name_status = False + if data['open']: + s_name_status = True + # print(data[s_name]['paths'], data[s_name]['open']) + self.__set_safe_state(data[s_name]['paths'], s_name_status) + msg = '已[%s]系统加固功能' % self.__state[data['open']] + self.writeLog(msg) + self.writeConf(data) + + def set_safe_status(self): + args = self.getArgs() + data = self.checkArgs(args, ['tag', 'status']) + if not data[0]: + return data[1] + + tag = args['tag'] + status = args['status'] + + # 转换格式 + if status == 'false': + status = False + if status == 'true': + status = True + + if not tag in ['bin', 'service', 'home', 'user', 'bin', 'cron', 'ssh', 'process']: + return mw.returnJson(False, '不存在此配置[{}]!'.format(tag)) + + data = self.getConf() + data[tag]['open'] = status + self.writeConf(data) + return mw.returnJson(True, '设置成功') + + # 取文件或目录锁定状态 + def __get_path_state(self, path): + if not os.path.exists(path): + return 'i' + if os.path.isfile(path): + shell_cmd = "lsattr %s|awk '{print $1}'" % path + else: + shell_cmd = "lsattr {}/ |grep '{}$'|awk '{{print $1}}'".format( + os.path.dirname(path), path) + result = mw.execShell(shell_cmd)[0] + if result.find('-i-') != -1: + return 'i' + if result.find('-a-') != -1: + return 'a' + return False + + # 遍历当前防护状态 + def __list_safe_state(self, paths): + result = [] + for i in range(len(paths)): + if not os.path.exists(paths[i]['path']): + continue + if os.path.islink(paths[i]['path']): + continue + mstate = self.__get_path_state(paths[i]['path']) + paths[i]['state'] = mstate == paths[i]['chattr'] + paths[i]['s_mode'] = oct(paths[i]['s_mode']) + paths[i]['d_mode'] = oct(paths[i]['d_mode']) + result.append(paths[i]) + return result + + def get_safe_data(self): + + args = self.getArgs() + check = self.checkArgs(args, ['tag']) + if not check[0]: + return check[1] + + tag = args['tag'] + if not tag in ['bin', 'service', 'home', 'user', 'bin', 'cron']: + return mw.returnJson(False, '不存在此配置[{}]!'.format(tag)) + + cpath = self.getServerConfPath() + data = self.getConf() + tmp = data[tag] + tmp['paths'] = self.__list_safe_state(tmp['paths']) + return mw.returnJson(True, {'open': data['open']}, tmp) + + def get_ssh_data(self): + data = self.getConf() + tmp = data['ssh'] + return mw.returnJson(True, {'open': data['open']}, tmp) + + def get_process_data(self): + data = self.getConf() + tmp = data['process'] + return mw.returnJson(True, {'open': data['open']}, tmp) + + # 添加防护对象 + def add_safe_path(self): + args = self.getArgs() + check = self.checkArgs(args, ['tag', 'path', 'chattr', 'd_mode']) + if not check[0]: + return check[1] + + path = args['path'] + tag = args['tag'] + chattr = args['chattr'] + d_mode = args['d_mode'] + if path[-1] == '/': + path = path[:-1] + if not os.path.exists(path): + return mw.returnJson(False, '指定文件或目录不存在!') + data = self.getConf() + + for m_path in data[tag]['paths']: + if path == m_path['path']: + return mw.returnJson(False, '指定文件或目录已经添加过了!') + + path_info = {} + path_info['path'] = path + path_info['chattr'] = chattr + path_info['s_mode'] = int(oct(os.stat(path).st_mode)[-3:], 8) + if d_mode != '': + path_info['d_mode'] = int(d_mode, 8) + else: + path_info['d_mode'] = path_info['s_mode'] + + data[tag]['paths'].insert(0, path_info) + if 'paths' in data[tag]: + mw.execShell('chattr -R -%s %s' % + (path_info['chattr'], path_info['path'])) + if data['open']: + self.__set_safe_state([path_info], data[tag]['open']) + msg = '添加防护对象[%s]到[%s]' % (path, data[tag]['name']) + self.writeLog(msg) + self.writeConf(data) + return mw.returnJson(True, msg) + + def save_safe_ssh(self): + + args = self.getArgs() + check = self.checkArgs(args, ['cycle', 'limit', 'limit_count']) + if not check[0]: + return check[1] + + cycle = int(args['cycle']) + limit = int(args['limit']) + limit_count = int(args['limit_count']) + + if cycle > limit: + return mw.returnJson(False, '封锁时间不能小于检测周期!') + if cycle < 30 or cycle > 1800: + return mw.returnJson(False, '检测周期的值必需在30 - 1800秒之间!') + if limit < 60: + return mw.returnJson(False, '封锁时间不能小于60秒') + if limit_count < 3 or limit_count > 100: + return mw.returnJson(False, '检测阈值必需在3 - 100秒之间!') + data = self.getConf() + data['ssh']['cycle'] = cycle + data['ssh']['limit'] = limit + data['ssh']['limit_count'] = limit_count + self.writeConf(data) + msg = '修改SSH策略: 在[%s]秒内,登录错误[%s]次,封锁[%s]秒' % ( + data['ssh']['cycle'], data['ssh']['limit_count'], data['ssh']['limit']) + self.writeLog(msg) + self.restart() + return mw.returnJson(True, '配置已保存!') + + # 添加进程白名单 + def add_process_white(self): + args = self.getArgs() + check = self.checkArgs(args, ['process_name']) + if not check[0]: + return check[1] + + data = self.getConf() + process_name = args['process_name'] + if process_name in data['process']['process_white']: + return mw.returnJson(False, '指定进程名已在白名单') + data['process']['process_white'].insert(0, process_name) + self.writeConf(data) + msg = '添加进程名[%s]到进程白名单' % process_name + self.writeLog(msg) + self.restart() + return mw.returnJson(True, msg) + + def del_safe_proccess_name(self): + args = self.getArgs() + check = self.checkArgs(args, ['tag', 'index']) + if not check[0]: + return check[1] + + tag = args['tag'] + index = int(args['index']) + + cpath = self.getServerConfPath() + data = self.getConf() + + del(data[tag]['process_white'][index]) + t = json.dumps(data) + mw.writeFile(cpath, t) + return mw.returnJson(True, '删除成功') + + def del_safe_path(self): + args = self.getArgs() + check = self.checkArgs(args, ['tag', 'index']) + if not check[0]: + return check[1] + + tag = args['tag'] + index = int(args['index']) + + cpath = self.getServerConfPath() + data = self.getConf() + + del(data[tag]['paths'][index]) + t = json.dumps(data) + mw.writeFile(cpath, t) + return mw.returnJson(True, '删除成功') + + def get_log_title(self, log_name): + log_name = log_name.replace('.1', '') + if log_name in ['auth.log', 'secure'] or log_name.find('auth.') == 0: + return '授权日志' + if log_name in ['dmesg'] or log_name.find('dmesg') == 0: + return '内核缓冲区日志' + if log_name in ['syslog'] or log_name.find('syslog') == 0: + return '系统警告/错误日志' + if log_name in ['btmp']: + return '失败的登录记录' + if log_name in ['utmp', 'wtmp']: + return '登录和重启记录' + if log_name in ['lastlog']: + return '用户最后登录' + if log_name in ['yum.log']: + return 'yum包管理器日志' + if log_name in ['anaconda.log']: + return 'Anaconda日志' + if log_name in ['dpkg.log']: + return 'dpkg日志' + if log_name in ['daemon.log']: + return '系统后台守护进程日志' + if log_name in ['boot.log']: + return '启动日志' + if log_name in ['kern.log']: + return '内核日志' + if log_name in ['maillog', 'mail.log']: + return '邮件日志' + if log_name.find('Xorg') == 0: + return 'Xorg日志' + if log_name in ['cron.log']: + return '定时任务日志' + if log_name in ['alternatives.log']: + return '更新替代信息' + if log_name in ['debug']: + return '调试信息' + if log_name.find('apt') == 0: + return 'apt-get相关日志' + if log_name.find('installer') == 0: + return '系统安装相关日志' + if log_name in ['messages']: + return '综合日志' + return '{}日志'.format(log_name.split('.')[0]) + + def get_sys_logfiles(self): + log_dir = '/var/log' + log_files = [] + for log_file in os.listdir(log_dir): + + log_suffix = log_file.split('.')[-1:] + if log_suffix[0] in ['gz', 'xz', 'bz2', 'asl']: + continue + + if log_file in ['.', '..', 'faillog', 'fontconfig.log', 'unattended-upgrades', 'tallylog']: + continue + + # print(log_suffix) + filename = os.path.join(log_dir, log_file) + if os.path.isfile(filename): + file_size = os.path.getsize(filename) + if not file_size: + continue + + tmp = { + 'name': log_file, + 'size': file_size, + 'log_file': filename, + 'title': self.get_log_title(log_file), + 'uptime': os.path.getmtime(filename) + } + + log_files.append(tmp) + else: + for next_name in os.listdir(filename): + if next_name[-3:] in ['.gz', '.xz']: + continue + next_file = os.path.join(filename, next_name) + if not os.path.isfile(next_file): + continue + file_size = os.path.getsize(next_file) + if not file_size: + continue + log_name = '{}/{}'.format(log_file, next_name) + tmp = { + 'name': log_name, + 'size': file_size, + 'log_file': next_file, + 'title': self.get_log_title(log_name), + 'uptime': os.path.getmtime(next_file) + } + log_files.append(tmp) + log_files = sorted(log_files, key=lambda x: x['name'], reverse=True) + return mw.returnJson(True, 'ok', log_files) + + def get_last(self, log_name): + # 获取日志 + cmd = '''LANG=en_US.UTF-8 last -n 200 -x -f {} |grep -v 127.0.0.1|grep -v " begins"'''.format( + '/var/log/' + log_name) + result = mw.execShell(cmd) + lastlog_list = [] + for _line in result[0].split("\n"): + if not _line: + continue + tmp = {} + sp_arr = _line.split() + tmp['用户'] = sp_arr[0] + if sp_arr[0] == 'runlevel': + tmp['来源'] = sp_arr[4] + tmp['端口'] = ' '.join(sp_arr[1:4]) + tmp['时间'] = self.__to_date3( + ' '.join(sp_arr[5:])) + ' ' + ' '.join(sp_arr[-2:]) + elif sp_arr[0] in ['reboot', 'shutdown']: + tmp['来源'] = sp_arr[3] + tmp['端口'] = ' '.join(sp_arr[1:3]) + if sp_arr[-3] == '-': + tmp['时间'] = self.__to_date3( + ' '.join(sp_arr[4:])) + ' ' + ' '.join(sp_arr[-3:]) + else: + tmp['时间'] = self.__to_date3( + ' '.join(sp_arr[4:])) + ' ' + ' '.join(sp_arr[-2:]) + elif sp_arr[1] in ['tty1', 'tty', 'tty2', 'tty3', 'hvc0', 'hvc1', 'hvc2'] or len(sp_arr) == 9: + tmp['来源'] = '' + tmp['端口'] = sp_arr[1] + tmp['时间'] = self.__to_date3( + ' '.join(sp_arr[2:])) + ' ' + ' '.join(sp_arr[-3:]) + else: + tmp['来源'] = sp_arr[2] + tmp['端口'] = sp_arr[1] + tmp['时间'] = self.__to_date3( + ' '.join(sp_arr[3:])) + ' ' + ' '.join(sp_arr[-3:]) + + # tmp['_line'] = _line + lastlog_list.append(tmp) + # lastlog_list = sorted(lastlog_list,key=lambda x:x['时间'],reverse=True) + return mw.returnJson(True, 'ok!', lastlog_list) + + def get_lastlog(self): + cmd = '''LANG=en_US.UTF-8 lastlog|grep -v Username''' + result = mw.execShell(cmd) + lastlog_list = [] + for _line in result[0].split("\n"): + if not _line: + continue + tmp = {} + sp_arr = _line.split() + tmp['用户'] = sp_arr[0] + # tmp['_line'] = _line + if _line.find('Never logged in') != -1: + tmp['最后登录时间'] = '0' + tmp['最后登录来源'] = '-' + tmp['最后登录端口'] = '-' + lastlog_list.append(tmp) + continue + tmp['最后登录来源'] = sp_arr[2] + tmp['最后登录端口'] = sp_arr[1] + tmp['最后登录时间'] = self.__to_date2(' '.join(sp_arr[3:])) + + lastlog_list.append(tmp) + lastlog_list = sorted(lastlog_list, key=lambda x: x[ + '最后登录时间'], reverse=True) + for i in range(len(lastlog_list)): + if lastlog_list[i]['最后登录时间'] == '0': + lastlog_list[i]['最后登录时间'] = '从未登录过' + return mw.returnJson(True, 'ok!', lastlog_list) + + def get_sys_log_with_name(self, log_name): + if log_name in ['wtmp', 'btmp', 'utmp'] or log_name.find('wtmp') == 0 or log_name.find('btmp') == 0 or log_name.find('utmp') == 0: + return self.get_last(log_name) + + if log_name.find('lastlog') == 0: + return self.get_lastlog() + + if log_name.find('sa/sa') == 0: + if log_name.find('sa/sar') == -1: + return mw.execShell("sar -f /var/log/{}".format(log_name))[0] + log_dir = '/var/log' + log_file = log_dir + '/' + log_name + if not os.path.exists(log_file): + return mw.returnJson(False, '日志文件不存在!') + result = mw.getLastLine(log_file, 100) + log_list = [] + is_string = True + for _line in result.split("\n"): + if not _line.strip(): + continue + if log_name.find('sa/sa') == -1: + if _line[:3] in self.__months: + _msg = _line[16:] + _tmp = _msg.split(": ") + _act = '' + if len(_tmp) > 1: + _act = _tmp[0] + _msg = _tmp[1] + else: + _msg = _tmp[0] + _line = { + "时间": self.__to_date4(_line[:16].strip()), + "角色": _act, + "事件": _msg + } + is_string = False + elif _line[:2] in ['19', '20', '21', '22', '23', '24']: + _msg = _line[19:] + _tmp = _msg.split(" ") + _act = _tmp[1] + _msg = ' '.join(_tmp[2:]) + _line = { + "时间": _line[:19].strip(), + "角色": _act, + "事件": _msg + } + is_string = False + elif log_name.find('alternatives') == 0: + _tmp = _line.split(": ") + _last = _tmp[0].split(" ") + _act = _last[0] + _msg = ' '.join(_tmp[1:]) + _line = { + "时间": ' '.join(_last[1:]).strip(), + "角色": _act, + "事件": _msg + } + is_string = False + else: + if not is_string: + if type(_line) != dict: + continue + + log_list.append(_line) + try: + # if len(log_list) > 1: + # if type(log_list[0]) != type(log_list[1]): + # del(log_list[0]) + # log_list = sorted(log_list,key=lambda x:x['时间'],reverse=True) + # return log_list + + _string = [] + _dict = [] + _list = [] + for _line in log_list: + if isinstance(_line, str): + _string.append(_line.strip()) + elif isinstance(_line, dict): + _dict.append(_line) + elif isinstance(_line, list): + _list.append(_line) + else: + continue + _str_len = len(_string) + _dict_len = len(_dict) + _list_len = len(_list) + if _str_len > _dict_len + _list_len: + return "\n".join(_string) + elif _dict_len > _str_len + _list_len: + return mw.returnJson(True, 'ok!', _dict) + else: + return mw.returnJson(True, 'ok!', _list) + + except: + data = '\n'.join(log_list) + return mw.returnJson(True, 'ok!', data) + + def get_sys_log(self): + args = self.getArgs() + check = self.checkArgs(args, ['log_name']) + if not check[0]: + return check[1] + + log_name = args['log_name'] + return self.get_sys_log_with_name(log_name) + + def __to_date2(self, date_str): + tmp = date_str.split() + s_date = str(tmp[-1]) + '-' + self.__months.get(tmp[1], + tmp[1]) + '-' + tmp[2] + ' ' + tmp[3] + return s_date + + def __to_date3(self, date_str): + tmp = date_str.split() + s_date = str(datetime.now().year) + '-' + \ + self.__months.get(tmp[1], tmp[1]) + '-' + tmp[2] + ' ' + tmp[3] + return s_date + + def __to_date4(self, date_str): + tmp = date_str.split() + s_date = str(datetime.now().year) + '-' + \ + self.__months.get(tmp[0], tmp[0]) + '-' + tmp[1] + ' ' + tmp[2] + return s_date + + def op_log(self): + args = self.getArgs() + check = self.checkArgs(args, ['p']) + if not check[0]: + return check[1] + + p = int(args['p']) + limit = 10 + start = (p - 1) * limit + + _list = mw.M('logs').field( + 'id,type,log,addtime').where('type=?', (self.__name,)).limit(str(start) + ',' + str(limit)).order('id desc').select() + data = {} + data['data'] = _list + count = mw.M('logs').where('type=?', (self.__name,)).count() + _page = {} + _page['count'] = count + _page['tojs'] = 'ssOpLogList' + _page['p'] = p + data['page'] = mw.getPage(_page) + return mw.returnJson(True, 'ok', data) + + +def get_sys_log(args): + classApp = App() + data = classApp.get_sys_log_with_name(args['log_name']) + return data + +if __name__ == "__main__": + func = sys.argv[1] + classApp = App() + try: + data = eval("classApp." + func + "()") + print(data) + except Exception as e: + print(mw.getTracebackInfo()) diff --git a/route/templates/default/config.html b/route/templates/default/config.html index 85c884f01..82a6001a1 100755 --- a/route/templates/default/config.html +++ b/route/templates/default/config.html @@ -171,7 +171,7 @@ -

VIP

+