Compare commits

..

100 Commits

Author SHA1 Message Date
xinwen
e86f84aaee fix: 消息订阅redis连接未关闭 2022-02-10 11:43:21 +08:00
xinwen
8b158d39b6 fix: Authbook 取认证信息bug 2022-02-10 11:41:44 +08:00
halo
5adbbeb868 feat: rdp协议新增username表达式,匹配更多特殊字符 2021-12-30 09:59:26 +08:00
Eric
c8b049349c perf: 修改 Jmservisor 的下载地址名称 2021-12-24 11:35:24 +08:00
Michael Bai
2ff92c5141 fix: 下载页面添加Jmservisor拉起脚本 2021-12-17 15:53:44 +08:00
Michael Bai
3260f0eba8 fix: 修改SAML2.0 Logo 2021-12-17 15:25:00 +08:00
Jiangjie.Bai
d27947919b Merge pull request #7404 from jumpserver/dev
v2.17.0 rc4
2021-12-15 22:03:19 +08:00
ibuler
b92530f0b9 perf: 优化通知,对支持 markdown 的发 markdown 2021-12-15 20:58:33 +08:00
ibuler
b113eeb1d6 perf: 修复基本设置中的 base_site 可能带 / 的问题 2021-12-15 20:55:06 +08:00
ibuler
eb3165f8e7 perf: 优化 saml 2021-12-15 20:54:34 +08:00
xinwen
93d77b2312 fix: 执行 ansible 任务日志记录错误 2021-12-15 18:02:14 +08:00
Michael Bai
ae1d419f70 fix: 修复用户组命令过滤规则获取不到的问题 2021-12-15 16:34:33 +08:00
feng626
36054cb64c Merge pull request #7397 from jumpserver/pr@dev@translate
feat: translate
2021-12-15 16:21:52 +08:00
feng626
022e93d7a2 feat: translate 2021-12-15 16:15:21 +08:00
Michael Bai
ac14790960 fix: 修改命令过滤规则动作允许值1->9 2021-12-15 14:57:44 +08:00
feng626
facc231e3f Merge pull request #7394 from jumpserver/pr@dev@ticket_filter_bug
perf: ticket filter
2021-12-15 14:40:28 +08:00
feng626
e4178849ba perf: ticket filter 2021-12-15 14:23:07 +08:00
Jiangjie.Bai
151d897746 Merge pull request #7391 from jumpserver/dev
v2.17.0 rc3
2021-12-14 21:58:27 +08:00
xinwen
27588f48d8 fix: authbook 创建的时候没有自动推送 2021-12-14 20:07:16 +08:00
Michael Bai
303102d40b fix: 删除一些启动时大量输出的debug日志 2021-12-14 20:06:49 +08:00
xinwen
ff9632d6da fix: LDAP 测试连接报错 2021-12-14 20:04:41 +08:00
Michael Bai
4cbf6dd5e6 fix: 修复获取系统用户认证信息API 2021-12-14 19:12:22 +08:00
xinwen
4f889cfe36 fix: 带 ad_domain 的系统用户不应该支持推送 2021-12-14 18:05:34 +08:00
ibuler
0c2e5f3f2a perf: 优化 saml2 i18n 2021-12-14 18:01:08 +08:00
ibuler
19ecc7fef6 fix: 修复 otp 返回时报错 2021-12-14 17:50:33 +08:00
ibuler
0020343ae0 perf: 优化运行的命名 2021-12-14 17:47:10 +08:00
ibuler
fa5c433c7c perf: 优化启动脚本,避免启动超时 2021-12-14 17:47:10 +08:00
jiangweidong
5139f9c4b9 feat: saml2认证支持https协议 2021-12-14 17:12:43 +08:00
Jiangjie.Bai
d6aad41d05 Merge pull request #7373 from jumpserver/dev
v2.17.0 rc2
2021-12-13 19:47:33 +08:00
xinwen
b3acc0d451 fix: 去掉 get_docker_mem_usage_if_limit 日志 2021-12-13 18:09:55 +08:00
ibuler
330917df4c fix: 修复 saml2 登陆的问题 2021-12-13 17:52:18 +08:00
ibuler
21d4ffa33b perf: 优化 cas 回调地址翻译 2021-12-13 16:33:00 +08:00
xinwen
1bc14c53d4 fix: 企业微信发送报错 2021-12-13 16:32:09 +08:00
ibuler
5024d0d739 perf: 优化 saml2 log 2021-12-13 16:30:38 +08:00
jiangweidong
c5013dcbd6 feat: saml2协议单点登录支持在页面上配置saml2协议的高级配置 (#7362) 2021-12-13 10:54:14 +08:00
halo
84924bc3f6 fix: 修复会话详情页命令列表排序失效bug 2021-12-13 10:52:37 +08:00
Michael Bai
2de769ecad chore: 修改依赖版本: jms-storage==0.0.40 2021-12-13 10:47:09 +08:00
feng626
ab68aed98f Merge pull request #7363 from jumpserver/pr@dev@ticket_bug
perf: 工单根据选择组织自动选择流
2021-12-13 10:25:48 +08:00
feng626
9b9e32d2f4 perf: 工单根据选择组织自动选择流 2021-12-11 12:50:30 +08:00
ibuler
b6249e9a63 fix: 修复登录时跳转问题 2021-12-10 17:49:29 +08:00
Jiangjie.Bai
5f7fa7e02f Merge pull request #7355 from jumpserver/dev
v2.17.0 rc1
2021-12-09 20:57:02 +08:00
Michael Bai
74fe9dddb7 fix: 修改i18n 2021-12-09 20:35:52 +08:00
ibuler
ade3f3ae6c fix: 修复需要设置 mfa 的 bug 2021-12-09 20:24:02 +08:00
Michael Bai
1c3b574c46 fix: 修复系统用户命令过滤规则必填的问题 2021-12-09 20:23:26 +08:00
Michael Bai
92aeae4a2a fix: 修改i18n
fix: 修改i18n
2021-12-09 20:23:07 +08:00
xinwen
ea6c28fa0d fix: 修改 cgroup memory log 2021-12-09 20:22:34 +08:00
fit2bot
f44acc923b perf: 修改 otp 的显示,避免误会 (#7345)
perf: 还是用 OTP 吧

Co-authored-by: ibuler <ibuler@qq.com>
2021-12-09 19:33:11 +08:00
ibuler
f27df2f523 fix: 修复 openstack 同步依赖 2021-12-09 19:28:22 +08:00
Michael Bai
bbf2aff96c feat: 命令过滤器支持多维度绑定
feat: 修改命令过滤规则校验

feat: 修改系统用户命令过滤器迁移文件
2021-12-09 19:06:28 +08:00
ibuler
3ea4a9fbe6 chore: 修改 html 中 license 文案 2021-12-09 17:33:56 +08:00
fit2bot
3962af7c4f feat: 支持saml2协议的单点登录,合并代码 (#7347)
* fix: 支持saml2协议的单点登录

* feat: 支持saml2协议的单点登录,合并代码

Co-authored-by: jiangweidong <weidong.jiang@fit2cloud.com>
2021-12-09 15:47:21 +08:00
ibuler
38c6d11af1 perf: 修改关闭 issue 的 comment 2021-12-09 15:31:27 +08:00
fit2bot
5f45acf68f workflow: 修改 workflow (#7341)
* workflow: 修改 workflow

* fix: 修复判断的错误

* perf: 添加移除的内容

Co-authored-by: ibuler <ibuler@qq.com>
2021-12-09 12:07:55 +08:00
fit2bot
c7f2afc3c1 fix: redis lock bug (#7338)
Co-authored-by: feng626 <1304903146@qq.com>
2021-12-08 17:55:32 +08:00
xinwen
16fae00e0e feat: xrdp 远程应用 2021-12-08 15:55:49 +08:00
Eric_Lee
0afeed0ff1 feat: 录像增加 cast 格式 (#7259)
* feat: 录像增加 cast 格式

* perf: 优化一下写法

* perf: 修改一点点

Co-authored-by: ibuler <ibuler@qq.com>
2021-12-08 15:35:22 +08:00
Michael Bai
d72aa34513 fix: 修改命令过滤规则生成正则表达式的逻辑,提高命令过滤准确性 2021-12-08 10:24:33 +08:00
feng626
d56de16563 fix: 依赖bug 2021-12-07 19:01:14 +08:00
ibuler
8536e6fca7 perf: 添加 issues workflow 2021-12-07 18:29:53 +08:00
feng626
adb9f01231 feat: 密码计划邮件提醒 2021-12-07 17:00:33 +08:00
ibuler
e0d4ad8570 workflow: 优化workflow 2021-12-07 10:40:13 +08:00
ibuler
3c8726f1b0 fix: 去掉多余的 collect static
perf: 使用bash 才能保证 subprocess 运行正常
2021-12-06 19:03:23 +08:00
ibuler
6b4bc1bdb5 chore: 升级 License 到 GPLv3
chore: 升级 License 到 GPLv3
2021-12-06 18:15:17 +08:00
ibuler
c92d36391f chore: change license 2021-12-06 17:45:54 +08:00
xinwen
24bbe7c31f fix: 计算docker limit 内存使用率时区分 cgroup v1 v2 2021-12-06 11:22:45 +08:00
fit2bot
77f2bd9262 perf: 优化workflow名称 (#7323)
* workflow: 添加定时检查issue的workflow

* perf: 优化workflow名称

Co-authored-by: ibuler <ibuler@qq.com>
2021-12-06 10:09:58 +08:00
ibuler
495a6fbc95 workflow: 添加定时检查issue的workflow 2021-12-03 19:25:56 +08:00
xinwen
36c6299a03 fix: redis 锁在redis集群环境报错 2021-12-03 19:23:44 +08:00
ibuler
8a31fbe35e chore: 添加判断 pull request 2021-12-03 15:22:13 +08:00
ibuler
dbe628a8db chore: 添加 issue 备注添加labels 2021-12-03 15:22:13 +08:00
ibuler
e45b893662 chore: 添加 workflow 检查issue 2021-12-02 17:50:31 +08:00
feng626
ac4b6e5b96 feat: 工单创建资产添加节点 2021-11-30 16:38:30 +08:00
ibuler
c85249be36 perf: 优化订阅处理,形成框架 2021-11-29 15:01:37 +08:00
ibuler
de006bc664 perf: 资产添加标签显示,更加易读
pref: 添加翻译
2021-11-29 14:57:50 +08:00
xinwen
a313e011ef perf: 内存使用率兼顾 docker cgroup limit 2021-11-29 14:53:04 +08:00
Michael Bai
3076b7a5e1 fix: 修复migrations序号重复问题 2021-11-29 11:24:12 +08:00
老广
c47a588e7c Merge pull request #7289 from jumpserver/pr@dev@merge_with_master
Merge branch 'dev' of github.com:jumpserver/jumpserver into dev
2021-11-26 11:20:39 +08:00
ibuler
7f61c49db2 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2021-11-25 20:00:34 +08:00
ibuler
c8a76c9afb fix: 修复 close connection 的问题 2021-11-25 18:29:01 +08:00
ibuler
3e85a9a079 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2021-11-25 18:05:18 +08:00
ibuler
62cbca7eb2 fix: 修复重置 mfa 的提示问题 2021-11-25 17:50:47 +08:00
ibuler
434793bc41 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2021-11-25 17:44:51 +08:00
xinwen
85a017b2c4 fix: 按资产ip搜索数据不全 2021-11-25 17:29:47 +08:00
ibuler
84bce19a92 perf: 去掉登录页面更好 2021-11-25 16:02:40 +08:00
ibuler
3874b8ed67 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev
repr@dev_v2.16_v2.15@2ee26971c9b152@fix_xxxx
merges an updated upstream into a topic branch.
2021-11-25 15:58:33 +08:00
ibuler
7f0ad7e27f fix: 修复 oidc cas 登录时跳转问题
perf: 优化一波,容易debug

perf: 还原回来的世界
2021-11-25 15:01:42 +08:00
ibuler
2ee26971c9 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2021-11-24 20:41:41 +08:00
ibuler
5ace5a752e fix: 修复 cas/oidc 登录 MFA 产生的bug
perf: 优化更严谨
2021-11-24 19:05:15 +08:00
Michael Bai
e838d974c3 fix: 修复根据节点/资产查询授权时报错的问题 2021-11-24 19:04:42 +08:00
ibuler
9dd93ea3b8 Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2021-11-24 16:15:57 +08:00
jiangweidong
88ea7ae149 feat: 云管同步中心支持OpenStack资产同步,所需python库依赖 2021-11-24 14:28:11 +08:00
ibuler
1132c6a4e4 fix: 修复 mfa radius 登录的bug 2021-11-24 12:51:12 +08:00
ibuler
0762f87ba5 Merge branch 'master' into dev 2021-11-24 11:25:51 +08:00
chenqiao
cb98b4f80a feat:新增对sqlserver数据库托管 2021-11-24 11:21:04 +08:00
feng626
599d58e9f2 fix: 修复重置mfa 500 bug 2021-11-23 16:11:54 +08:00
ibuler
5c6f1730d5 perf: 系统用户密码不再trim空格 2021-11-23 10:41:58 +08:00
feng626
67d084fc43 perf: ip list 优化 2021-11-19 16:36:58 +08:00
feng626
24d0d52a0a perf: 优化ip黑白名单 2021-11-19 11:48:45 +08:00
xinwen
d94c515cfc fix: 验证码逻辑错误 2021-11-19 10:46:59 +08:00
Michael Bai
cae956f9a5 fix(i18n): 修改翻译文件 2021-11-18 19:07:14 +08:00
117 changed files with 2768 additions and 1047 deletions

View File

@@ -0,0 +1,18 @@
name: Issue Close Require
on:
schedule:
- cron: "0 0 * * *"
jobs:
issue-close-require:
runs-on: ubuntu-latest
steps:
- name: need reproduce
uses: actions-cool/issues-helper@v2
with:
actions: 'close-issues'
labels: '状态:待反馈'
inactive-day: 30
body: |
您超过 30 天未反馈信息,我们将关闭该 issue如有需求您可以重新打开或者提交新的 issue。

16
.github/workflows/issue-close.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
name: Issue Close Check
on:
issues:
types: [closed]
jobs:
issue-close-remove-labels:
runs-on: ubuntu-latest
steps:
- name: Remove labels
uses: actions-cool/issues-helper@v2
if: ${{ !github.event.issue.pull_request }}
with:
actions: 'remove-labels'
labels: '状态:待处理,状态:待反馈'

38
.github/workflows/issue-comment.yml vendored Normal file
View File

@@ -0,0 +1,38 @@
on:
issue_comment:
types: [created]
name: Add issues workflow labels
jobs:
add-label-if-is-author:
runs-on: ubuntu-latest
if: (github.event.issue.user.id == github.event.comment.user.id) && !github.event.issue.pull_request && (github.event.issue.state == 'open')
steps:
- name: Add require handle label
uses: actions-cool/issues-helper@v2
with:
actions: 'add-labels'
labels: '状态:待处理'
- name: Remove require reply label
uses: actions-cool/issues-helper@v2
with:
actions: 'remove-labels'
labels: '状态:待反馈'
add-label-if-not-author:
runs-on: ubuntu-latest
if: (github.event.issue.user.id != github.event.comment.user.id) && !github.event.issue.pull_request && (github.event.issue.state == 'open')
steps:
- name: Add require replay label
uses: actions-cool/issues-helper@v2
with:
actions: 'add-labels'
labels: '状态:待反馈'
- name: Remove require handle label
uses: actions-cool/issues-helper@v2
with:
actions: 'remove-labels'
labels: '状态:待处理'

16
.github/workflows/issue-open.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
name: Issue Open Check
on:
issues:
types: [opened]
jobs:
issue-open-add-labels:
runs-on: ubuntu-latest
steps:
- name: Add labels
uses: actions-cool/issues-helper@v2
if: ${{ !github.event.issue.pull_request }}
with:
actions: 'add-labels'
labels: '状态:待处理'

View File

@@ -0,0 +1,17 @@
on:
schedule:
- cron: "0 1 * * *"
name: Check recent handle issues
jobs:
check-recent-issues-not-handle:
runs-on: ubuntu-latest
steps:
- name: Check recent issues and send msg
uses: jumpserver/action-issues-alert@master
with:
hook: ${{ secrets.WECHAT_GROUP_WEB_HOOK }}
type: recent
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,17 @@
on:
schedule:
- cron: "0 9 * * 1-5"
name: Check untimely handle issues
jobs:
check-untimely-handle-issues:
runs-on: ubuntu-latest
steps:
- name: Check untimely issues and send msg
uses: jumpserver/action-issues-alert@master
with:
hook: ${{ secrets.WECHAT_GROUP_WEB_HOOK }}
type: untimely
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -37,7 +37,9 @@ RUN pip install --upgrade pip==20.2.4 setuptools==49.6.0 wheel==0.34.2 -i ${PIP_
COPY --from=stage-build /opt/jumpserver/release/jumpserver /opt/jumpserver
RUN mkdir -p /root/.ssh/ \
&& echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile /dev/null" > /root/.ssh/config
&& echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile /dev/null" > /root/.ssh/config \
&& mv /bin/sh /bin/sh.bak \
&& ln -s /bin/bash /bin/sh
RUN mkdir -p /opt/jumpserver/oracle/ \
&& wget https://download.jumpserver.org/public/instantclient-basiclite-linux.x64-21.1.0.0.0.tar > /dev/null \

837
LICENSE
View File

@@ -1,281 +1,622 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Version 3, 29 June 2007
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
TERMS AND CONDITIONS
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
0. Definitions.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
"This License" refers to version 3 of the GNU General Public License.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
A "covered work" means either the unmodified Program or a work based
on the Program.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
1. Source Code.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
The Corresponding Source for a work in source code form is that
same work.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
2. Basic Permissions.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
13. Use with the GNU Affero General Public License.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
14. Revised Versions of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
NO WARRANTY
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
15. Disclaimer of Warranty.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
@@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
@@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -2,7 +2,7 @@
<h3 align="center">多云环境下更好用的堡垒机</h3>
<p align="center">
<a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0"><img src="https://shields.io/github/license/jumpserver/jumpserver" alt="License: GPL v2"></a>
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/github/license/jumpserver/jumpserver" alt="License: GPLv3"></a>
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
@@ -13,7 +13,7 @@
JumpServer 是全球首款开源的堡垒机,使用 GNU GPL v2.0 开源协议,是符合 4A 规范的运维安全审计系统。
JumpServer 是全球首款开源的堡垒机,使用 GPLv3 开源协议,是符合 4A 规范的运维安全审计系统。
JumpServer 使用 Python 开发,遵循 Web 2.0 规范,配备了业界领先的 Web Terminal 方案,交互界面美观、用户体验好。
@@ -126,9 +126,9 @@ JumpServer是一款安全产品请参考 [基本安全建议](https://docs.ju
Copyright (c) 2014-2021 飞致云 FIT2CLOUD, All rights reserved.
Licensed under The GNU General Public License version 2 (GPLv2) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Licensed under The GNU General Public License version 3 (GPLv3) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-2.0.html
https://www.gnu.org/licenses/gpl-3.0.html
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.

View File

@@ -2,13 +2,13 @@
<h3 align="center">Open Source Bastion Host</h3>
<p align="center">
<a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0"><img src="https://shields.io/github/license/jumpserver/jumpserver" alt="License: GPL v2"></a>
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/github/license/jumpserver/jumpserver" alt="License: GPLv3"></a>
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
</p>
JumpServer is the world's first open-source Bastion Host and is licensed under the GNU GPL v2.0. It is a 4A-compliant professional operation and maintenance security audit system.
JumpServer is the world's first open-source Bastion Host and is licensed under the GPLv3. It is a 4A-compliant professional operation and maintenance security audit system.
JumpServer uses Python / Django for development, follows Web 2.0 specifications, and is equipped with an industry-leading Web Terminal solution that provides a beautiful user interface and great user experience
@@ -85,10 +85,11 @@ If you find a security problem, please contact us directly
- 400-052-0755
### License & Copyright
Copyright (c) 2014-2021 Beijing Duizhan Tech, Inc., All rights reserved.
Copyright (c) 2014-2021 FIT2CLOUD Tech, Inc., All rights reserved.
Licensed under The GNU General Public License version 2 (GPLv2) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Licensed under The GNU General Public License version 3 (GPLv3) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-2.0.html
https://www.gnu.org/licenses/gpl-3.0.htmll
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.

View File

@@ -20,6 +20,7 @@ class AppType(TextChoices):
oracle = 'oracle', 'Oracle'
pgsql = 'postgresql', 'PostgreSQL'
mariadb = 'mariadb', 'MariaDB'
sqlserver = 'sqlserver', 'SQLServer'
# remote-app category
chrome = 'chrome', 'Chrome'
@@ -33,7 +34,7 @@ class AppType(TextChoices):
@classmethod
def category_types_mapper(cls):
return {
AppCategory.db: [cls.mysql, cls.oracle, cls.pgsql, cls.mariadb],
AppCategory.db: [cls.mysql, cls.oracle, cls.pgsql, cls.mariadb, cls.sqlserver],
AppCategory.remote_app: [cls.chrome, cls.mysql_workbench, cls.vmware_client, cls.custom],
AppCategory.cloud: [cls.k8s]
}

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.1.12 on 2021-11-05 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('applications', '0013_auto_20211026_1711'),
]
operations = [
migrations.AlterField(
model_name='application',
name='type',
field=models.CharField(choices=[('mysql', 'MySQL'), ('oracle', 'Oracle'), ('postgresql', 'PostgreSQL'), ('mariadb', 'MariaDB'), ('sqlserver', 'SQLServer'), ('chrome', 'Chrome'), ('mysql_workbench', 'MySQL Workbench'), ('vmware_client', 'vSphere Client'), ('custom', 'Custom'), ('k8s', 'Kubernetes')], max_length=16, verbose_name='Type'),
),
]

View File

@@ -3,6 +3,7 @@ from .mysql import *
from .mariadb import *
from .oracle import *
from .pgsql import *
from .sqlserver import *
from .chrome import *
from .mysql_workbench import *

View File

@@ -0,0 +1,12 @@
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from ..application_category import DBSerializer
__all__ = ['SQLServerSerializer']
class SQLServerSerializer(DBSerializer):
port = serializers.IntegerField(default=1433, label=_('Port'), allow_null=True)

View File

@@ -28,6 +28,7 @@ type_serializer_classes_mapping = {
const.AppType.mariadb.value: application_type.MariaDBSerializer,
const.AppType.oracle.value: application_type.OracleSerializer,
const.AppType.pgsql.value: application_type.PostgreSerializer,
const.AppType.sqlserver.value: application_type.SQLServerSerializer,
# remote-app
const.AppType.chrome.value: application_type.ChromeSerializer,
const.AppType.mysql_workbench.value: application_type.MySQLWorkbenchSerializer,

View File

@@ -147,7 +147,7 @@ class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
asset = data['asset']
system_users = data.get('system_users')
if not system_users:
system_users = asset.get_all_systemusers()
system_users = asset.get_all_system_users()
if action == 'push_system_user':
task = push_system_users_a_asset.delay(system_users, asset=asset)
elif action == 'test_system_user':

View File

@@ -29,7 +29,7 @@ class CommandFilterViewSet(OrgBulkModelViewSet):
class CommandFilterRuleViewSet(OrgBulkModelViewSet):
model = CommandFilterRule
filterset_fields = ("content",)
filterset_fields = ('content',)
search_fields = filterset_fields
permission_classes = (IsOrgAdmin,)
serializer_class = serializers.CommandFilterRuleSerializer

View File

@@ -13,6 +13,7 @@ from django.db.models.signals import m2m_changed
from common.const.http import POST
from common.exceptions import SomeoneIsDoingThis
from common.const.signals import PRE_REMOVE, POST_REMOVE
from common.mixins.api import SuggestionMixin
from assets.models import Asset
from common.utils import get_logger, get_object_or_none
from common.tree import TreeNodeSerializer
@@ -41,7 +42,7 @@ __all__ = [
]
class NodeViewSet(OrgModelViewSet):
class NodeViewSet(SuggestionMixin, OrgModelViewSet):
model = Node
filterset_fields = ('value', 'key', 'id')
search_fields = ('value', )

View File

@@ -1,15 +1,18 @@
# ~*~ coding: utf-8 ~*~
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from django.db.models import Q
from common.utils import get_logger
from common.utils import get_logger, get_object_or_none
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsValidUser
from orgs.mixins.api import OrgBulkModelViewSet
from orgs.mixins import generics
from common.mixins.api import SuggestionMixin
from orgs.utils import tmp_to_root_org
from rest_framework.decorators import action
from ..models import SystemUser, Asset
from users.models import User, UserGroup
from applications.models import Application
from ..models import SystemUser, Asset, CommandFilter, CommandFilterRule
from .. import serializers
from ..serializers import SystemUserWithAuthInfoSerializer, SystemUserTempAuthSerializer
from ..tasks import (
@@ -135,7 +138,8 @@ class SystemUserAppAuthInfoApi(generics.RetrieveAPIView):
instance = super().get_object()
app_id = self.kwargs.get('app_id')
user_id = self.request.query_params.get("user_id")
instance.load_app_more_auth(app_id, user_id)
username = self.request.query_params.get("username")
instance.load_app_more_auth(app_id, username, user_id)
return instance
@@ -192,9 +196,42 @@ class SystemUserCommandFilterRuleListApi(generics.ListAPIView):
return CommandFilterRuleSerializer
def get_queryset(self):
pk = self.kwargs.get('pk', None)
system_user = get_object_or_404(SystemUser, pk=pk)
return system_user.cmd_filter_rules
user_groups = []
user_id = self.request.query_params.get('user_id')
user = get_object_or_none(User, pk=user_id)
if user:
user_groups.extend(list(user.groups.all()))
user_group_id = self.request.query_params.get('user_group_id')
user_group = get_object_or_none(UserGroup, pk=user_group_id)
if user_group:
user_groups.append(user_group)
system_user_id = self.kwargs.get('pk', None)
system_user = get_object_or_none(SystemUser, pk=system_user_id)
if not system_user:
system_user_id = self.request.query_params.get('system_user_id')
system_user = get_object_or_none(SystemUser, pk=system_user_id)
asset_id = self.request.query_params.get('asset_id')
asset = get_object_or_none(Asset, pk=asset_id)
application_id = self.request.query_params.get('application_id')
application = get_object_or_none(Application, pk=application_id)
q = Q()
if user:
q |= Q(users=user)
if user_groups:
q |= Q(user_groups__in=set(user_groups))
if system_user:
q |= Q(system_users=system_user)
if asset:
q |= Q(assets=asset)
if application:
q |= Q(applications=application)
if q:
cmd_filters = CommandFilter.objects.filter(q).filter(is_active=True)
rule_ids = cmd_filters.values_list('rules', flat=True)
rules = CommandFilterRule.objects.filter(id__in=rule_ids)
else:
rules = CommandFilterRule.objects.none()
return rules
class SystemUserAssetsListView(generics.ListAPIView):

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.1.12 on 2021-11-05 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0080_auto_20211104_1347'),
]
operations = [
migrations.AlterField(
model_name='systemuser',
name='protocol',
field=models.CharField(choices=[('ssh', 'SSH'), ('rdp', 'RDP'), ('telnet', 'Telnet'), ('vnc', 'VNC'), ('mysql', 'MySQL'), ('oracle', 'Oracle'), ('mariadb', 'MariaDB'), ('postgresql', 'PostgreSQL'), ('sqlserver', 'SQLServer'), ('k8s', 'K8S')], default='ssh', max_length=16, verbose_name='Protocol'),
),
]

View File

@@ -0,0 +1,74 @@
# Generated by Django 3.1.13 on 2021-12-09 06:40
from django.conf import settings
from django.db import migrations, models
def migrate_system_users_cmd_filters(apps, schema_editor):
system_user_model = apps.get_model("assets", "SystemUser")
cmd_filter_model = apps.get_model("assets", "CommandFilter")
su_through = system_user_model.cmd_filters.through
cf_through = cmd_filter_model.system_users.through
su_relation_objects = su_through.objects.all()
cf_relation_objects = [
cf_through(**{
'id': su_relation.id,
'systemuser_id': su_relation.systemuser_id,
'commandfilter_id': su_relation.commandfilter_id
})
for su_relation in su_relation_objects
]
cf_through.objects.bulk_create(cf_relation_objects)
class Migration(migrations.Migration):
dependencies = [
('applications', '0014_auto_20211105_1605'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('assets', '0081_auto_20211105_1605'),
]
operations = [
migrations.AddField(
model_name='commandfilter',
name='applications',
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='applications.Application', verbose_name='Application'),
),
migrations.AddField(
model_name='commandfilter',
name='assets',
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='assets.Asset', verbose_name='Asset'),
),
migrations.AddField(
model_name='commandfilter',
name='system_users',
field=models.ManyToManyField(blank=True, related_name='cmd_filters_pre', to='assets.SystemUser', verbose_name='System user'),
),
migrations.AddField(
model_name='commandfilter',
name='users',
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to=settings.AUTH_USER_MODEL, verbose_name='User'),
),
migrations.AddField(
model_name='commandfilter',
name='user_groups',
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='users.UserGroup', verbose_name='User group'),
),
migrations.AlterField(
model_name='systemuser',
name='cmd_filters',
field=models.ManyToManyField(blank=True, related_name='system_users_bak', to='assets.CommandFilter', verbose_name='Command filter'),
),
migrations.RunPython(migrate_system_users_cmd_filters),
migrations.RemoveField(
model_name='systemuser',
name='cmd_filters',
),
migrations.AlterField(
model_name='commandfilter',
name='system_users',
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='assets.SystemUser', verbose_name='System user'),
),
]

View File

@@ -0,0 +1,27 @@
# Generated by Django 3.1.13 on 2021-12-15 06:36
from django.db import migrations, models
OLD_ACTION_ALLOW = 1
NEW_ACTION_ALLOW = 9
def migrate_action(apps, schema_editor):
model = apps.get_model("assets", "CommandFilterRule")
model.objects.filter(action=OLD_ACTION_ALLOW).update(action=NEW_ACTION_ALLOW)
class Migration(migrations.Migration):
dependencies = [
('assets', '0082_auto_20211209_1440'),
]
operations = [
migrations.RunPython(migrate_action),
migrations.AlterField(
model_name='commandfilterrule',
name='action',
field=models.IntegerField(choices=[(0, 'Deny'), (9, 'Allow'), (2, 'Reconfirm')], default=0, verbose_name='Action'),
),
]

View File

@@ -299,6 +299,12 @@ class Asset(AbsConnectivity, AbsHardwareInfo, ProtocolsMixin, NodesRelationMixin
names.append(n.full_value)
return names
def labels_display(self):
names = []
for n in self.labels.all():
names.append(n.name + ':' + n.value)
return names
def as_node(self):
from .node import Node
fake_node = Node()
@@ -338,7 +344,7 @@ class Asset(AbsConnectivity, AbsHardwareInfo, ProtocolsMixin, NodesRelationMixin
tree_node = TreeNode(**data)
return tree_node
def get_all_systemusers(self):
def get_all_system_users(self):
from .user import SystemUser
system_user_ids = SystemUser.assets.through.objects.filter(asset=self)\
.values_list('systemuser_id', flat=True)

View File

@@ -7,9 +7,11 @@ from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils.translation import ugettext_lazy as _
from common.utils import lazyproperty
from common.utils import lazyproperty, get_logger
from orgs.mixins.models import OrgModelMixin
logger = get_logger(__file__)
__all__ = [
'CommandFilter', 'CommandFilterRule'
@@ -19,11 +21,32 @@ __all__ = [
class CommandFilter(OrgModelMixin):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
name = models.CharField(max_length=64, verbose_name=_("Name"))
users = models.ManyToManyField(
'users.User', related_name='cmd_filters', blank=True,
verbose_name=_("User")
)
user_groups = models.ManyToManyField(
'users.UserGroup', related_name='cmd_filters', blank=True,
verbose_name=_("User group"),
)
assets = models.ManyToManyField(
'assets.Asset', related_name='cmd_filters', blank=True,
verbose_name=_("Asset")
)
system_users = models.ManyToManyField(
'assets.SystemUser', related_name='cmd_filters', blank=True,
verbose_name=_("System user"))
applications = models.ManyToManyField(
'applications.Application', related_name='cmd_filters', blank=True,
verbose_name=_("Application")
)
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
comment = models.TextField(blank=True, default='', verbose_name=_("Comment"))
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
created_by = models.CharField(max_length=128, blank=True, default='', verbose_name=_('Created by'))
created_by = models.CharField(
max_length=128, blank=True, default='', verbose_name=_('Created by')
)
def __str__(self):
return self.name
@@ -45,7 +68,7 @@ class CommandFilterRule(OrgModelMixin):
class ActionChoices(models.IntegerChoices):
deny = 0, _('Deny')
allow = 1, _('Allow')
allow = 9, _('Allow')
confirm = 2, _('Reconfirm')
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
@@ -71,28 +94,52 @@ class CommandFilterRule(OrgModelMixin):
verbose_name = _("Command filter rule")
@lazyproperty
def _pattern(self):
def pattern(self):
if self.type == 'command':
regex = []
content = self.content.replace('\r\n', '\n')
for cmd in content.split('\n'):
cmd = re.escape(cmd)
cmd = cmd.replace('\\ ', '\s+')
if cmd[-1].isalpha():
regex.append(r'\b{0}\b'.format(cmd))
else:
regex.append(r'\b{0}'.format(cmd))
s = r'{}'.format('|'.join(regex))
s = self.construct_command_regex(content=self.content)
else:
s = r'{0}'.format(self.content)
return s
@classmethod
def construct_command_regex(cls, content):
regex = []
content = content.replace('\r\n', '\n')
for _cmd in content.split('\n'):
cmd = re.sub(r'\s+', ' ', _cmd)
cmd = re.escape(cmd)
cmd = cmd.replace('\\ ', '\s+')
# 有空格就不能 铆钉单词了
if ' ' in _cmd:
regex.append(cmd)
continue
# 如果是单个字符
if cmd[-1].isalpha():
regex.append(r'\b{0}\b'.format(cmd))
else:
regex.append(r'\b{0}'.format(cmd))
s = r'(?i){}'.format('|'.join(regex))
return s
@staticmethod
def compile_regex(regex):
try:
_pattern = re.compile(s)
except:
_pattern = ''
return _pattern
pattern = re.compile(regex)
except Exception as e:
error = _('The generated regular expression is incorrect: {}').format(str(e))
logger.error(error)
return False, error, None
return True, '', pattern
def match(self, data):
found = self._pattern.search(data)
succeed, error, pattern = self.compile_regex(regex=self.pattern)
if not succeed:
return self.ACTION_UNKNOWN, ''
found = pattern.search(data)
if not found:
return self.ACTION_UNKNOWN, ''

View File

@@ -32,6 +32,7 @@ class ProtocolMixin:
oracle = 'oracle', 'Oracle'
mariadb = 'mariadb', 'MariaDB'
postgresql = 'postgresql', 'PostgreSQL'
sqlserver = 'sqlserver', 'SQLServer'
k8s = 'k8s', 'K8S'
SUPPORT_PUSH_PROTOCOLS = [Protocol.ssh, Protocol.rdp]
@@ -43,7 +44,7 @@ class ProtocolMixin:
Protocol.rdp
]
APPLICATION_CATEGORY_DB_PROTOCOLS = [
Protocol.mysql, Protocol.oracle, Protocol.mariadb, Protocol.postgresql
Protocol.mysql, Protocol.oracle, Protocol.mariadb, Protocol.postgresql, Protocol.sqlserver
]
APPLICATION_CATEGORY_CLOUD_PROTOCOLS = [
Protocol.k8s
@@ -128,24 +129,55 @@ class AuthMixin:
if password:
self.password = password
def load_app_more_auth(self, app_id=None, user_id=None):
def load_app_more_auth(self, app_id=None, username=None, user_id=None):
self._clean_auth_info_if_manual_login_mode()
# 加载临时认证信息
if self.login_mode == self.LOGIN_MANUAL:
self._load_tmp_auth_if_has(app_id, user_id)
return
# 更新用户名
from users.models import User
user = get_object_or_none(User, pk=user_id) if user_id else None
if self.username_same_with_user:
if user and not username:
_username = user.username
else:
_username = username
self.username = _username
def load_asset_special_auth(self, asset, username=''):
"""
AuthBook 的数据状态
| asset | systemuser | username |
1 | * | * | x |
2 | * | x | * |
当前 AuthBook 只有以上两种状态systemuser 与 username 不会并存。
正常的资产与系统用户关联产生的是第1种状态改密则产生第2种状态。改密之后
只有 username 而没有 systemuser 。
Freq: 关联同一资产的多个系统用户指定同一用户名时,修改用户密码会影响所有系统用户
这里有一个不对称的行为,同名系统用户密码覆盖
当有相同 username 的多个系统用户时,有改密动作之后,所有的同名系统用户都使用最后
一次改动,但如果没有发生过改密,同名系统用户使用的密码还是各自的。
"""
authbooks = list(AuthBook.objects.filter(asset=asset, systemuser=self))
if len(authbooks) == 0:
if username == '':
username = self.username
authbook = AuthBook.objects.filter(
asset=asset, username=username, systemuser__isnull=True
).order_by('-date_created').first()
if not authbook:
authbook = AuthBook.objects.filter(
asset=asset, systemuser=self
).order_by('-date_created').first()
if not authbook:
return None
elif len(authbooks) == 1:
authbook = authbooks[0]
else:
authbooks.sort(key=lambda x: 1 if x.username == username else 0, reverse=True)
authbook = authbooks[0]
authbook.load_auth()
self.password = authbook.password
self.private_key = authbook.private_key
@@ -202,7 +234,6 @@ class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo'))
shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell'))
login_mode = models.CharField(choices=LOGIN_MODE_CHOICES, default=LOGIN_AUTO, max_length=10, verbose_name=_('Login mode'))
cmd_filters = models.ManyToManyField('CommandFilter', related_name='system_users', verbose_name=_("Command filter"), blank=True)
sftp_root = models.CharField(default='tmp', max_length=128, verbose_name=_("SFTP Root"))
token = models.TextField(default='', verbose_name=_('Token'))
home = models.CharField(max_length=4096, default='', verbose_name=_('Home'), blank=True)

View File

@@ -69,6 +69,9 @@ class AssetSerializer(BulkOrgResourceModelSerializer):
nodes_display = serializers.ListField(
child=serializers.CharField(), label=_('Nodes name'), required=False
)
labels_display = serializers.ListField(
child=serializers.CharField(), label=_('Labels name'), required=False, read_only=True
)
"""
资产的数据结构
@@ -91,7 +94,7 @@ class AssetSerializer(BulkOrgResourceModelSerializer):
'domain', 'domain_display', 'platform', 'admin_user', 'admin_user_display'
]
fields_m2m = [
'nodes', 'nodes_display', 'labels',
'nodes', 'nodes_display', 'labels', 'labels_display',
]
read_only_fields = [
'connectivity', 'date_verified', 'cpu_info', 'hardware_info',

View File

@@ -3,6 +3,7 @@
import re
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from ..models import CommandFilter, CommandFilterRule
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from orgs.utils import tmp_to_root_org
@@ -22,16 +23,14 @@ class CommandFilterSerializer(BulkOrgResourceModelSerializer):
'comment', 'created_by',
]
fields_fk = ['rules']
fields_m2m = ['system_users']
fields_m2m = ['users', 'user_groups', 'system_users', 'assets', 'applications']
fields = fields_small + fields_fk + fields_m2m
extra_kwargs = {
'rules': {'read_only': True},
'system_users': {'required': False},
'rules': {'read_only': True}
}
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
invalid_pattern = re.compile(r'[\.\*\+\[\\\?\{\}\^\$\|\(\)\#\<\>]')
type_display = serializers.ReadOnlyField(source='get_type_display')
action_display = serializers.ReadOnlyField(source='get_action_display')
@@ -39,13 +38,13 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
model = CommandFilterRule
fields_mini = ['id']
fields_small = fields_mini + [
'type', 'type_display', 'content', 'priority',
'type', 'type_display', 'content', 'pattern', 'priority',
'action', 'action_display', 'reviewers',
'date_created', 'date_updated',
'comment', 'created_by',
]
fields_fk = ['filter']
fields = '__all__'
fields = fields_small + fields_fk
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -61,15 +60,16 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
action._choices = choices
# def validate_content(self, content):
# tp = self.initial_data.get("type")
# if tp == CommandFilterRule.TYPE_REGEX:
# return content
# if self.invalid_pattern.search(content):
# invalid_char = self.invalid_pattern.pattern.replace('\\', '')
# msg = _("Content should not be contain: {}").format(invalid_char)
# raise serializers.ValidationError(msg)
# return content
def validate_content(self, content):
tp = self.initial_data.get("type")
if tp == CommandFilterRule.TYPE_COMMAND:
regex = CommandFilterRule.construct_command_regex(content)
else:
regex = content
succeed, error, pattern = CommandFilterRule.compile_regex(regex)
if not succeed:
raise serializers.ValidationError(error)
return content
class CommandConfirmSerializer(serializers.Serializer):

View File

@@ -4,7 +4,7 @@ from django.db.models import Count
from common.mixins.serializers import BulkSerializerMixin
from common.utils import ssh_pubkey_gen
from common.validators import alphanumeric_re, alphanumeric_cn_re
from common.validators import alphanumeric_re, alphanumeric_cn_re, alphanumeric_win_re
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from ..models import SystemUser, Asset
from .utils import validate_password_contains_left_double_curly_bracket
@@ -51,6 +51,7 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
'trim_whitespace': False,
"validators": [validate_password_contains_left_double_curly_bracket]
},
'cmd_filters': {"required": False},
'public_key': {"write_only": True},
'private_key': {"write_only": True},
'token': {"write_only": True},
@@ -106,9 +107,12 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
def validate_username(self, username):
protocol = self.get_initial_value("protocol")
if username:
regx = alphanumeric_re
if protocol == SystemUser.Protocol.telnet:
regx = alphanumeric_cn_re
elif protocol == SystemUser.Protocol.rdp:
regx = alphanumeric_win_re
else:
regx = alphanumeric_re
if not regx.match(username):
raise serializers.ValidationError(_('Special char not allowed'))
return username

View File

@@ -10,7 +10,6 @@ from django.dispatch import receiver
from django.utils.functional import LazyObject
from common.signals import django_ready
from common.db.utils import close_old_connections
from common.utils.connection import RedisPubSub
from common.utils import get_logger
from assets.models import Asset, Node
@@ -41,10 +40,6 @@ def expire_node_assets_mapping_for_memory(org_id):
root_org_id = Organization.ROOT_ID
# 当前进程清除(cache 数据)
logger.debug(
"Expire node assets id mapping from cache of org={}, pid={}"
"".format(org_id, os.getpid())
)
Node.expire_node_all_asset_ids_mapping_from_cache(org_id)
Node.expire_node_all_asset_ids_mapping_from_cache(root_org_id)
@@ -78,31 +73,13 @@ def on_node_asset_change(sender, instance, **kwargs):
def subscribe_node_assets_mapping_expire(sender, **kwargs):
logger.debug("Start subscribe for expire node assets id mapping from memory")
def handle_node_relation_change(org_id):
root_org_id = Organization.ROOT_ID
Node.expire_node_all_asset_ids_mapping_from_memory(org_id)
Node.expire_node_all_asset_ids_mapping_from_memory(root_org_id)
def keep_subscribe_node_assets_relation():
while True:
try:
subscribe = node_assets_mapping_for_memory_pub_sub.subscribe()
msgs = subscribe.listen()
# 开始之前关闭连接因为server端可能关闭了连接而 client 还在 CONN_MAX_AGE 中
for message in msgs:
if message["type"] != "message":
continue
close_old_connections()
org_id = message['data'].decode()
root_org_id = Organization.ROOT_ID
Node.expire_node_all_asset_ids_mapping_from_memory(org_id)
Node.expire_node_all_asset_ids_mapping_from_memory(root_org_id)
logger.debug(
"Expire node assets id mapping from memory of org={}, pid={}"
"".format(str(org_id), os.getpid())
)
close_old_connections()
except Exception as e:
logger.exception(f'subscribe_node_assets_mapping_expire: {e}')
Node.expire_all_orgs_node_all_asset_ids_mapping_from_memory()
finally:
# 请求结束,关闭连接
close_old_connections()
node_assets_mapping_for_memory_pub_sub.keep_handle_msg(handle_node_relation_change)
t = threading.Thread(target=keep_subscribe_node_assets_relation)
t.daemon = True

View File

@@ -13,16 +13,24 @@ __all__ = ['add_nodes_assets_to_system_users']
@tmp_to_root_org()
def add_nodes_assets_to_system_users(nodes_keys, system_users):
from ..models import Node
from assets.tasks import push_system_user_to_assets
nodes = Node.objects.filter(key__in=nodes_keys)
assets = Node.get_nodes_all_assets(*nodes)
for system_user in system_users:
""" 解决资产和节点进行关联时,已经关联过的节点不会触发 authbook post_save 信号,
无法更新节点下所有资产的管理用户的问题 """
need_push_asset_ids = []
for asset in assets:
defaults = {'asset': asset, 'systemuser': system_user, 'org_id': asset.org_id}
instance, created = AuthBook.objects.update_or_create(
defaults=defaults, asset=asset, systemuser=system_user
)
if created:
need_push_asset_ids.append(asset.id)
# # 不再自动更新资产管理用户,只允许用户手动指定。
# 只要关联都需要更新资产的管理用户
# instance.update_asset_admin_user_if_need()
if need_push_asset_ids:
push_system_user_to_assets.delay(system_user.id, need_push_asset_ids)

View File

@@ -4,10 +4,10 @@ from itertools import groupby
from celery import shared_task
from common.db.utils import get_object_if_need, get_objects
from django.utils.translation import ugettext as _
from django.db.models import Empty, Q
from django.db.models import Empty
from common.utils import encrypt_password, get_logger
from assets.models import SystemUser, Asset, AuthBook
from assets.models import SystemUser, Asset
from orgs.utils import org_aware_func, tmp_to_root_org
from . import const
from .utils import clean_ansible_task_hosts, group_asset_by_platform
@@ -138,7 +138,7 @@ def get_push_unixlike_system_user_tasks(system_user, username=None):
return tasks
def get_push_windows_system_user_tasks(system_user, username=None):
def get_push_windows_system_user_tasks(system_user: SystemUser, username=None):
if username is None:
username = system_user.username
password = system_user.password
@@ -151,6 +151,11 @@ def get_push_windows_system_user_tasks(system_user, username=None):
if not password:
logger.error("Error: no password found")
return tasks
if system_user.ad_domain:
logger.error('System user with AD domain do not support push.')
return tasks
task = {
'name': 'Add user {}'.format(username),
'action': {
@@ -173,6 +178,7 @@ def get_push_windows_system_user_tasks(system_user, username=None):
def get_push_system_user_tasks(system_user, platform="unixlike", username=None):
"""
获取推送系统用户的 ansible 命令,跟资产无关
:param system_user:
:param platform:
:param username: 当动态时,近推送某个
@@ -204,18 +210,10 @@ def push_system_user_util(system_user, assets, task_name, username=None):
if not assets:
return {}
# 资产按平台分类
assets_sorted = sorted(assets, key=group_asset_by_platform)
platform_hosts = groupby(assets_sorted, key=group_asset_by_platform)
def run_task(_tasks, _hosts):
if not _tasks:
return
task, created = update_or_create_ansible_task(
task_name=task_name, hosts=_hosts, tasks=_tasks, pattern='all',
options=const.TASK_OPTIONS, run_as_admin=True,
)
task.run()
if system_user.username_same_with_user:
if username is None:
# 动态系统用户,但是没有指定 username
@@ -227,6 +225,15 @@ def push_system_user_util(system_user, assets, task_name, username=None):
assert username is None, 'Only Dynamic user can assign `username`'
usernames = [system_user.username]
def run_task(_tasks, _hosts):
if not _tasks:
return
task, created = update_or_create_ansible_task(
task_name=task_name, hosts=_hosts, tasks=_tasks, pattern='all',
options=const.TASK_OPTIONS, run_as_admin=True,
)
task.run()
for platform, _assets in platform_hosts:
_assets = list(_assets)
if not _assets:
@@ -234,36 +241,11 @@ def push_system_user_util(system_user, assets, task_name, username=None):
print(_("Start push system user for platform: [{}]").format(platform))
print(_("Hosts count: {}").format(len(_assets)))
id_asset_map = {_asset.id: _asset for _asset in _assets}
asset_ids = id_asset_map.keys()
no_special_auth = []
special_auth_set = set()
auth_books = AuthBook.objects.filter(asset_id__in=asset_ids).filter(
Q(username__in=usernames) | Q(systemuser__username__in=usernames)
).prefetch_related('systemuser')
for auth_book in auth_books:
auth_book.load_auth()
special_auth_set.add((auth_book.username, auth_book.asset_id))
for _username in usernames:
no_special_assets = []
for asset_id in asset_ids:
if (_username, asset_id) not in special_auth_set:
no_special_assets.append(id_asset_map[asset_id])
if no_special_assets:
no_special_auth.append((_username, no_special_assets))
for _username, no_special_assets in no_special_auth:
tasks = get_push_system_user_tasks(system_user, platform, username=_username)
run_task(tasks, no_special_assets)
for auth_book in auth_books:
system_user._merge_auth(auth_book)
tasks = get_push_system_user_tasks(system_user, platform, username=auth_book.username)
asset = id_asset_map[auth_book.asset_id]
run_task(tasks, [asset])
for u in usernames:
for a in _assets:
system_user.load_asset_special_auth(a, u)
tasks = get_push_system_user_tasks(system_user, platform, username=u)
run_task(tasks, [a])
@shared_task(queue="ansible")

View File

@@ -48,6 +48,7 @@ urlpatterns = [
path('system-users/<uuid:pk>/temp-auth/', api.SystemUserTempAuthInfoApi.as_view(), name='system-user-asset-temp-info'),
path('system-users/<uuid:pk>/tasks/', api.SystemUserTaskApi.as_view(), name='system-user-task-create'),
path('system-users/<uuid:pk>/cmd-filter-rules/', api.SystemUserCommandFilterRuleListApi.as_view(), name='system-user-cmd-filter-rule-list'),
path('cmd-filter-rules/', api.SystemUserCommandFilterRuleListApi.as_view(), name='cmd-filter-rules'),
path('accounts/tasks/', api.AccountTaskCreateAPI.as_view(), name='account-task-create'),

View File

@@ -2,9 +2,10 @@
#
import urllib.parse
import json
import base64
from typing import Callable
import os
import base64
import ctypes
from django.conf import settings
from django.core.cache import cache
@@ -18,10 +19,12 @@ from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
from rest_framework import serializers
from applications.models import Application
from authentication.signals import post_auth_failed, post_auth_success
from common.utils import get_logger, random_string
from common.mixins.api import SerializerMixin
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
from common.utils.common import get_file_by_arch
from orgs.mixins.api import RootOrgViewMixin
from common.http import is_true
from perms.utils.asset.permission import get_asset_system_user_ids_with_actions_by_user
@@ -124,17 +127,40 @@ class ClientProtocolMixin:
options['session bpp:i'] = os.getenv('JUMPSERVER_COLOR_DEPTH', '32')
options['audiomode:i'] = self.parse_env_bool('JUMPSERVER_DISABLE_AUDIO', 'false', '2', '0')
content = ''
for k, v in options.items():
content += f'{k}:{v}\n'
if asset:
name = asset.hostname
elif application:
name = application.name
application.get_rdp_remote_app_setting()
app = f'||jmservisor'
options['remoteapplicationmode:i'] = '1'
options['alternate shell:s'] = app
options['remoteapplicationprogram:s'] = app
options['remoteapplicationname:s'] = name
options['remoteapplicationcmdline:s'] = '- ' + self.get_encrypt_cmdline(application)
else:
name = '*'
content = ''
for k, v in options.items():
content += f'{k}:{v}\n'
return name, content
def get_encrypt_cmdline(self, app: Application):
parameters = app.get_rdp_remote_app_setting()['parameters']
parameters = parameters.encode('ascii')
lib_path = get_file_by_arch('xpack/libs', 'librailencrypt.so')
lib = ctypes.CDLL(lib_path)
lib.encrypt.argtypes = [ctypes.c_char_p, ctypes.c_int]
lib.encrypt.restype = ctypes.c_char_p
rst = lib.encrypt(parameters, len(parameters))
rst = rst.decode('ascii')
return rst
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file', permission_classes=[IsValidUser])
def get_rdp_file(self, request, *args, **kwargs):
if self.request.method == 'GET':
@@ -268,7 +294,7 @@ class SecretDetailMixin:
data.update(asset_detail)
else:
app_detail = self._get_application_secret_detail(app)
system_user.load_app_more_auth(app.id, user.id)
system_user.load_app_more_auth(app.id, user.username, user.id)
data['type'] = 'application'
data.update(app_detail)

View File

@@ -40,5 +40,7 @@ class TokenCreateApi(AuthMixin, CreateAPIView):
return Response(e.as_data(), status=400)
except errors.NeedMoreInfoError as e:
return Response(e.as_data(), status=200)
except errors.PasswordTooSimple as e:
return redirect(e.url)
except errors.MFAUnsetError:
return Response({'error': 'MFA unset, please set first'}, status=400)
except Exception as e:
return Response({"error": str(e)}, status=400)

View File

@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
#
from .backends import *

View File

@@ -0,0 +1,67 @@
# -*- coding: utf-8 -*-
#
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db import transaction
from common.utils import get_logger
from authentication.errors import reason_choices, reason_user_invalid
from .signals import (
saml2_user_authenticated, saml2_user_authentication_failed,
saml2_create_or_update_user
)
__all__ = ['SAML2Backend']
logger = get_logger(__file__)
class SAML2Backend(ModelBackend):
def user_can_authenticate(self, user):
is_valid = getattr(user, 'is_valid', None)
return is_valid or is_valid is None
@transaction.atomic
def get_or_create_from_saml_data(self, request, **saml_user_data):
log_prompt = "Get or Create user [SAML2Backend]: {}"
logger.debug(log_prompt.format('start'))
user, created = get_user_model().objects.get_or_create(
username=saml_user_data['username'], defaults=saml_user_data
)
logger.debug(log_prompt.format("user: {}|created: {}".format(user, created)))
logger.debug(log_prompt.format("Send signal => saml2 create or update user"))
saml2_create_or_update_user.send(
sender=self, request=request, user=user, created=created, attrs=saml_user_data
)
return user, created
def authenticate(self, request, saml_user_data=None, **kwargs):
log_prompt = "Process authenticate [SAML2AuthCodeBackend]: {}"
logger.debug(log_prompt.format('Start'))
if saml_user_data is None:
logger.error(log_prompt.format('saml_user_data is missing'))
return None
logger.debug(log_prompt.format('saml data, {}'.format(saml_user_data)))
username = saml_user_data.get('username')
if not username:
logger.debug(log_prompt.format('username is missing'))
return None
user, created = self.get_or_create_from_saml_data(request, **saml_user_data)
if self.user_can_authenticate(user):
logger.debug(log_prompt.format('SAML2 user login success'))
saml2_user_authenticated.send(
sender=self, request=request, user=user, created=created
)
return user
else:
logger.debug(log_prompt.format('SAML2 user login failed'))
saml2_user_authentication_failed.send(
sender=self, request=request, username=username,
reason=reason_choices.get(reason_user_invalid)
)
return None

View File

@@ -0,0 +1,12 @@
from django.conf import settings
from onelogin.saml2.settings import OneLogin_Saml2_Settings
class JmsSaml2Settings(OneLogin_Saml2_Settings):
def get_sp_key(self):
key = getattr(settings, 'SAML2_SP_KEY_CONTENT', '')
return key
def get_sp_cert(self):
cert = getattr(settings, 'SAML2_SP_CERT_CONTENT', '')
return cert

View File

@@ -0,0 +1,6 @@
from django.dispatch import Signal
saml2_create_or_update_user = Signal(providing_args=('user', 'created', 'request', 'attrs'))
saml2_user_authenticated = Signal(providing_args=('user', 'created', 'request'))
saml2_user_authentication_failed = Signal(providing_args=('request', 'username', 'reason'))

View File

@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
#
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.Saml2AuthRequestView.as_view(), name='saml2-login'),
path('logout/', views.Saml2EndSessionView.as_view(), name='saml2-logout'),
path('callback/', views.Saml2AuthCallbackView.as_view(), name='saml2-callback'),
path('metadata/', views.Saml2AuthMetadataView.as_view(), name='saml2-metadata'),
]

View File

@@ -0,0 +1,295 @@
import copy
from urllib import parse
from django.views import View
from django.contrib import auth as auth
from django.urls import reverse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseServerError
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.errors import OneLogin_Saml2_Error
from onelogin.saml2.idp_metadata_parser import (
OneLogin_Saml2_IdPMetadataParser as IdPMetadataParse,
dict_deep_merge
)
from .settings import JmsSaml2Settings
from common.utils import get_logger
logger = get_logger(__file__)
class PrepareRequestMixin:
@staticmethod
def is_secure():
url_result = parse.urlparse(settings.SITE_URL)
return 'on' if url_result.scheme == 'https' else 'off'
def prepare_django_request(self, request):
result = {
'https': self.is_secure(),
'http_host': request.META['HTTP_HOST'],
'script_name': request.META['PATH_INFO'],
'get_data': request.GET.copy(),
'post_data': request.POST.copy()
}
return result
@staticmethod
def get_idp_settings():
idp_metadata_xml = settings.SAML2_IDP_METADATA_XML
idp_metadata_url = settings.SAML2_IDP_METADATA_URL
logger.debug('Start getting IDP configuration')
xml_idp_settings = None
try:
if idp_metadata_xml.strip():
xml_idp_settings = IdPMetadataParse.parse(idp_metadata_xml)
except Exception as err:
logger.warning('Failed to get IDP metadata XML settings, error: %s', str(err))
url_idp_settings = None
try:
if idp_metadata_url.strip():
url_idp_settings = IdPMetadataParse.parse_remote(
idp_metadata_url, timeout=20
)
except Exception as err:
logger.warning('Failed to get IDP metadata URL settings, error: %s', str(err))
idp_settings = url_idp_settings or xml_idp_settings
if idp_settings is None:
msg = 'Unable to resolve IDP settings. '
tip = 'Please contact your administrator to check system settings,' \
'or login using other methods.'
logger.error(msg)
raise OneLogin_Saml2_Error(msg + tip, OneLogin_Saml2_Error.SETTINGS_INVALID)
logger.debug('IDP settings obtained successfully')
return idp_settings
@staticmethod
def get_attribute_consuming_service():
attr_mapping = settings.SAML2_RENAME_ATTRIBUTES
name_prefix = settings.SITE_URL
if attr_mapping and isinstance(attr_mapping, dict):
attr_list = [
{
"name": '{}/{}'.format(name_prefix, sp_key),
"friendlyName": idp_key, "isRequired": True
}
for idp_key, sp_key in attr_mapping.items()
]
request_attribute_template = {
"attributeConsumingService": {
"isDefault": False,
"serviceName": "JumpServer",
"serviceDescription": "JumpServer",
"requestedAttributes": attr_list
}
}
return request_attribute_template
else:
return {}
@staticmethod
def get_advanced_settings():
try:
other_settings = dict(settings.SAML2_SP_ADVANCED_SETTINGS)
other_settings = copy.deepcopy(other_settings)
except Exception as error:
logger.error('Get other settings error: %s', error)
other_settings = {}
security_default = {
'wantAttributeStatement': False,
'allowRepeatAttributeName': True
}
security = other_settings.get('security', {})
security_default.update(security)
default = {
"organization": {
"en": {
"name": "JumpServer",
"displayname": "JumpServer",
"url": "https://jumpserver.org/"
}
},
}
default.update(other_settings)
default['security'] = security_default
return default
def get_sp_settings(self):
sp_host = settings.SITE_URL
attrs = self.get_attribute_consuming_service()
sp_settings = {
'sp': {
'entityId': f"{sp_host}{reverse('authentication:saml2:saml2-login')}",
'assertionConsumerService': {
'url': f"{sp_host}{reverse('authentication:saml2:saml2-callback')}",
},
'singleLogoutService': {
'url': f"{sp_host}{reverse('authentication:saml2:saml2-logout')}"
}
}
}
sp_settings['sp'].update(attrs)
advanced_settings = self.get_advanced_settings()
sp_settings.update(advanced_settings)
return sp_settings
def get_saml2_settings(self):
sp_settings = self.get_sp_settings()
idp_settings = self.get_idp_settings()
saml2_settings = dict_deep_merge(sp_settings, idp_settings)
return saml2_settings
def init_saml_auth(self, request):
request = self.prepare_django_request(request)
_settings = self.get_saml2_settings()
saml_instance = OneLogin_Saml2_Auth(
request, old_settings=_settings, custom_base_path=settings.SAML_FOLDER
)
return saml_instance
@staticmethod
def value_to_str(attr):
if isinstance(attr, str):
return attr
elif isinstance(attr, list) and len(attr) > 0:
return str(attr[0])
def get_attributes(self, saml_instance):
user_attrs = {}
real_key_index = len(settings.SITE_URL) + 1
attrs = saml_instance.get_attributes()
valid_attrs = ['username', 'name', 'email', 'comment', 'phone']
for attr, value in attrs.items():
attr = attr[real_key_index:]
if attr not in valid_attrs:
continue
user_attrs[attr] = self.value_to_str(value)
return user_attrs
class Saml2AuthRequestView(View, PrepareRequestMixin):
def get(self, request):
log_prompt = "Process SAML GET requests: {}"
logger.debug(log_prompt.format('Start'))
try:
saml_instance = self.init_saml_auth(request)
except OneLogin_Saml2_Error as error:
logger.error(log_prompt.format('Init saml auth error: %s' % error))
return HttpResponse(error, status=412)
next_url = settings.AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT
url = saml_instance.login(return_to=next_url)
logger.debug(log_prompt.format('Redirect login url'))
return HttpResponseRedirect(url)
class Saml2EndSessionView(View, PrepareRequestMixin):
http_method_names = ['get', 'post', ]
def get(self, request):
log_prompt = "Process SAML GET requests: {}"
logger.debug(log_prompt.format('Start'))
return self.post(request)
def post(self, request):
log_prompt = "Process SAML POST requests: {}"
logger.debug(log_prompt.format('Start'))
logout_url = settings.LOGOUT_REDIRECT_URL or '/'
if request.user.is_authenticated:
logger.debug(log_prompt.format('Log out the current user: {}'.format(request.user)))
auth.logout(request)
if settings.SAML2_LOGOUT_COMPLETELY:
saml_instance = self.init_saml_auth(request)
logger.debug(log_prompt.format('Log out IDP user session synchronously'))
return HttpResponseRedirect(saml_instance.logout())
logger.debug(log_prompt.format('Redirect logout url'))
return HttpResponseRedirect(logout_url)
class Saml2AuthCallbackView(View, PrepareRequestMixin):
def post(self, request):
log_prompt = "Process SAML2 POST requests: {}"
post_data = request.POST
try:
saml_instance = self.init_saml_auth(request)
except OneLogin_Saml2_Error as error:
logger.error(log_prompt.format('Init saml auth error: %s' % error))
return HttpResponse(error, status=412)
request_id = None
if 'AuthNRequestID' in request.session:
request_id = request.session['AuthNRequestID']
logger.debug(log_prompt.format('Process saml response'))
saml_instance.process_response(request_id=request_id)
errors = saml_instance.get_last_error_reason()
if errors:
logger.error(log_prompt.format('Saml response has error: %s' % str(errors)))
return HttpResponseRedirect(settings.AUTH_SAML2_AUTHENTICATION_FAILURE_REDIRECT_URI)
if 'AuthNRequestID' in request.session:
del request.session['AuthNRequestID']
logger.debug(log_prompt.format('Process authenticate'))
saml_user_data = self.get_attributes(saml_instance)
user = auth.authenticate(request=request, saml_user_data=saml_user_data)
if user and user.is_valid:
logger.debug(log_prompt.format('Login: {}'.format(user)))
auth.login(self.request, user)
logger.debug(log_prompt.format('Redirect'))
next_url = saml_instance.redirect_to(post_data.get('RelayState', '/'))
return HttpResponseRedirect(next_url)
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
class Saml2AuthMetadataView(View, PrepareRequestMixin):
def get(self, request):
saml_settings = self.get_sp_settings()
saml_settings = JmsSaml2Settings(
settings=saml_settings, sp_validation_only=True,
custom_base_path=settings.SAML_FOLDER
)
metadata = saml_settings.get_sp_metadata()
errors = saml_settings.validate_metadata(metadata)
key = saml_settings.get_sp_key()
cert = saml_settings.get_sp_cert()
if not key:
errors.append('Not found SP private key')
if not cert:
errors.append('Not found SP cert')
if len(errors) == 0:
resp = HttpResponse(content=metadata, content_type='text/xml')
else:
content = "Error occur: <br>"
content += '<br>'.join(errors)
resp = HttpResponseServerError(content=content)
return resp

View File

@@ -7,6 +7,10 @@ from django.dispatch import receiver
from django_cas_ng.signals import cas_user_authenticated
from jms_oidc_rp.signals import openid_user_login_failed, openid_user_login_success
from authentication.backends.saml2.signals import (
saml2_user_authenticated, saml2_user_authentication_failed
)
from .signals import post_auth_success, post_auth_failed
@@ -42,3 +46,15 @@ def on_oidc_user_login_failed(sender, username, request, reason, **kwargs):
def on_cas_user_login_success(sender, request, user, **kwargs):
request.session['auth_backend'] = settings.AUTH_BACKEND_CAS
post_auth_success.send(sender, user=user, request=request)
@receiver(saml2_user_authenticated)
def on_saml2_user_login_success(sender, request, user, **kwargs):
request.session['auth_backend'] = settings.AUTH_BACKEND_SAML2
post_auth_success.send(sender, user=user, request=request)
@receiver(saml2_user_authentication_failed)
def on_saml2_user_login_failed(sender, request, username, reason, **kwargs):
request.session['auth_backend'] = settings.AUTH_BACKEND_SAML2
post_auth_failed.send(sender, username=username, request=request, reason=reason)

View File

@@ -11,6 +11,7 @@
<b>{% trans 'Login city' %}:</b> {{ city }}({{ ip }})
</p>
-
<p>
{% trans 'If you suspect that the login behavior is abnormal, please modify the account password in time.' %}
</p>

View File

@@ -11,9 +11,8 @@
</a>
</p>
-
<p>
{% trans 'This link is valid for 1 hour. After it expires' %}
<a href="{{ forget_password_url }}?email={{ user.email }}">
{% trans 'request new one' %}
</a>
<a href="{{ forget_password_url }}?email={{ user.email }}">{% trans 'request new one' %}</a>
</p>

View File

@@ -8,6 +8,7 @@
<b>{% trans 'IP' %}:</b> {{ ip_address }} <br />
<b>{% trans 'Browser' %}:</b> {{ browser }}
</p>
-
<p>
{% trans 'If the password update was not initiated by you, your account may have security issues' %} <br />
{% trans 'If you have any questions, you can contact the administrator' %}

View File

@@ -8,6 +8,7 @@
<b>{% trans 'IP' %}:</b> {{ ip_address }} <br />
<b>{% trans 'Browser' %}:</b> {{ browser }}
</p>
-
<p>
{% trans 'If the public key update was not initiated by you, your account may have security issues' %} <br />
{% trans 'If you have any questions, you can contact the administrator' %}

View File

@@ -56,5 +56,6 @@ urlpatterns = [
# openid
path('cas/', include(('authentication.backends.cas.urls', 'authentication'), namespace='cas')),
path('openid/', include(('jms_oidc_rp.urls', 'authentication'), namespace='openid')),
path('saml2/', include(('authentication.backends.saml2.urls', 'authentication'), namespace='saml2')),
path('captcha/', include('captcha.urls')),
]

View File

@@ -46,50 +46,35 @@ class UserLoginView(mixins.AuthMixin, FormView):
# show jumpserver login page if request http://{JUMP-SERVER}/?admin=1
if self.request.GET.get("admin", 0):
return None
auth_types = [m for m in self.get_support_auth_methods() if m.get('auto_redirect')]
if not auth_types:
return None
# 明确直接登录哪个
login_to = settings.LOGIN_REDIRECT_TO_BACKEND.upper()
if login_to == 'DIRECT':
return None
auth_method = next(filter(lambda x: x['name'] == login_to, auth_types), None)
if not auth_method:
auth_method = auth_types[0]
auth_name, redirect_url = auth_method['name'], auth_method['url']
next_url = request.GET.get('next') or '/'
auth_type = ''
query_string = request.GET.urlencode()
redirect_url = '{}?next={}&{}'.format(redirect_url, next_url, query_string)
if settings.AUTH_OPENID:
auth_type = 'OIDC'
openid_auth_url = reverse(settings.AUTH_OPENID_AUTH_LOGIN_URL_NAME)
openid_auth_url = openid_auth_url + f'?next={next_url}'
else:
openid_auth_url = None
if settings.AUTH_CAS:
auth_type = 'CAS'
cas_auth_url = reverse(settings.CAS_LOGIN_URL_NAME) + f'?next={next_url}'
else:
cas_auth_url = None
if not any([openid_auth_url, cas_auth_url]):
return None
login_redirect = settings.LOGIN_REDIRECT_TO_BACKEND.lower()
if login_redirect in ['direct']:
return None
if login_redirect in ['cas'] and cas_auth_url:
auth_url = cas_auth_url
elif login_redirect in ['openid', 'oidc'] and openid_auth_url:
auth_url = openid_auth_url
else:
auth_url = openid_auth_url or cas_auth_url
if settings.LOGIN_REDIRECT_TO_BACKEND or not settings.LOGIN_REDIRECT_MSG_ENABLED:
redirect_url = auth_url
else:
if settings.LOGIN_REDIRECT_MSG_ENABLED:
message_data = {
'title': _('Redirecting'),
'message': _("Redirecting to {} authentication").format(auth_type),
'redirect_url': auth_url,
'message': _("Redirecting to {} authentication").format(auth_name),
'redirect_url': redirect_url,
'interval': 3,
'has_cancel': True,
'cancel_url': reverse('authentication:login') + '?admin=1'
}
redirect_url = FlashMessageUtil.gen_message_url(message_data)
query_string = request.GET.urlencode()
redirect_url = "{}&{}".format(redirect_url, query_string)
return redirect_url
def get(self, request, *args, **kwargs):
@@ -158,19 +143,28 @@ class UserLoginView(mixins.AuthMixin, FormView):
'name': 'OpenID',
'enabled': settings.AUTH_OPENID,
'url': reverse('authentication:openid:login'),
'logo': static('img/login_oidc_logo.png')
'logo': static('img/login_oidc_logo.png'),
'auto_redirect': True # 是否支持自动重定向
},
{
'name': 'CAS',
'enabled': settings.AUTH_CAS,
'url': reverse('authentication:cas:cas-login'),
'logo': static('img/login_cas_logo.png')
'logo': static('img/login_cas_logo.png'),
'auto_redirect': True
},
{
'name': 'SAML2',
'enabled': settings.AUTH_SAML2,
'url': reverse('authentication:saml2:saml2-login'),
'logo': static('img/login_saml2_logo.png'),
'auto_redirect': True
},
{
'name': _('WeCom'),
'enabled': settings.AUTH_WECOM,
'url': reverse('authentication:wecom-qr-login'),
'logo': static('img/login_wecom_logo.png')
'logo': static('img/login_wecom_logo.png'),
},
{
'name': _('DingTalk'),
@@ -292,6 +286,8 @@ class UserLogoutView(TemplateView):
return settings.AUTH_OPENID_AUTH_LOGOUT_URL_NAME
elif 'CAS' in backend:
return settings.CAS_LOGOUT_URL_NAME
elif 'saml2' in backend:
return settings.SAML2_LOGOUT_URL_NAME
return None
def get(self, request, *args, **kwargs):

View File

@@ -173,7 +173,6 @@ class Cache(metaclass=CacheType):
def expire(self, *fields):
self._data = None
if not fields:
logger.debug(f'Delete cached key: key={self.key}')
self.redis.delete(self.key)
else:
self.redis.hdel(self.key, *fields)

View File

@@ -1,6 +1,9 @@
from common.utils import get_logger
from contextlib import contextmanager
from django.db import connections
from common.utils import get_logger
logger = get_logger(__file__)
@@ -44,3 +47,10 @@ def get_objects(model, pks):
def close_old_connections():
for conn in connections.all():
conn.close_if_unusable_or_obsolete()
@contextmanager
def safe_db_connection():
close_old_connections()
yield
close_old_connections()

View File

@@ -170,7 +170,7 @@ class BaseService(object):
def _restart(self):
if self.retry > self.max_retry:
logging.info("Service start failed, exit: ", self.name)
logging.info("Service start failed, exit: {}".format(self.name))
self.EXIT_EVENT.set()
return
self.retry += 1

View File

@@ -151,12 +151,29 @@ class DingTalk:
'data': data
}
data = self._request.post(URL.SEND_MESSAGE_BY_TEMPLATE, json=body, with_token=True)
return data
def send_markdown(self, user_ids, title, msg):
body = {
'agent_id': self._agentid,
'userid_list': ','.join(user_ids),
'to_all_user': False,
'msg': {
'msgtype': 'markdown',
'markdown': {
'title': title,
'text': msg
}
}
}
logger.info(f'Dingtalk send markdown to user {user_ids}: {msg}')
data = self._request.post(URL.SEND_MESSAGE, json=body, with_token=True)
return data
def send_text(self, user_ids, msg):
body = {
'agent_id': self._agentid,
'userid_list': ','.join(user_ids),
# 'dept_id_list': '',
'to_all_user': False,
'msg': {
'msgtype': 'text',
@@ -165,7 +182,7 @@ class DingTalk:
}
}
}
logger.info(f'Dingtalk send text: user_ids={user_ids} msg={msg}')
logger.info(f'Dingtalk send msg to user {user_ids}: {msg}')
data = self._request.post(URL.SEND_MESSAGE, json=body, with_token=True)
return data

View File

@@ -29,7 +29,7 @@ def set_default(data: dict, default: dict):
class DictWrapper:
def __init__(self, data:dict):
def __init__(self, data: dict):
self.raw_data = data
def __getitem__(self, item):
@@ -51,7 +51,7 @@ class DictWrapper:
return str(self.raw_data)
def __repr__(self):
return str(self.raw_data)
return repr(self.raw_data)
def as_request(func):

View File

@@ -90,7 +90,10 @@ class WeCom(RequestMixin):
timeout=timeout
)
def send_text(self, users: Iterable, msg: AnyStr, **kwargs):
def send_markdown(self, users: Iterable, msg: AnyStr, **kwargs):
pass
def send_text(self, users: Iterable, msg: AnyStr, markdown=False, **kwargs):
"""
https://open.work.weixin.qq.com/api/doc/90000/90135/90236
@@ -115,6 +118,13 @@ class WeCom(RequestMixin):
},
**extra_params
}
if markdown:
body['msgtype'] = 'markdown'
body["markdown"] = {
"content": msg
}
body.pop('text', '')
logger.info(f'Wecom send text: users={users} msg={msg}')
data = self._requests.post(URL.SEND_MESSAGE, json=body, check_errcode_is_0=False)
@@ -124,6 +134,9 @@ class WeCom(RequestMixin):
return users
self._requests.check_errcode_is_0(data)
if 'invaliduser' not in data:
return ()
invaliduser = data['invaliduser']
if not invaliduser:
return ()

View File

@@ -1,4 +1,6 @@
from django.core.mail import send_mail
import os
from django.core.mail import send_mail, EmailMultiAlternatives
from django.conf import settings
from celery import shared_task
@@ -24,11 +26,31 @@ def send_mail_async(*args, **kwargs):
if len(args) == 3:
args = list(args)
args[0] = (settings.EMAIL_SUBJECT_PREFIX or '') + args[0]
email_from = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
args.insert(2, email_from)
from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
args.insert(2, from_email)
args = tuple(args)
try:
return send_mail(*args, **kwargs)
except Exception as e:
logger.error("Sending mail error: {}".format(e))
@shared_task
def send_mail_attachment_async(subject, message, recipient_list, attachment_list=None):
if attachment_list is None:
attachment_list = []
from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
email = EmailMultiAlternatives(
subject=subject,
body=message,
from_email=from_email,
to=recipient_list
)
for attachment in attachment_list:
email.attach_file(attachment)
os.remove(attachment)
try:
return email.send()
except Exception as e:
logger.error("Sending mail attachment error: {}".format(e))

View File

@@ -10,7 +10,10 @@ from functools import wraps
import time
import ipaddress
import psutil
from typing import Iterable
import platform
import os
from django.conf import settings
UUID_PATTERN = re.compile(r'\w{8}(-\w{4}){3}-\w{12}')
ipip_db = None
@@ -252,7 +255,39 @@ def get_cpu_load():
return float(single_cpu_load_1)
def get_docker_mem_usage_if_limit():
try:
with open('/sys/fs/cgroup/memory/memory.limit_in_bytes') as f:
limit_in_bytes = int(f.readline())
total = psutil.virtual_memory().total
if limit_in_bytes >= total:
raise ValueError('Not limit')
with open('/sys/fs/cgroup/memory/memory.usage_in_bytes') as f:
usage_in_bytes = int(f.readline())
with open('/sys/fs/cgroup/memory/memory.stat') as f:
inactive_file = 0
for line in f:
if line.startswith('total_inactive_file'):
name, inactive_file = line.split()
break
if line.startswith('inactive_file'):
name, inactive_file = line.split()
continue
inactive_file = int(inactive_file)
return ((usage_in_bytes - inactive_file) / limit_in_bytes) * 100
except Exception as e:
return None
def get_memory_usage():
usage = get_docker_mem_usage_if_limit()
if usage is not None:
return usage
return psutil.virtual_memory().percent
@@ -293,3 +328,13 @@ def unique(objects, key=None):
if v not in seen:
seen[v] = obj
return list(seen.values())
def get_file_by_arch(dir, filename):
platform_name = platform.system()
arch = platform.machine()
file_path = os.path.join(
settings.BASE_DIR, dir, platform_name, arch, filename
)
return file_path

View File

@@ -1,6 +1,13 @@
import json
import redis
from django.conf import settings
from common.db.utils import safe_db_connection
from common.utils import get_logger
logger = get_logger(__name__)
def get_redis_client(db):
rc = redis.StrictRedis(
@@ -16,6 +23,7 @@ class RedisPubSub:
def __init__(self, ch, db=10):
self.ch = ch
self.redis = get_redis_client(db)
self.subscriber = None
def subscribe(self):
ps = self.redis.pubsub()
@@ -23,5 +31,45 @@ class RedisPubSub:
return ps
def publish(self, data):
self.redis.publish(self.ch, data)
data_json = json.dumps(data)
self.redis.publish(self.ch, data_json)
return True
def keep_handle_msg(self, handle):
"""
handle arg is the pub published
:param handle: lambda item: do_something
:return:
"""
self.close_handle_msg()
sub = self.subscribe()
self.subscriber = sub
msgs = sub.listen()
try:
for msg in msgs:
if msg["type"] != "message":
continue
try:
item_json = msg['data'].decode()
item = json.loads(item_json)
with safe_db_connection():
handle(item)
except Exception as e:
logger.error('Subscribe handler handle msg error: ', e)
except Exception as e:
logger.error('Consume msg error: ', e)
try:
sub.close()
except Exception as e:
logger.error("Redis observer close error: ", e)
def close_handle_msg(self):
if self.subscriber:
self.subscriber.close()
self.subscriber = None

19
apps/common/utils/file.py Normal file
View File

@@ -0,0 +1,19 @@
import os
import csv
import pyzipper
def create_csv_file(filename, headers, rows, ):
with open(filename, 'w', encoding='utf-8-sig')as f:
w = csv.writer(f)
w.writerow(headers)
w.writerows(rows)
def encrypt_and_compress_zip_file(filename, secret_password, encrypted_filename):
with pyzipper.AESZipFile(
filename, 'w', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES
) as zf:
zf.setpassword(secret_password)
with open(encrypted_filename, 'rb') as f:
zf.writestr(os.path.basename(encrypted_filename), f.read())

View File

@@ -1,7 +1,10 @@
from functools import wraps
import threading
from redis_lock import Lock as RedisLock, NotAcquired
from redis_lock import (
Lock as RedisLock, NotAcquired, UNLOCK_SCRIPT,
EXTEND_SCRIPT, RESET_SCRIPT, RESET_ALL_SCRIPT
)
from redis import Redis
from django.db import transaction
@@ -49,7 +52,8 @@ class DistributedLock(RedisLock):
else:
auto_renewal = False
super().__init__(redis_client=redis, name=name, expire=expire, auto_renewal=auto_renewal)
super().__init__(redis_client=redis, name='{' + name + '}', expire=expire, auto_renewal=auto_renewal)
self.register_scripts(redis)
self._release_on_transaction_commit = release_on_transaction_commit
self._release_raise_exc = release_raise_exc
self._reentrant = reentrant
@@ -71,8 +75,16 @@ class DistributedLock(RedisLock):
# 要创建一个新的锁对象
with self.__class__(**self.kwargs_copy):
return func(*args, **kwds)
return inner
@classmethod
def register_scripts(cls, redis_client):
cls.unlock_script = redis_client.register_script(UNLOCK_SCRIPT)
cls.extend_script = redis_client.register_script(EXTEND_SCRIPT)
cls.reset_script = redis_client.register_script(RESET_SCRIPT)
cls.reset_all_script = redis_client.register_script(RESET_ALL_SCRIPT)
def locked_by_me(self):
if self.locked():
if self.get_owner_id() == self.id:
@@ -92,8 +104,7 @@ class DistributedLock(RedisLock):
if self._reentrant:
if self.locked_by_current_thread():
self._acquired_reentrant_lock = True
logger.debug(
f'Reentry lock ok: lock_id={self.id} owner_id={self.get_owner_id()} lock={self.name} thread={self._thread_id}')
logger.debug(f'Reentry lock ok: lock_id={self.id} owner_id={self.get_owner_id()} lock={self.name} thread={self._thread_id}')
return True
logger.debug(f'Attempt acquire reentrant-lock: lock_id={self.id} lock={self.name} thread={self._thread_id}')
@@ -102,7 +113,8 @@ class DistributedLock(RedisLock):
logger.debug(f'Acquired reentrant-lock ok: lock_id={self.id} lock={self.name} thread={self._thread_id}')
setattr(thread_local, self.name, self.id)
else:
logger.debug(f'Acquired reentrant-lock failed: lock_id={self.id} lock={self.name} thread={self._thread_id}')
logger.debug(
f'Acquired reentrant-lock failed: lock_id={self.id} lock={self.name} thread={self._thread_id}')
return acquired
else:
logger.debug(f'Attempt acquire lock: lock_id={self.id} lock={self.name} thread={self._thread_id}')
@@ -174,11 +186,13 @@ class DistributedLock(RedisLock):
else:
_release = self._release_on_reentrant_locked_by_brother
else:
self._raise_exc_with_log(f'Reentrant-lock is not acquired: lock_id={self.id} lock={self.name} thread={self._thread_id}')
self._raise_exc_with_log(
f'Reentrant-lock is not acquired: lock_id={self.id} lock={self.name} thread={self._thread_id}')
# 处理是否在事务提交时才释放锁
if self._release_on_transaction_commit:
logger.debug(f'Release lock on transaction commit ... :lock_id={self.id} lock={self.name} thread={self._thread_id}')
logger.debug(
f'Release lock on transaction commit ... :lock_id={self.id} lock={self.name} thread={self._thread_id}')
transaction.on_commit(_release)
else:
_release()

View File

@@ -17,6 +17,8 @@ alphanumeric_re = re.compile(r'^[0-9a-zA-Z_@\-\.]*$')
alphanumeric_cn_re = re.compile(r'^[0-9a-zA-Z_@\-\.\u4E00-\u9FA5]*$')
alphanumeric_win_re = re.compile(r'^[0-9a-zA-Z_@#%&~\^\$\-\.\u4E00-\u9FA5]*$')
class ProjectUniqueValidator(UniqueTogetherValidator):
def __call__(self, attrs, serializer):

View File

@@ -229,6 +229,30 @@ class Config(dict):
'AUTH_SSO': False,
'AUTH_SSO_AUTHKEY_TTL': 60 * 15,
# SAML2 认证
'AUTH_SAML2': False,
'SAML2_LOGOUT_COMPLETELY': True,
'AUTH_SAML2_ALWAYS_UPDATE_USER': True,
'SAML2_RENAME_ATTRIBUTES': {'uid': 'username', 'email': 'email'},
'SAML2_SP_ADVANCED_SETTINGS': {
"organization": {
"en": {
"name": "JumpServer",
"displayname": "JumpServer",
"url": "https://jumpserver.org/"
}
},
"strict": True,
"security": {
}
},
'SAML2_IDP_METADATA_URL': '',
'SAML2_IDP_METADATA_XML': '',
'SAML2_SP_KEY_CONTENT': '',
'SAML2_SP_CERT_CONTENT': '',
'AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT': '/',
'AUTH_SAML2_AUTHENTICATION_FAILURE_REDIRECT_URI': '/',
# 企业微信
'AUTH_WECOM': False,
'WECOM_CORPID': '',
@@ -246,7 +270,7 @@ class Config(dict):
'FEISHU_APP_ID': '',
'FEISHU_APP_SECRET': '',
'LOGIN_REDIRECT_TO_BACKEND': '', # 'OPENID / CAS
'LOGIN_REDIRECT_TO_BACKEND': '', # 'OPENID / CAS / SAML2
'LOGIN_REDIRECT_MSG_ENABLED': True,
'SMS_ENABLED': False,

View File

@@ -4,7 +4,7 @@ import os
import ldap
from django.utils.translation import ugettext_lazy as _
from ..const import CONFIG, PROJECT_DIR
from ..const import CONFIG, PROJECT_DIR, BASE_DIR
# OTP settings
OTP_ISSUER_NAME = CONFIG.OTP_ISSUER_NAME
@@ -122,7 +122,16 @@ AUTH_FEISHU = CONFIG.AUTH_FEISHU
FEISHU_APP_ID = CONFIG.FEISHU_APP_ID
FEISHU_APP_SECRET = CONFIG.FEISHU_APP_SECRET
# Saml2 auth
AUTH_SAML2 = CONFIG.AUTH_SAML2
AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT = CONFIG.AUTH_SAML2_PROVIDER_AUTHORIZATION_ENDPOINT
AUTH_SAML2_AUTHENTICATION_FAILURE_REDIRECT_URI = CONFIG.AUTH_SAML2_AUTHENTICATION_FAILURE_REDIRECT_URI
AUTH_SAML2_ALWAYS_UPDATE_USER = CONFIG.AUTH_SAML2_ALWAYS_UPDATE_USER
SAML2_LOGOUT_COMPLETELY = CONFIG.SAML2_LOGOUT_COMPLETELY
SAML2_RENAME_ATTRIBUTES = CONFIG.SAML2_RENAME_ATTRIBUTES
SAML2_SP_ADVANCED_SETTINGS = CONFIG.SAML2_SP_ADVANCED_SETTINGS
SAML2_LOGIN_URL_NAME = "authentication:saml2:saml2-login"
SAML2_LOGOUT_URL_NAME = "authentication:saml2:saml2-logout"
# Other setting
TOKEN_EXPIRATION = CONFIG.TOKEN_EXPIRATION
@@ -141,6 +150,7 @@ AUTH_BACKEND_WECOM = 'authentication.backends.api.WeComAuthentication'
AUTH_BACKEND_DINGTALK = 'authentication.backends.api.DingTalkAuthentication'
AUTH_BACKEND_FEISHU = 'authentication.backends.api.FeiShuAuthentication'
AUTH_BACKEND_AUTH_TOKEN = 'authentication.backends.api.AuthorizationTokenAuthentication'
AUTH_BACKEND_SAML2 = 'authentication.backends.saml2.SAML2Backend'
AUTHENTICATION_BACKENDS = [
@@ -156,7 +166,11 @@ if AUTH_OPENID:
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_OIDC_CODE)
if AUTH_RADIUS:
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_RADIUS)
if AUTH_SAML2:
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_SAML2)
ONLY_ALLOW_EXIST_USER_AUTH = CONFIG.ONLY_ALLOW_EXIST_USER_AUTH
ONLY_ALLOW_AUTH_FROM_SOURCE = CONFIG.ONLY_ALLOW_AUTH_FROM_SOURCE
SAML_FOLDER = os.path.join(BASE_DIR, 'authentication', 'backends', 'saml2')

View File

@@ -55,7 +55,7 @@ api_info = openapi.Info(
description="JumpServer Restful api docs",
terms_of_service="https://www.jumpserver.org",
contact=openapi.Contact(email="support@fit2cloud.com"),
license=openapi.License(name="GPLv2 License"),
license=openapi.License(name="GPLv3 License"),
)

View File

@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c9823f96465943a304034daf10ad6a98f2e02d8fe80a145f6e0196693a933387
size 93547
oid sha256:151597996418474bb0ec965084ef04c8e1f93b6546b6829a1e0174e9e1f2e43a
size 95238

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,7 @@ class DingTalk(BackendBase):
def send_msg(self, users, message, subject=None):
accounts, __, __ = self.get_accounts(users)
return self.dingtalk.send_text(accounts, message)
return self.dingtalk.send_markdown(accounts, subject, message)
backend = DingTalk

View File

@@ -17,7 +17,7 @@ class WeCom(BackendBase):
def send_msg(self, users, message, subject=None):
accounts, __, __ = self.get_accounts(users)
return self.wecom.send_text(accounts, message)
return self.wecom.send_text(accounts, message, markdown=True)
backend = WeCom

View File

@@ -1,5 +1,4 @@
from django.db import models
from django.utils.translation import gettext_lazy as _
from common.db.models import JMSModel

View File

@@ -94,7 +94,7 @@ class Message(metaclass=MessageType):
traceback.print_exc()
@classmethod
def send_test_msg(cls, ding=True):
def send_test_msg(cls, ding=True, wecom=False):
msg = cls.gen_test_msg()
if not msg:
return
@@ -104,6 +104,8 @@ class Message(metaclass=MessageType):
backends = []
if ding:
backends.append(BACKEND.DINGTALK)
if wecom:
backends.append(BACKEND.WECOM)
msg.send_msg(users, backends)
@staticmethod
@@ -113,8 +115,17 @@ class Message(metaclass=MessageType):
def get_html_msg(self) -> dict:
return self.get_common_msg()
def get_markdown_msg(self) -> dict:
h = HTML2Text()
h.body_width = 300
msg = self.get_html_msg()
content = msg['message']
msg['message'] = h.handle(content)
return msg
def get_text_msg(self) -> dict:
h = HTML2Text()
h.body_width = 90
msg = self.get_html_msg()
content = msg['message']
h.ignore_links = self.text_msg_ignore_links
@@ -130,6 +141,10 @@ class Message(metaclass=MessageType):
msg = self.get_text_msg()
return msg
@lazyproperty
def markdown_msg(self):
return self.get_markdown_msg()
@lazyproperty
def html_msg(self) -> dict:
msg = self.get_html_msg()
@@ -167,17 +182,17 @@ class Message(metaclass=MessageType):
# 支持不同发送消息的方式定义自己的消息内容,比如有些支持 html 标签
def get_dingtalk_msg(self) -> dict:
# 钉钉相同的消息一天只能发一次,所以给所有消息添加基于时间的序号,使他们不相同
message = self.text_msg['message']
message = self.markdown_msg['message']
time = local_now().strftime('%Y-%m-%d %H:%M:%S')
suffix = '\n{}: {}'.format(_('Time'), time)
return {
'subject': self.text_msg['subject'],
'subject': self.markdown_msg['subject'],
'message': message + suffix
}
def get_wecom_msg(self) -> dict:
return self.text_msg
return self.markdown_msg
def get_feishu_msg(self) -> dict:
return self.text_msg
@@ -207,12 +222,12 @@ class Message(metaclass=MessageType):
return messages_cls
@classmethod
def test_all_messages(cls):
def test_all_messages(cls, ding=True, wecom=False):
messages_cls = cls.get_all_sub_messages()
for _cls in messages_cls:
try:
msg = _cls.send_test_msg()
_cls.send_test_msg(ding=ding, wecom=wecom)
except NotImplementedError:
continue

View File

@@ -46,7 +46,6 @@ def on_site_message_create(sender, instance, created, **kwargs):
'message': instance.message,
'users': user_ids
}
data = json.dumps(data)
new_site_msg_chan.publish(data)

View File

@@ -1,31 +1,36 @@
import threading
import json
from redis.exceptions import ConnectionError
from channels.generic.websocket import JsonWebsocketConsumer
from common.db.utils import close_old_connections
from common.utils import get_logger
from common.db.utils import safe_db_connection
from .site_msg import SiteMessageUtil
from .signals_handler import new_site_msg_chan
from .signals_handler import NewSiteMsgSubPub
logger = get_logger(__name__)
class SiteMsgWebsocket(JsonWebsocketConsumer):
refresh_every_seconds = 10
chan = None
def __init__(self, *args, **kwargs):
super(SiteMsgWebsocket, self).__init__(*args, **kwargs)
self.subscriber = None
def connect(self):
user = self.scope["user"]
if user.is_authenticated:
self.accept()
self.chan = new_site_msg_chan.subscribe()
thread = threading.Thread(target=self.unread_site_msg_count)
thread = threading.Thread(target=self.watch_recv_new_site_msg)
thread.start()
else:
self.close()
def disconnect(self, code):
if self.subscriber:
self.subscriber.close_handle_msg()
def receive(self, text_data=None, bytes_data=None, **kwargs):
data = json.loads(text_data)
refresh_every_seconds = data.get('refresh_every_seconds')
@@ -45,45 +50,20 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
logger.debug('Send unread count to user: {} {}'.format(user_id, unread_count))
self.send_json({'type': 'unread_count', 'unread_count': unread_count})
def unread_site_msg_count(self):
def watch_recv_new_site_msg(self):
ws = self
user_id = str(self.scope["user"].id)
self.send_unread_msg_count()
try:
msgs = self.chan.listen()
# 开始之前关闭连接因为server端可能关闭了连接而 client 还在 CONN_MAX_AGE 中
for message in msgs:
if message['type'] != 'message':
continue
close_old_connections()
try:
msg = json.loads(message['data'].decode())
except json.JSONDecoder as e:
logger.debug('Decode json error: ', e)
continue
if not msg:
continue
logger.debug('New site msg recv, may be mine: {}'.format(msg))
users = msg.get('users', [])
logger.debug('Message users: {}'.format(users))
if user_id in users:
self.send_unread_msg_count()
close_old_connections()
except ConnectionError:
logger.error('Redis chan closed')
finally:
logger.info('Notification ws thread end')
close_old_connections()
def disconnect(self, close_code):
try:
if self.chan is not None:
self.chan.close()
self.close()
finally:
close_old_connections()
logger.info('Notification websocket disconnect')
# 先发一个消息再说
with safe_db_connection():
self.send_unread_msg_count()
def handle_new_site_msg_recv(msg):
users = msg.get('users', [])
logger.debug('New site msg recv, message users: {}'.format(users))
if user_id in users:
ws.send_unread_msg_count()
subscriber = NewSiteMsgSubPub()
self.subscriber = subscriber
subscriber.keep_handle_msg(handle_new_site_msg_recv)

View File

@@ -54,6 +54,9 @@ class AdHocDisplay(Display, metaclass=UnSingleton):
self.log_file.write(msg)
def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False, newline=True):
if log_only:
return
if color:
msg = stringc(msg, color)
@@ -62,7 +65,5 @@ class AdHocDisplay(Display, metaclass=UnSingleton):
else:
msg2 = msg
if log_only:
self._write_to_log_file(msg2)
else:
self._write_to_screen(msg2, stderr)
self._write_to_log_file(msg2)
self._write_to_screen(msg2, stderr)

View File

@@ -72,7 +72,7 @@ class OrgResourceStatisticsCache(OrgRelatedCache):
self.org = org
def get_key_suffix(self):
return f'<org:{self.org.id}>'
return f'org_{self.org.id}'
def get_current_org(self):
return self.org

View File

@@ -6,9 +6,8 @@ from functools import partial
from django.dispatch import receiver
from django.utils.functional import LazyObject
from common.db.utils import close_old_connections
from django.db.models.signals import m2m_changed
from django.db.models.signals import post_save, post_delete, pre_delete
from django.db.models.signals import post_save, pre_delete
from orgs.utils import tmp_to_org
from orgs.models import Organization, OrganizationMember
@@ -47,25 +46,9 @@ def subscribe_orgs_mapping_expire(sender, **kwargs):
logger.debug("Start subscribe for expire orgs mapping from memory")
def keep_subscribe_org_mapping():
while True:
try:
subscribe = orgs_mapping_for_memory_pub_sub.subscribe()
msgs = subscribe.listen()
# 开始之前关闭连接因为server端可能关闭了连接而 client 还在 CONN_MAX_AGE 中
close_old_connections()
for message in msgs:
if message['type'] != 'message':
continue
if message['data'] == b'error':
raise ValueError
Organization.expire_orgs_mapping()
logger.debug('Expire orgs mapping: ' + str(message['data']))
except Exception as e:
logger.exception(f'subscribe_orgs_mapping_expire: {e}')
Organization.expire_orgs_mapping()
finally:
# 结束收关闭连接
close_old_connections()
orgs_mapping_for_memory_pub_sub.keep_handle_msg(
lambda org_id: Organization.expire_orgs_mapping()
)
t = threading.Thread(target=keep_subscribe_org_mapping)
t.daemon = True

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.1.12 on 2021-11-05 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('perms', '0020_auto_20210910_1103'),
]
operations = [
migrations.AlterField(
model_name='applicationpermission',
name='type',
field=models.CharField(choices=[('mysql', 'MySQL'), ('oracle', 'Oracle'), ('postgresql', 'PostgreSQL'), ('mariadb', 'MariaDB'), ('sqlserver', 'SQLServer'), ('chrome', 'Chrome'), ('mysql_workbench', 'MySQL Workbench'), ('vmware_client', 'vSphere Client'), ('custom', 'Custom'), ('k8s', 'Kubernetes')], max_length=16, verbose_name='Type'),
),
]

View File

@@ -16,6 +16,7 @@
</ul>
<br />
-
<p>
{% trans 'If you have any question, please contact the administrator' %}
</p>

View File

@@ -6,6 +6,7 @@ from rest_framework import generics
from rest_framework.views import Response, APIView
from orgs.models import Organization
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from ..utils import (
LDAPServerUtil, LDAPCacheUtil, LDAPImportUtil, LDAPSyncUtil,
@@ -47,6 +48,10 @@ class LDAPTestingConfigAPI(APIView):
search_filter = serializer.validated_data["AUTH_LDAP_SEARCH_FILTER"]
attr_map = serializer.validated_data["AUTH_LDAP_USER_ATTR_MAP"]
auth_ldap = serializer.validated_data.get('AUTH_LDAP', False)
if not password:
password = settings.AUTH_LDAP_BIND_PASSWORD
config = {
'server_uri': server_uri,
'bind_dn': bind_dn,

View File

@@ -32,6 +32,7 @@ class SettingsApi(generics.RetrieveUpdateAPIView):
'radius': serializers.RadiusSettingSerializer,
'cas': serializers.CASSettingSerializer,
'sso': serializers.SSOSettingSerializer,
'saml2': serializers.SAML2SettingSerializer,
'clean': serializers.CleaningSerializer,
'other': serializers.OtherSettingSerializer,
'sms': serializers.SMSSettingSerializer,

View File

@@ -97,6 +97,7 @@ class Setting(models.Model):
'AUTH_OPENID': [settings.AUTH_BACKEND_OIDC_CODE, settings.AUTH_BACKEND_OIDC_PASSWORD],
'AUTH_RADIUS': [settings.AUTH_BACKEND_RADIUS],
'AUTH_CAS': [settings.AUTH_BACKEND_CAS],
'AUTH_SAML2': [settings.AUTH_BACKEND_SAML2],
}
setting_backends = backends_map[name]
auth_backends = settings.AUTHENTICATION_BACKENDS
@@ -130,6 +131,10 @@ class Setting(models.Model):
def refresh_AUTH_OPENID(cls):
cls.refresh_authentications('AUTH_OPENID')
@classmethod
def refresh_AUTH_SAML2(cls):
cls.refresh_authentications('AUTH_SAML2')
def refresh_keycloak_to_openid_if_need(self):
watch_config_names = [
'AUTH_OPENID', 'AUTH_OPENID_REALM_NAME', 'AUTH_OPENID_SERVER_URL',

View File

@@ -8,3 +8,4 @@ from .wecom import *
from .sso import *
from .base import *
from .sms import *
from .saml2 import *

View File

@@ -14,6 +14,7 @@ class AuthSettingSerializer(serializers.Serializer):
AUTH_FEISHU = serializers.BooleanField(default=False, label=_('FeiShu Auth'))
AUTH_WECOM = serializers.BooleanField(default=False, label=_('WeCom Auth'))
AUTH_SSO = serializers.BooleanField(default=False, label=_("SSO Auth"))
AUTH_SAML2 = serializers.BooleanField(default=False, label=_("SAML2 Auth"))
FORGOT_PASSWORD_URL = serializers.CharField(
required=False, allow_blank=True, max_length=1024,
label=_("Forgot password url")

View File

@@ -0,0 +1,33 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
__all__ = [
'SAML2SettingSerializer',
]
class SAML2SettingSerializer(serializers.Serializer):
AUTH_SAML2 = serializers.BooleanField(
default=False, required=False, label=_('Enable SAML2 Auth')
)
SAML2_IDP_METADATA_URL = serializers.URLField(
allow_blank=True, required=False, label=_('IDP metadata URL')
)
SAML2_IDP_METADATA_XML = serializers.CharField(
allow_blank=True, required=False, label=_('IDP metadata XML')
)
SAML2_SP_ADVANCED_SETTINGS = serializers.JSONField(
required=False, label=_('SP advanced settings')
)
SAML2_SP_KEY_CONTENT = serializers.CharField(
allow_blank=True, required=False,
write_only=True, label=_('SP private key')
)
SAML2_SP_CERT_CONTENT = serializers.CharField(
allow_blank=True, required=False,
write_only=True, label=_('SP cert')
)
SAML2_RENAME_ATTRIBUTES = serializers.DictField(required=False, label=_('Rename attr'))
SAML2_LOGOUT_COMPLETELY = serializers.BooleanField(required=False, label=_('Logout completely'))
AUTH_SAML2_ALWAYS_UPDATE_USER = serializers.BooleanField(required=False, label=_('Always update user'))

View File

@@ -44,3 +44,10 @@ class BasicSettingSerializer(serializers.Serializer):
TICKETS_ENABLED = serializers.BooleanField(required=False, default=True, label=_("Enable tickets"))
ANNOUNCEMENT_ENABLED = serializers.BooleanField(label=_('Enable announcement'), default=True)
ANNOUNCEMENT = AnnouncementSerializer(label=_("Announcement"))
@staticmethod
def validate_SITE_URL(s):
if not s:
return 'http://127.0.0.1'
return s.strip('/')

View File

@@ -11,7 +11,6 @@ from jumpserver.utils import current_request
from common.decorator import on_transaction_commit
from common.utils import get_logger, ssh_key_gen
from common.utils.connection import RedisPubSub
from common.db.utils import close_old_connections
from common.signals import django_ready
from .models import Setting
@@ -81,23 +80,9 @@ def subscribe_settings_change(sender, **kwargs):
logger.debug("Start subscribe setting change")
def keep_subscribe_settings_change():
while True:
try:
sub = setting_pub_sub.subscribe()
msgs = sub.listen()
# 开始之前关闭连接因为server端可能关闭了连接而 client 还在 CONN_MAX_AGE 中
for msg in msgs:
if msg["type"] != "message":
continue
close_old_connections()
item = msg['data'].decode()
logger.debug("Found setting change: {}".format(str(item)))
Setting.refresh_item(item)
close_old_connections()
except Exception as e:
logger.exception(f'subscribe_settings_change: {e}')
Setting.refresh_all_settings()
close_old_connections()
setting_pub_sub.keep_handle_msg(
lambda name: Setting.refresh_item(name)
)
t = threading.Thread(target=keep_subscribe_settings_change)
t.daemon = True

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

View File

@@ -1,7 +1,7 @@
{% load i18n %}
<div class="footer fixed">
<div class="pull-right">
Version <strong>{{ VERSION }}-{% include '_build.html' %}</strong> GPLv2.
Version <strong>{{ VERSION }}-{% include '_build.html' %}</strong> GPLv3.
<!--<img style="display: none" src="http://www.jumpserver.org/img/evaluate_avatar1.jpg">-->
</div>
<div>

View File

@@ -35,6 +35,16 @@ p {
<li><a href="/download/Microsoft_Remote_Desktop_10.6.7_installer.pkg">Microsoft_Remote_Desktop_10.6.7_installer.pkg</a></li>
</ul>
</div>
{% if XPACK_ENABLED %}
<div class="group">
<h2>{% trans 'Windows Remote application publisher tools' %}</h2>
<p>{% trans 'Jmservisor is the program used to pull up remote applications in Windows Remote Application publisher' %}</p>
<ul>
<li><a href="/download/Jmservisor.msi">Jmservisor</a></li>
</ul>
</div>
{% endif %}
</div>
<style>
ul {

View File

@@ -121,8 +121,11 @@ class CommandViewSet(JMSBulkModelViewSet):
qs = storage.get_command_queryset()
commands = self.filter_queryset(qs)
merged_commands.extend(commands[:]) # ES 默认只取 10 条数据
merged_commands.sort(key=lambda command: command.timestamp, reverse=True)
order = self.request.query_params.get('order', None)
if order == 'timestamp':
merged_commands.sort(key=lambda command: command.timestamp)
else:
merged_commands.sort(key=lambda command: command.timestamp, reverse=True)
page = self.paginate_queryset(merged_commands)
if page is not None:
serializer = self.get_serializer(page, many=True)

View File

@@ -28,7 +28,6 @@ from ..hands import SystemUser
from ..models import Session
from .. import serializers
__all__ = [
'SessionViewSet', 'SessionReplayViewSet', 'SessionJoinValidateAPI'
]
@@ -41,7 +40,7 @@ class SessionViewSet(OrgBulkModelViewSet):
'default': serializers.SessionSerializer,
'display': serializers.SessionDisplaySerializer,
}
permission_classes = (IsOrgAdminOrAppUser, )
permission_classes = (IsOrgAdminOrAppUser,)
search_fields = [
"user", "asset", "system_user", "remote_addr", "protocol", "is_finished", 'login_from',
]
@@ -71,7 +70,8 @@ class SessionViewSet(OrgBulkModelViewSet):
os.chdir(current_dir)
return file
@action(methods=[GET], detail=True, renderer_classes=(PassthroughRenderer,), url_path='replay/download', url_name='replay-download')
@action(methods=[GET], detail=True, renderer_classes=(PassthroughRenderer,), url_path='replay/download',
url_name='replay-download')
def download(self, request, *args, **kwargs):
session = self.get_object()
local_path, url = utils.get_session_replay_url(session)
@@ -102,7 +102,7 @@ class SessionViewSet(OrgBulkModelViewSet):
def get_permissions(self):
if self.request.method.lower() in ['get', 'options']:
self.permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor, )
self.permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor,)
return super().get_permissions()
@@ -119,7 +119,9 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
if serializer.is_valid():
file = serializer.validated_data['file']
name, err = session.save_replay_to_storage(file)
# 兼容旧版本 API 未指定 version 为 2 的情况
version = serializer.validated_data.get('version', 2)
name, err = session.save_replay_to_storage_with_version(file, version)
if not name:
msg = "Failed save replay `{}`: {}".format(session_id, err)
logger.error(msg)
@@ -137,6 +139,8 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
if session.protocol in ('rdp', 'vnc'):
# 需要考虑录像播放和离线播放器的约定,暂时不处理
tp = 'guacamole'
if url.endswith('.cast.gz'):
tp = 'asciicast'
download_url = reverse('api-terminal:session-replay-download', kwargs={'pk': session.id})
data = {
@@ -168,7 +172,7 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
class SessionJoinValidateAPI(views.APIView):
permission_classes = (IsAppUser, )
permission_classes = (IsAppUser,)
serializer_class = serializers.SessionJoinValidateSerializer
def post(self, request, *args, **kwargs):

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.1.12 on 2021-11-05 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('terminal', '0040_sessionjoinrecord_sessionsharing'),
]
operations = [
migrations.AlterField(
model_name='session',
name='protocol',
field=models.CharField(choices=[('ssh', 'ssh'), ('rdp', 'rdp'), ('vnc', 'vnc'), ('telnet', 'telnet'), ('mysql', 'mysql'), ('oracle', 'oracle'), ('mariadb', 'mariadb'), ('sqlserver', 'sqlserver'), ('postgresql', 'postgresql'), ('k8s', 'kubernetes')], db_index=True, default='ssh', max_length=16),
),
]

View File

@@ -31,6 +31,7 @@ class Session(OrgModelMixin):
MYSQL = 'mysql', 'mysql'
ORACLE = 'oracle', 'oracle'
MARIADB = 'mariadb', 'mariadb'
SQLSERVER = 'sqlserver', 'sqlserver'
POSTGRESQL = 'postgresql', 'postgresql'
K8S = 'k8s', 'kubernetes'
@@ -55,26 +56,65 @@ class Session(OrgModelMixin):
upload_to = 'replay'
ACTIVE_CACHE_KEY_PREFIX = 'SESSION_ACTIVE_{}'
_DATE_START_FIRST_HAS_REPLAY_RDP_SESSION = None
SUFFIX_MAP = {1: '.gz', 2: '.replay.gz', 3: '.cast.gz'}
DEFAULT_SUFFIXES = ['.replay.gz', '.cast.gz', '.gz']
def get_rel_replay_path(self, version=2):
# Todo: 将来干掉 local_path, 使用 default storage 实现
def get_all_possible_local_path(self):
"""
获取session日志的文件路径
:param version: 原来后缀是 .gz为了统一新版本改为 .replay.gz
获取所有可能的本地存储录像文件路径
:return:
"""
return [self.get_local_storage_path_by_suffix(suffix)
for suffix in self.SUFFIX_MAP.values()]
def get_all_possible_relative_path(self):
"""
获取所有可能的外部存储录像文件路径
:return:
"""
return [self.get_relative_path_by_suffix(suffix)
for suffix in self.SUFFIX_MAP.values()]
def get_local_storage_path_by_suffix(self, suffix='.cast.gz'):
"""
local_path: replay/2021-12-08/session_id.cast.gz
通过后缀名获取本地存储的录像文件路径
:param suffix: .cast.gz | '.replay.gz' | '.gz'
:return:
"""
rel_path = self.get_relative_path_by_suffix(suffix)
if suffix == '.gz':
# 兼容 v1 的版本
return rel_path
return os.path.join(self.upload_to, rel_path)
def get_relative_path_by_suffix(self, suffix='.cast.gz'):
"""
relative_path: 2021-12-08/session_id.cast.gz
通过后缀名获取外部存储录像文件路径
:param suffix: .cast.gz | '.replay.gz' | '.gz'
:return:
"""
suffix = '.replay.gz'
if version == 1:
suffix = '.gz'
date = self.date_start.strftime('%Y-%m-%d')
return os.path.join(date, str(self.id) + suffix)
def get_local_path(self, version=2):
rel_path = self.get_rel_replay_path(version=version)
if version == 2:
local_path = os.path.join(self.upload_to, rel_path)
else:
local_path = rel_path
return local_path
def get_local_path_by_relative_path(self, rel_path):
"""
2021-12-08/session_id.cast.gz
:param rel_path:
:return: replay/2021-12-08/session_id.cast.gz
"""
return '{}/{}'.format(self.upload_to, rel_path)
def get_relative_path_by_local_path(self, local_path):
return local_path.replace('{}/'.format(self.upload_to), '')
def find_ok_relative_path_in_storage(self, storage):
session_paths = self.get_all_possible_relative_path()
for rel_path in session_paths:
if storage.exists(rel_path):
return rel_path
@property
def asset_obj(self):
@@ -122,7 +162,7 @@ class Session(OrgModelMixin):
@property
def db_protocols(self):
_PROTOCOL = self.PROTOCOL
return [_PROTOCOL.MYSQL, _PROTOCOL.MARIADB, _PROTOCOL.ORACLE, _PROTOCOL.POSTGRESQL]
return [_PROTOCOL.MYSQL, _PROTOCOL.MARIADB, _PROTOCOL.ORACLE, _PROTOCOL.POSTGRESQL, _PROTOCOL.SQLSERVER]
@property
def can_terminate(self):
@@ -132,8 +172,9 @@ class Session(OrgModelMixin):
else:
return True
def save_replay_to_storage(self, f):
local_path = self.get_local_path()
def save_replay_to_storage_with_version(self, f, version=2):
suffix = self.SUFFIX_MAP.get(version, '.cast.gz')
local_path = self.get_local_storage_path_by_suffix(suffix)
try:
name = default_storage.save(local_path, f)
except OSError as e:
@@ -147,7 +188,7 @@ class Session(OrgModelMixin):
@classmethod
def set_sessions_active(cls, session_ids):
data = {cls.ACTIVE_CACHE_KEY_PREFIX.format(i): i for i in session_ids}
cache.set_many(data, timeout=5*60)
cache.set_many(data, timeout=5 * 60)
@classmethod
def get_active_sessions(cls):
@@ -194,7 +235,7 @@ class Session(OrgModelMixin):
for user, asset, system_user in ziped:
ip = random_ip()
date_start = random_datetime(month_ago, now)
date_end = random_datetime(date_start, date_start+timezone.timedelta(hours=2))
date_end = random_datetime(date_start, date_start + timezone.timedelta(hours=2))
data = dict(
user=str(user), user_id=user.id,
asset=str(asset), asset_id=asset.id,

View File

@@ -50,6 +50,7 @@ class SessionDisplaySerializer(SessionSerializer):
class ReplaySerializer(serializers.Serializer):
file = serializers.FileField(allow_empty_file=True)
version = serializers.IntegerField(write_only=True, required=False, min_value=2, max_value=3)
class SessionJoinValidateSerializer(serializers.Serializer):

View File

@@ -85,7 +85,7 @@ def upload_session_replay_to_external_storage(session_id):
logger.error(f'Session replay not found, may be upload error: {local_path}')
return
abs_path = default_storage.path(local_path)
remote_path = session.get_rel_replay_path()
remote_path = session.get_relative_path_by_local_path(abs_path)
ok, err = server_replay_storage.upload(abs_path, remote_path)
if not ok:
logger.error(f'Session replay upload to external error: {err}')

View File

@@ -1,30 +1,28 @@
# -*- coding: utf-8 -*-
#
import os
from itertools import groupby
from itertools import groupby, chain
from django.conf import settings
from django.core.files.storage import default_storage
from django.utils.translation import ugettext as _
import jms_storage
from common.tasks import send_mail_async
from common.utils import get_logger, reverse
from common.utils import get_logger
from . import const
from .models import ReplayStorage, Session, Command
from .models import ReplayStorage
logger = get_logger(__name__)
def find_session_replay_local(session):
# 新版本和老版本的文件后缀不同
session_path = session.get_rel_replay_path() # 存在外部存储上的路径
local_path = session.get_local_path()
local_path_v1 = session.get_local_path(version=1)
# 存在外部存储上,所有可能的路径名
session_paths = session.get_all_possible_relative_path()
# 去default storage中查找
for _local_path in (local_path, local_path_v1, session_path):
# 存在本地存储上,所有可能的路径名
local_paths = session.get_all_possible_local_path()
for _local_path in chain(session_paths, local_paths):
if default_storage.exists(_local_path):
url = default_storage.url(_local_path)
return _local_path, url
@@ -32,8 +30,6 @@ def find_session_replay_local(session):
def download_session_replay(session):
session_path = session.get_rel_replay_path() # 存在外部存储上的路径
local_path = session.get_local_path()
replay_storages = ReplayStorage.objects.all()
configs = {
storage.name: storage.config
@@ -45,13 +41,23 @@ def download_session_replay(session):
if not configs:
msg = "Not found replay file, and not remote storage set"
return None, msg
storage = jms_storage.get_multi_object_storage(configs)
# 获取外部存储路径名
session_path = session.find_ok_relative_path_in_storage(storage)
if not session_path:
msg = "Not found session replay file"
return None, msg
# 通过外部存储路径名后缀,构造真实的本地存储路径
local_path = session.get_local_path_by_relative_path(session_path)
# 保存到storage的路径
target_path = os.path.join(default_storage.base_location, local_path)
target_dir = os.path.dirname(target_path)
if not os.path.isdir(target_dir):
os.makedirs(target_dir, exist_ok=True)
storage = jms_storage.get_multi_object_storage(configs)
ok, err = storage.download(session_path, target_path)
if not ok:
msg = "Failed download replay file: {}".format(err)

View File

@@ -10,7 +10,7 @@ class TicketFilter(BaseFilterSet):
class Meta:
model = Ticket
fields = (
'id', 'title', 'type', 'status', 'applicant', 'assignees__id',
'id', 'title', 'type', 'status', 'state', 'applicant', 'assignees__id',
'applicant_display',
)

View File

@@ -1,4 +1,5 @@
from django.utils.translation import ugettext as _
from orgs.utils import tmp_to_org, tmp_to_root_org
from applications.const import AppCategory, AppType
from applications.models import Application

View File

@@ -1,11 +1,9 @@
from assets.models import Asset
from assets.models import SystemUser
from .base import BaseHandler
from django.utils.translation import ugettext as _
from assets.models import Node, Asset, SystemUser
from perms.models import AssetPermission, Action
from orgs.utils import tmp_to_org, tmp_to_root_org
from .base import BaseHandler
class Handler(BaseHandler):
@@ -22,17 +20,22 @@ class Handler(BaseHandler):
apply_actions_display = Action.value_to_choices_display(apply_actions)
meta_display_values = [apply_actions_display]
meta_display = dict(zip(meta_display_fields, meta_display_values))
apply_assets = self.ticket.meta.get('apply_assets')
apply_nodes = self.ticket.meta.get('apply_nodes', [])
apply_assets = self.ticket.meta.get('apply_assets', [])
apply_system_users = self.ticket.meta.get('apply_system_users')
with tmp_to_org(self.ticket.org_id):
meta_display.update({
'apply_nodes_display': [str(i) for i in Node.objects.filter(id__in=apply_nodes)],
'apply_assets_display': [str(i) for i in Asset.objects.filter(id__in=apply_assets)],
'apply_system_users_display': [str(i)for i in SystemUser.objects.filter(id__in=apply_system_users)]
'apply_system_users_display': [
str(i) for i in SystemUser.objects.filter(id__in=apply_system_users)
]
})
return meta_display
# body
def _construct_meta_body_of_open(self):
apply_nodes = self.ticket.meta.get('apply_nodes_display', [])
apply_assets = self.ticket.meta.get('apply_assets_display', [])
apply_system_users = self.ticket.meta.get('apply_system_users_display', [])
apply_actions_display = self.ticket.meta.get('apply_actions_display', [])
@@ -44,6 +47,7 @@ class Handler(BaseHandler):
{}: {},
{}: {}
'''.format(
_("Applied node group"), ','.join(apply_nodes),
_("Applied hostname group"), ','.join(apply_assets),
_("Applied system user group"), ','.join(apply_system_users),
_("Applied actions"), ','.join(apply_actions_display),
@@ -60,6 +64,7 @@ class Handler(BaseHandler):
return asset_permission
apply_permission_name = self.ticket.meta.get('apply_permission_name', )
apply_nodes = self.ticket.meta.get('apply_nodes', [])
apply_assets = self.ticket.meta.get('apply_assets', [])
apply_system_users = self.ticket.meta.get('apply_system_users', [])
apply_actions = self.ticket.meta.get('apply_actions', Action.NONE)
@@ -94,6 +99,7 @@ class Handler(BaseHandler):
with tmp_to_org(self.ticket.org_id):
asset_permission = AssetPermission.objects.create(**permission_data)
asset_permission.users.add(self.ticket.applicant)
asset_permission.nodes.set(apply_nodes)
asset_permission.assets.set(apply_assets)
asset_permission.system_users.set(apply_system_users)

View File

@@ -29,9 +29,9 @@ class BaseHandler(object):
self._send_applied_mail_to_assignees()
is_finished = False
else:
self._send_processed_mail_to_applicant(self.ticket.processor)
self.ticket.set_state_approve()
self.ticket.set_status_closed()
self._send_processed_mail_to_applicant(self.ticket.processor)
is_finished = True
self.ticket.save()

View File

@@ -7,7 +7,7 @@ from common.mixins.models import CommonModelMixin
from common.db.encoder import ModelJSONFieldEncoder
from orgs.mixins.models import OrgModelMixin
from orgs.models import Organization
from orgs.utils import tmp_to_root_org
from orgs.utils import tmp_to_root_org, tmp_to_org
from ..const import TicketType, TicketApprovalLevel, TicketApprovalStrategy
from ..signals import post_or_update_change_ticket_flow_approval
@@ -64,9 +64,13 @@ class TicketFlow(CommonModelMixin, OrgModelMixin):
return '{}'.format(self.type)
@classmethod
def get_org_related_flows(cls):
flows = cls.objects.all()
def get_org_related_flows(cls, org_id=None):
if org_id:
with tmp_to_org(org_id):
flows = cls.objects.all()
else:
flows = cls.objects.all()
cur_flow_types = flows.values_list('type', flat=True)
with tmp_to_root_org():
diff_global_flows = cls.objects.exclude(type__in=cur_flow_types).filter(org_id=Organization.ROOT_ID)
diff_global_flows = cls.objects.exclude(type__in=cur_flow_types)
return flows | diff_global_flows

View File

@@ -1,13 +1,11 @@
from datetime import datetime
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from perms.models import ApplicationPermission
from applications.const import AppCategory, AppType
from orgs.utils import tmp_to_org
from tickets.models import Ticket
from applications.models import Application
from assets.models import SystemUser
from .common import DefaultPermissionName
__all__ = [

View File

@@ -1,7 +1,6 @@
from datetime import datetime
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from perms.serializers import ActionsField
from perms.models import AssetPermission
from orgs.utils import tmp_to_org
@@ -12,23 +11,34 @@ __all__ = [
'ApplySerializer',
]
asset_or_node_help_text = _("Select at least one asset or node")
class ApplySerializer(serializers.Serializer):
apply_permission_name = serializers.CharField(
max_length=128, default=DefaultPermissionName(), label=_('Apply name')
)
apply_nodes = serializers.ListField(
required=False, allow_null=True, child=serializers.UUIDField(),
label=_('Apply nodes'), help_text=asset_or_node_help_text,
default=list
)
apply_nodes_display = serializers.ListField(
child=serializers.CharField(), label=_('Apply nodes display'), required=False
)
# 申请信息
apply_assets = serializers.ListField(
required=True, allow_null=True, child=serializers.UUIDField(), label=_('Apply assets')
required=False, allow_null=True, child=serializers.UUIDField(),
label=_('Apply assets'), help_text=asset_or_node_help_text
)
apply_assets_display = serializers.ListField(
required=False, read_only=True, child=serializers.CharField(),
label=_('Approve assets display'), allow_null=True,
default=list,
label=_('Apply assets display'), allow_null=True,
default=list
)
apply_system_users = serializers.ListField(
required=True, allow_null=True, child=serializers.UUIDField(),
label=_('Approve system users')
label=_('Apply system users')
)
apply_system_users_display = serializers.ListField(
required=False, read_only=True, child=serializers.CharField(),
@@ -64,6 +74,12 @@ class ApplySerializer(serializers.Serializer):
))
def validate(self, attrs):
if not attrs.get('apply_nodes') and not attrs.get('apply_assets'):
raise serializers.ValidationError({
'apply_nodes': asset_or_node_help_text,
'apply_assets': asset_or_node_help_text,
})
apply_date_start = attrs['apply_date_start'].strftime('%Y-%m-%d %H:%M:%S')
apply_date_expired = attrs['apply_date_expired'].strftime('%Y-%m-%d %H:%M:%S')

Some files were not shown because too many files have changed in this diff Show More