mirror of https://github.com/jumpserver/jumpserver
commit
5f7fa7e02f
|
@ -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。
|
|
@ -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: '状态:待处理,状态:待反馈'
|
|
@ -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: '状态:待处理'
|
|
@ -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: '状态:待处理'
|
|
@ -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 }}
|
|
@ -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 }}
|
|
@ -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
|
COPY --from=stage-build /opt/jumpserver/release/jumpserver /opt/jumpserver
|
||||||
RUN mkdir -p /root/.ssh/ \
|
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/ \
|
RUN mkdir -p /opt/jumpserver/oracle/ \
|
||||||
&& wget https://download.jumpserver.org/public/instantclient-basiclite-linux.x64-21.1.0.0.0.tar > /dev/null \
|
&& wget https://download.jumpserver.org/public/instantclient-basiclite-linux.x64-21.1.0.0.0.tar > /dev/null \
|
||||||
|
|
837
LICENSE
837
LICENSE
|
@ -1,281 +1,622 @@
|
||||||
GNU GENERAL PUBLIC LICENSE
|
GNU GENERAL PUBLIC LICENSE
|
||||||
Version 2, June 1991
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
of this license document, but changing it is not allowed.
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Preamble
|
Preamble
|
||||||
|
|
||||||
The licenses for most software are designed to take away your
|
The GNU General Public License is a free, copyleft license for
|
||||||
freedom to share and change it. By contrast, the GNU General Public
|
software and other kinds of works.
|
||||||
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
|
The licenses for most software and other practical works are designed
|
||||||
General Public License applies to most of the Free Software
|
to take away your freedom to share and change the works. By contrast,
|
||||||
Foundation's software and to any other program whose authors commit to
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
using it. (Some other Free Software Foundation software is covered by
|
share and change all versions of a program--to make sure it remains free
|
||||||
the GNU Lesser General Public License instead.) You can apply it to
|
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.
|
your programs, too.
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
When we speak of free software, we are referring to freedom, not
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
have the freedom to distribute copies of free software (and charge for
|
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
|
them if you wish), that you receive source code or can get it if you
|
||||||
if you want it, that you can change the software or use pieces of it
|
want it, that you can change the software or use pieces of it in new
|
||||||
in new free programs; and that you know you can do these things.
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
To protect your rights, we need to make restrictions that forbid
|
To protect your rights, we need to prevent others from denying you
|
||||||
anyone to deny you these rights or to ask you to surrender the rights.
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
These restrictions translate to certain responsibilities for you if you
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
distribute copies of the software, or if you modify it.
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether
|
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
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
you have. You must make sure that they, too, receive or can get the
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
source code. And you must show them these terms so they know their
|
or can get the source code. And you must show them these terms so they
|
||||||
rights.
|
know their rights.
|
||||||
|
|
||||||
We protect your rights with two steps: (1) copyright the software, and
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
(2) offer you this license which gives you legal permission to copy,
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
distribute and/or modify the software.
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
Also, for each author's protection and ours, we want to make certain
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
that everyone understands that there is no warranty for this free
|
that there is no warranty for this free software. For both users' and
|
||||||
software. If the software is modified by someone else and passed on, we
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
want its recipients to know that what they have is not the original, so
|
changed, so that their problems will not be attributed erroneously to
|
||||||
that any problems introduced by others will not reflect on the original
|
authors of previous versions.
|
||||||
authors' reputations.
|
|
||||||
|
|
||||||
Finally, any free program is threatened constantly by software
|
Some devices are designed to deny users access to install or run
|
||||||
patents. We wish to avoid the danger that redistributors of a free
|
modified versions of the software inside them, although the manufacturer
|
||||||
program will individually obtain patent licenses, in effect making the
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
program proprietary. To prevent this, we have made it clear that any
|
protecting users' freedom to change the software. The systematic
|
||||||
patent must be licensed for everyone's free use or not licensed at all.
|
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
|
The precise terms and conditions for copying, distribution and
|
||||||
modification follow.
|
modification follow.
|
||||||
|
|
||||||
GNU GENERAL PUBLIC LICENSE
|
TERMS AND CONDITIONS
|
||||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
|
||||||
|
|
||||||
0. This License applies to any program or other work which contains
|
0. Definitions.
|
||||||
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".
|
|
||||||
|
|
||||||
Activities other than copying, distribution and modification are not
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
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.
|
|
||||||
|
|
||||||
1. You may copy and distribute verbatim copies of the Program's
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
source code as you receive it, in any medium, provided that you
|
works, such as semiconductor masks.
|
||||||
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.
|
|
||||||
|
|
||||||
You may charge a fee for the physical act of transferring a copy, and
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
you may at your option offer warranty protection in exchange for a fee.
|
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
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
of it, thus forming a work based on the Program, and copy and
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
distribute such modifications or work under the terms of Section 1
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
above, provided that you also meet all of these conditions:
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
a) You must cause the modified files to carry prominent notices
|
A "covered work" means either the unmodified Program or a work based
|
||||||
stating that you changed the files and the date of any change.
|
on the Program.
|
||||||
|
|
||||||
b) You must cause any work that you distribute or publish, that in
|
To "propagate" a work means to do anything with it that, without
|
||||||
whole or in part contains or is derived from the Program or any
|
permission, would make you directly or secondarily liable for
|
||||||
part thereof, to be licensed as a whole at no charge to all third
|
infringement under applicable copyright law, except executing it on a
|
||||||
parties under the terms of this License.
|
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
|
To "convey" a work means any kind of propagation that enables other
|
||||||
when run, you must cause it, when started running for such
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
interactive use in the most ordinary way, to print or display an
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
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.)
|
|
||||||
|
|
||||||
These requirements apply to the modified work as a whole. If
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
identifiable sections of that work are not derived from the Program,
|
to the extent that it includes a convenient and prominently visible
|
||||||
and can be reasonably considered independent and separate works in
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
themselves, then this License, and its terms, do not apply to those
|
tells the user that there is no warranty for the work (except to the
|
||||||
sections when you distribute them as separate works. But when you
|
extent that warranties are provided), that licensees may convey the
|
||||||
distribute the same sections as part of a whole which is a work based
|
work under this License, and how to view a copy of this License. If
|
||||||
on the Program, the distribution of the whole must be on the terms of
|
the interface presents a list of user commands or options, such as a
|
||||||
this License, whose permissions for other licensees extend to the
|
menu, a prominent item in the list meets this criterion.
|
||||||
entire whole, and thus to each and every part regardless of who wrote it.
|
|
||||||
|
|
||||||
Thus, it is not the intent of this section to claim rights or contest
|
1. Source Code.
|
||||||
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.
|
|
||||||
|
|
||||||
In addition, mere aggregation of another work not based on the Program
|
The "source code" for a work means the preferred form of the work
|
||||||
with the Program (or with a work based on the Program) on a volume of
|
for making modifications to it. "Object code" means any non-source
|
||||||
a storage or distribution medium does not bring the other work under
|
form of a work.
|
||||||
the scope of this License.
|
|
||||||
|
|
||||||
3. You may copy and distribute the Program (or a work based on it,
|
A "Standard Interface" means an interface that either is an official
|
||||||
under Section 2) in object code or executable form under the terms of
|
standard defined by a recognized standards body, or, in the case of
|
||||||
Sections 1 and 2 above provided that you also do one of the following:
|
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
|
The "System Libraries" of an executable work include anything, other
|
||||||
source code, which must be distributed under the terms of Sections
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
1 and 2 above on a medium customarily used for software interchange; or,
|
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
|
The "Corresponding Source" for a work in object code form means all
|
||||||
years, to give any third party, for a charge no more than your
|
the source code needed to generate, install, and (for an executable
|
||||||
cost of physically performing source distribution, a complete
|
work) run the object code and to modify the work, including scripts to
|
||||||
machine-readable copy of the corresponding source code, to be
|
control those activities. However, it does not include the work's
|
||||||
distributed under the terms of Sections 1 and 2 above on a medium
|
System Libraries, or general-purpose tools or generally available free
|
||||||
customarily used for software interchange; or,
|
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
|
The Corresponding Source need not include anything that users
|
||||||
to distribute corresponding source code. (This alternative is
|
can regenerate automatically from other parts of the Corresponding
|
||||||
allowed only for noncommercial distribution and only if you
|
Source.
|
||||||
received the program in object code or executable form with such
|
|
||||||
an offer, in accord with Subsection b above.)
|
|
||||||
|
|
||||||
The source code for a work means the preferred form of the work for
|
The Corresponding Source for a work in source code form is that
|
||||||
making modifications to it. For an executable work, complete source
|
same work.
|
||||||
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.
|
|
||||||
|
|
||||||
If distribution of executable or object code is made by offering
|
2. Basic Permissions.
|
||||||
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.
|
|
||||||
|
|
||||||
4. You may not copy, modify, sublicense, or distribute the Program
|
All rights granted under this License are granted for the term of
|
||||||
except as expressly provided under this License. Any attempt
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
otherwise to copy, modify, sublicense or distribute the Program is
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
void, and will automatically terminate your rights under this License.
|
permission to run the unmodified Program. The output from running a
|
||||||
However, parties who have received copies, or rights, from you under
|
covered work is covered by this License only if the output, given its
|
||||||
this License will not have their licenses terminated so long as such
|
content, constitutes a covered work. This License acknowledges your
|
||||||
parties remain in full compliance.
|
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
|
You may make, run and propagate covered works that you do not
|
||||||
signed it. However, nothing else grants you permission to modify or
|
convey, without conditions so long as your license otherwise remains
|
||||||
distribute the Program or its derivative works. These actions are
|
in force. You may convey covered works to others for the sole purpose
|
||||||
prohibited by law if you do not accept this License. Therefore, by
|
of having them make modifications exclusively for you, or provide you
|
||||||
modifying or distributing the Program (or any work based on the
|
with facilities for running those works, provided that you comply with
|
||||||
Program), you indicate your acceptance of this License to do so, and
|
the terms of this License in conveying all material for which you do
|
||||||
all its terms and conditions for copying, distributing or modifying
|
not control copyright. Those thus making or running the covered works
|
||||||
the Program or works based on it.
|
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
|
Conveying under any other circumstances is permitted solely under
|
||||||
Program), the recipient automatically receives a license from the
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
original licensor to copy, distribute or modify the Program subject to
|
makes it unnecessary.
|
||||||
these terms and conditions. You may not impose any further
|
|
||||||
restrictions on the recipients' exercise of the rights granted herein.
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
You are not responsible for enforcing compliance by third parties to
|
|
||||||
|
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.
|
this License.
|
||||||
|
|
||||||
7. If, as a consequence of a court judgment or allegation of patent
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
infringement or for any other reason (not limited to patent issues),
|
patent license under the contributor's essential patent claims, to
|
||||||
conditions are imposed on you (whether by court order, agreement or
|
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
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
excuse you from the conditions of this License. If you cannot
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
distribute so as to satisfy simultaneously your obligations under this
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
License and any other pertinent obligations, then as a consequence you
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
may not distribute the Program at all. For example, if a patent
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
license would not permit royalty-free redistribution of the Program by
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
all those who receive copies directly or indirectly through you, then
|
the Program, the only way you could satisfy both those terms and this
|
||||||
the only way you could satisfy both it and this License would be to
|
License would be to refrain entirely from conveying the Program.
|
||||||
refrain entirely from distribution of the Program.
|
|
||||||
|
|
||||||
If any portion of this section is held invalid or unenforceable under
|
13. Use with the GNU Affero General Public License.
|
||||||
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.
|
|
||||||
|
|
||||||
It is not the purpose of this section to induce you to infringe any
|
Notwithstanding any other provision of this License, you have
|
||||||
patents or other property right claims or to contest validity of any
|
permission to link or combine any covered work with a work licensed
|
||||||
such claims; this section has the sole purpose of protecting the
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
integrity of the free software distribution system, which is
|
combined work, and to convey the resulting work. The terms of this
|
||||||
implemented by public license practices. Many people have made
|
License will continue to apply to the part which is the covered work,
|
||||||
generous contributions to the wide range of software distributed
|
but the special requirements of the GNU Affero General Public License,
|
||||||
through that system in reliance on consistent application of that
|
section 13, concerning interaction through a network will apply to the
|
||||||
system; it is up to the author/donor to decide if he or she is willing
|
combination as such.
|
||||||
to distribute software through any other system and a licensee cannot
|
|
||||||
impose that choice.
|
|
||||||
|
|
||||||
This section is intended to make thoroughly clear what is believed to
|
14. Revised Versions of this License.
|
||||||
be a consequence of the rest of this License.
|
|
||||||
|
|
||||||
8. If the distribution and/or use of the Program is restricted in
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
certain countries either by patents or by copyrighted interfaces, the
|
the GNU General Public License from time to time. Such new versions will
|
||||||
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
|
|
||||||
be similar in spirit to the present version, but may differ in detail to
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
address new problems or concerns.
|
address new problems or concerns.
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Program
|
Each version is given a distinguishing version number. If the
|
||||||
specifies a version number of this License which applies to it and "any
|
Program specifies that a certain numbered version of the GNU General
|
||||||
later version", you have the option of following the terms and conditions
|
Public License "or any later version" applies to it, you have the
|
||||||
either of that version or of any later version published by the Free
|
option of following the terms and conditions either of that numbered
|
||||||
Software Foundation. If the Program does not specify a version number of
|
version or of any later version published by the Free Software
|
||||||
this License, you may choose any version ever published by the Free Software
|
Foundation. If the Program does not specify a version number of the
|
||||||
Foundation.
|
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
|
If the Program specifies that a proxy can decide which future
|
||||||
programs whose distribution conditions are different, write to the author
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
to ask for permission. For software which is copyrighted by the Free
|
public statement of acceptance of a version permanently authorizes you
|
||||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
to choose that version for the Program.
|
||||||
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.
|
|
||||||
|
|
||||||
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
|
15. Disclaimer of 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.
|
|
||||||
|
|
||||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
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
|
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 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
|
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.
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
{description}
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) {year} {fullname}
|
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
|
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.
|
(at your option) any later version.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
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
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
GNU General Public License for more details.
|
GNU General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License along
|
You should have received a copy of the GNU General Public License
|
||||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
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
|
If the program does terminal interaction, make it output a short
|
||||||
when it starts in an interactive mode:
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
Gnomovision version 69, Copyright (C) year name of author
|
<program> Copyright (C) <year> <name of author>
|
||||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
This is free software, and you are welcome to redistribute it
|
This is free software, and you are welcome to redistribute it
|
||||||
under certain conditions; type `show c' for details.
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
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
|
parts of the General Public License. Of course, your program's commands
|
||||||
be called something other than `show w' and `show c'; they could even be
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
mouse-clicks or menu items--whatever suits your program.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or your
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
necessary. Here is a sample; alter the names:
|
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
|
The GNU General Public License does not permit incorporating your program
|
||||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
{signature of Ty Coon}, 1 April 1989
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
Ty Coon, President of Vice
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
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.
|
|
|
@ -2,7 +2,7 @@
|
||||||
<h3 align="center">多云环境下更好用的堡垒机</h3>
|
<h3 align="center">多云环境下更好用的堡垒机</h3>
|
||||||
|
|
||||||
<p align="center">
|
<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://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://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>
|
<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 方案,交互界面美观、用户体验好。
|
JumpServer 使用 Python 开发,遵循 Web 2.0 规范,配备了业界领先的 Web Terminal 方案,交互界面美观、用户体验好。
|
||||||
|
|
||||||
|
@ -126,9 +126,9 @@ JumpServer是一款安全产品,请参考 [基本安全建议](https://docs.ju
|
||||||
|
|
||||||
Copyright (c) 2014-2021 飞致云 FIT2CLOUD, All rights reserved.
|
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.
|
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.
|
||||||
|
|
||||||
|
|
11
README_EN.md
11
README_EN.md
|
@ -2,13 +2,13 @@
|
||||||
<h3 align="center">Open Source Bastion Host</h3>
|
<h3 align="center">Open Source Bastion Host</h3>
|
||||||
|
|
||||||
<p align="center">
|
<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://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://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>
|
<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>
|
</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
|
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
|
- 400-052-0755
|
||||||
|
|
||||||
### License & Copyright
|
### 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.
|
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.
|
||||||
|
|
||||||
|
|
|
@ -8,7 +8,7 @@ from common.utils.ip import is_ip_address, is_ip_network, is_ip_segment
|
||||||
|
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
__all__ = ['RuleSerializer']
|
__all__ = ['RuleSerializer', 'ip_group_child_validator', 'ip_group_help_text']
|
||||||
|
|
||||||
|
|
||||||
def ip_group_child_validator(ip_group_child):
|
def ip_group_child_validator(ip_group_child):
|
||||||
|
@ -21,13 +21,14 @@ def ip_group_child_validator(ip_group_child):
|
||||||
raise serializers.ValidationError(error)
|
raise serializers.ValidationError(error)
|
||||||
|
|
||||||
|
|
||||||
class RuleSerializer(serializers.Serializer):
|
ip_group_help_text = _(
|
||||||
ip_group_help_text = _(
|
'Format for comma-delimited string, with * indicating a match all. '
|
||||||
'Format for comma-delimited string, with * indicating a match all. '
|
'Such as: '
|
||||||
'Such as: '
|
'192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64 '
|
||||||
'192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64 '
|
)
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
class RuleSerializer(serializers.Serializer):
|
||||||
ip_group = serializers.ListField(
|
ip_group = serializers.ListField(
|
||||||
default=['*'], label=_('IP'), help_text=ip_group_help_text,
|
default=['*'], label=_('IP'), help_text=ip_group_help_text,
|
||||||
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator]))
|
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator]))
|
||||||
|
|
|
@ -6,7 +6,7 @@ from django.db import migrations, models
|
||||||
class Migration(migrations.Migration):
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
('applications', '0012_auto_20211014_2209'),
|
('applications', '0013_auto_20211026_1711'),
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
|
@ -147,7 +147,7 @@ class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
||||||
asset = data['asset']
|
asset = data['asset']
|
||||||
system_users = data.get('system_users')
|
system_users = data.get('system_users')
|
||||||
if not system_users:
|
if not system_users:
|
||||||
system_users = asset.get_all_systemusers()
|
system_users = asset.get_all_system_users()
|
||||||
if action == 'push_system_user':
|
if action == 'push_system_user':
|
||||||
task = push_system_users_a_asset.delay(system_users, asset=asset)
|
task = push_system_users_a_asset.delay(system_users, asset=asset)
|
||||||
elif action == 'test_system_user':
|
elif action == 'test_system_user':
|
||||||
|
|
|
@ -29,7 +29,7 @@ class CommandFilterViewSet(OrgBulkModelViewSet):
|
||||||
|
|
||||||
class CommandFilterRuleViewSet(OrgBulkModelViewSet):
|
class CommandFilterRuleViewSet(OrgBulkModelViewSet):
|
||||||
model = CommandFilterRule
|
model = CommandFilterRule
|
||||||
filterset_fields = ("content",)
|
filterset_fields = ('content',)
|
||||||
search_fields = filterset_fields
|
search_fields = filterset_fields
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdmin,)
|
||||||
serializer_class = serializers.CommandFilterRuleSerializer
|
serializer_class = serializers.CommandFilterRuleSerializer
|
||||||
|
|
|
@ -13,6 +13,7 @@ from django.db.models.signals import m2m_changed
|
||||||
from common.const.http import POST
|
from common.const.http import POST
|
||||||
from common.exceptions import SomeoneIsDoingThis
|
from common.exceptions import SomeoneIsDoingThis
|
||||||
from common.const.signals import PRE_REMOVE, POST_REMOVE
|
from common.const.signals import PRE_REMOVE, POST_REMOVE
|
||||||
|
from common.mixins.api import SuggestionMixin
|
||||||
from assets.models import Asset
|
from assets.models import Asset
|
||||||
from common.utils import get_logger, get_object_or_none
|
from common.utils import get_logger, get_object_or_none
|
||||||
from common.tree import TreeNodeSerializer
|
from common.tree import TreeNodeSerializer
|
||||||
|
@ -41,7 +42,7 @@ __all__ = [
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class NodeViewSet(OrgModelViewSet):
|
class NodeViewSet(SuggestionMixin, OrgModelViewSet):
|
||||||
model = Node
|
model = Node
|
||||||
filterset_fields = ('value', 'key', 'id')
|
filterset_fields = ('value', 'key', 'id')
|
||||||
search_fields = ('value', )
|
search_fields = ('value', )
|
||||||
|
|
|
@ -1,15 +1,18 @@
|
||||||
# ~*~ coding: utf-8 ~*~
|
# ~*~ coding: utf-8 ~*~
|
||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
from rest_framework.response import Response
|
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 common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsValidUser
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
from orgs.mixins import generics
|
from orgs.mixins import generics
|
||||||
from common.mixins.api import SuggestionMixin
|
from common.mixins.api import SuggestionMixin
|
||||||
from orgs.utils import tmp_to_root_org
|
from orgs.utils import tmp_to_root_org
|
||||||
from rest_framework.decorators import action
|
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 .. import serializers
|
||||||
from ..serializers import SystemUserWithAuthInfoSerializer, SystemUserTempAuthSerializer
|
from ..serializers import SystemUserWithAuthInfoSerializer, SystemUserTempAuthSerializer
|
||||||
from ..tasks import (
|
from ..tasks import (
|
||||||
|
@ -192,9 +195,42 @@ class SystemUserCommandFilterRuleListApi(generics.ListAPIView):
|
||||||
return CommandFilterRuleSerializer
|
return CommandFilterRuleSerializer
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
pk = self.kwargs.get('pk', None)
|
user_groups = []
|
||||||
system_user = get_object_or_404(SystemUser, pk=pk)
|
user_id = self.request.query_params.get('user_id')
|
||||||
return system_user.cmd_filter_rules
|
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_group:
|
||||||
|
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):
|
class SystemUserAssetsListView(generics.ListAPIView):
|
||||||
|
|
|
@ -6,7 +6,7 @@ from django.db import migrations, models
|
||||||
class Migration(migrations.Migration):
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
('assets', '0078_auto_20211014_2209'),
|
('assets', '0080_auto_20211104_1347'),
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
|
@ -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'),
|
||||||
|
),
|
||||||
|
]
|
|
@ -299,6 +299,12 @@ class Asset(AbsConnectivity, AbsHardwareInfo, ProtocolsMixin, NodesRelationMixin
|
||||||
names.append(n.full_value)
|
names.append(n.full_value)
|
||||||
return names
|
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):
|
def as_node(self):
|
||||||
from .node import Node
|
from .node import Node
|
||||||
fake_node = Node()
|
fake_node = Node()
|
||||||
|
@ -338,7 +344,7 @@ class Asset(AbsConnectivity, AbsHardwareInfo, ProtocolsMixin, NodesRelationMixin
|
||||||
tree_node = TreeNode(**data)
|
tree_node = TreeNode(**data)
|
||||||
return tree_node
|
return tree_node
|
||||||
|
|
||||||
def get_all_systemusers(self):
|
def get_all_system_users(self):
|
||||||
from .user import SystemUser
|
from .user import SystemUser
|
||||||
system_user_ids = SystemUser.assets.through.objects.filter(asset=self)\
|
system_user_ids = SystemUser.assets.through.objects.filter(asset=self)\
|
||||||
.values_list('systemuser_id', flat=True)
|
.values_list('systemuser_id', flat=True)
|
||||||
|
|
|
@ -7,9 +7,11 @@ from django.db import models
|
||||||
from django.core.validators import MinValueValidator, MaxValueValidator
|
from django.core.validators import MinValueValidator, MaxValueValidator
|
||||||
from django.utils.translation import ugettext_lazy as _
|
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
|
from orgs.mixins.models import OrgModelMixin
|
||||||
|
|
||||||
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'CommandFilter', 'CommandFilterRule'
|
'CommandFilter', 'CommandFilterRule'
|
||||||
|
@ -19,11 +21,32 @@ __all__ = [
|
||||||
class CommandFilter(OrgModelMixin):
|
class CommandFilter(OrgModelMixin):
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
name = models.CharField(max_length=64, verbose_name=_("Name"))
|
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'))
|
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
|
||||||
comment = models.TextField(blank=True, default='', verbose_name=_("Comment"))
|
comment = models.TextField(blank=True, default='', verbose_name=_("Comment"))
|
||||||
date_created = models.DateTimeField(auto_now_add=True)
|
date_created = models.DateTimeField(auto_now_add=True)
|
||||||
date_updated = models.DateTimeField(auto_now=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):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
|
@ -71,28 +94,52 @@ class CommandFilterRule(OrgModelMixin):
|
||||||
verbose_name = _("Command filter rule")
|
verbose_name = _("Command filter rule")
|
||||||
|
|
||||||
@lazyproperty
|
@lazyproperty
|
||||||
def _pattern(self):
|
def pattern(self):
|
||||||
if self.type == 'command':
|
if self.type == 'command':
|
||||||
regex = []
|
s = self.construct_command_regex(content=self.content)
|
||||||
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))
|
|
||||||
else:
|
else:
|
||||||
s = r'{0}'.format(self.content)
|
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:
|
try:
|
||||||
_pattern = re.compile(s)
|
pattern = re.compile(regex)
|
||||||
except:
|
except Exception as e:
|
||||||
_pattern = ''
|
error = _('The generated regular expression is incorrect: {}').format(str(e))
|
||||||
return _pattern
|
logger.error(error)
|
||||||
|
return False, error, None
|
||||||
|
return True, '', pattern
|
||||||
|
|
||||||
def match(self, data):
|
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:
|
if not found:
|
||||||
return self.ACTION_UNKNOWN, ''
|
return self.ACTION_UNKNOWN, ''
|
||||||
|
|
||||||
|
|
|
@ -203,7 +203,6 @@ class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
|
||||||
sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo'))
|
sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo'))
|
||||||
shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell'))
|
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'))
|
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"))
|
sftp_root = models.CharField(default='tmp', max_length=128, verbose_name=_("SFTP Root"))
|
||||||
token = models.TextField(default='', verbose_name=_('Token'))
|
token = models.TextField(default='', verbose_name=_('Token'))
|
||||||
home = models.CharField(max_length=4096, default='', verbose_name=_('Home'), blank=True)
|
home = models.CharField(max_length=4096, default='', verbose_name=_('Home'), blank=True)
|
||||||
|
|
|
@ -69,6 +69,9 @@ class AssetSerializer(BulkOrgResourceModelSerializer):
|
||||||
nodes_display = serializers.ListField(
|
nodes_display = serializers.ListField(
|
||||||
child=serializers.CharField(), label=_('Nodes name'), required=False
|
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'
|
'domain', 'domain_display', 'platform', 'admin_user', 'admin_user_display'
|
||||||
]
|
]
|
||||||
fields_m2m = [
|
fields_m2m = [
|
||||||
'nodes', 'nodes_display', 'labels',
|
'nodes', 'nodes_display', 'labels', 'labels_display',
|
||||||
]
|
]
|
||||||
read_only_fields = [
|
read_only_fields = [
|
||||||
'connectivity', 'date_verified', 'cpu_info', 'hardware_info',
|
'connectivity', 'date_verified', 'cpu_info', 'hardware_info',
|
||||||
|
|
|
@ -3,6 +3,7 @@
|
||||||
import re
|
import re
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from ..models import CommandFilter, CommandFilterRule
|
from ..models import CommandFilter, CommandFilterRule
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
from orgs.utils import tmp_to_root_org
|
from orgs.utils import tmp_to_root_org
|
||||||
|
@ -22,16 +23,14 @@ class CommandFilterSerializer(BulkOrgResourceModelSerializer):
|
||||||
'comment', 'created_by',
|
'comment', 'created_by',
|
||||||
]
|
]
|
||||||
fields_fk = ['rules']
|
fields_fk = ['rules']
|
||||||
fields_m2m = ['system_users']
|
fields_m2m = ['users', 'user_groups', 'system_users', 'assets', 'applications']
|
||||||
fields = fields_small + fields_fk + fields_m2m
|
fields = fields_small + fields_fk + fields_m2m
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'rules': {'read_only': True},
|
'rules': {'read_only': True}
|
||||||
'system_users': {'required': False},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
||||||
invalid_pattern = re.compile(r'[\.\*\+\[\\\?\{\}\^\$\|\(\)\#\<\>]')
|
|
||||||
type_display = serializers.ReadOnlyField(source='get_type_display')
|
type_display = serializers.ReadOnlyField(source='get_type_display')
|
||||||
action_display = serializers.ReadOnlyField(source='get_action_display')
|
action_display = serializers.ReadOnlyField(source='get_action_display')
|
||||||
|
|
||||||
|
@ -39,13 +38,13 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
||||||
model = CommandFilterRule
|
model = CommandFilterRule
|
||||||
fields_mini = ['id']
|
fields_mini = ['id']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'type', 'type_display', 'content', 'priority',
|
'type', 'type_display', 'content', 'pattern', 'priority',
|
||||||
'action', 'action_display', 'reviewers',
|
'action', 'action_display', 'reviewers',
|
||||||
'date_created', 'date_updated',
|
'date_created', 'date_updated',
|
||||||
'comment', 'created_by',
|
'comment', 'created_by',
|
||||||
]
|
]
|
||||||
fields_fk = ['filter']
|
fields_fk = ['filter']
|
||||||
fields = '__all__'
|
fields = fields_small + fields_fk
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
@ -61,15 +60,16 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
||||||
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
|
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
|
||||||
action._choices = choices
|
action._choices = choices
|
||||||
|
|
||||||
# def validate_content(self, content):
|
def validate_content(self, content):
|
||||||
# tp = self.initial_data.get("type")
|
tp = self.initial_data.get("type")
|
||||||
# if tp == CommandFilterRule.TYPE_REGEX:
|
if tp == CommandFilterRule.TYPE_COMMAND:
|
||||||
# return content
|
regex = CommandFilterRule.construct_command_regex(content)
|
||||||
# if self.invalid_pattern.search(content):
|
else:
|
||||||
# invalid_char = self.invalid_pattern.pattern.replace('\\', '')
|
regex = content
|
||||||
# msg = _("Content should not be contain: {}").format(invalid_char)
|
succeed, error, pattern = CommandFilterRule.compile_regex(regex)
|
||||||
# raise serializers.ValidationError(msg)
|
if not succeed:
|
||||||
# return content
|
raise serializers.ValidationError(error)
|
||||||
|
return content
|
||||||
|
|
||||||
|
|
||||||
class CommandConfirmSerializer(serializers.Serializer):
|
class CommandConfirmSerializer(serializers.Serializer):
|
||||||
|
|
|
@ -48,8 +48,10 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'password': {
|
'password': {
|
||||||
"write_only": True,
|
"write_only": True,
|
||||||
|
'trim_whitespace': False,
|
||||||
"validators": [validate_password_contains_left_double_curly_bracket]
|
"validators": [validate_password_contains_left_double_curly_bracket]
|
||||||
},
|
},
|
||||||
|
'cmd_filters': {"required": False},
|
||||||
'public_key': {"write_only": True},
|
'public_key': {"write_only": True},
|
||||||
'private_key': {"write_only": True},
|
'private_key': {"write_only": True},
|
||||||
'token': {"write_only": True},
|
'token': {"write_only": True},
|
||||||
|
|
|
@ -10,7 +10,6 @@ from django.dispatch import receiver
|
||||||
from django.utils.functional import LazyObject
|
from django.utils.functional import LazyObject
|
||||||
|
|
||||||
from common.signals import django_ready
|
from common.signals import django_ready
|
||||||
from common.db.utils import close_old_connections
|
|
||||||
from common.utils.connection import RedisPubSub
|
from common.utils.connection import RedisPubSub
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
from assets.models import Asset, Node
|
from assets.models import Asset, Node
|
||||||
|
@ -78,30 +77,17 @@ def on_node_asset_change(sender, instance, **kwargs):
|
||||||
def subscribe_node_assets_mapping_expire(sender, **kwargs):
|
def subscribe_node_assets_mapping_expire(sender, **kwargs):
|
||||||
logger.debug("Start subscribe for expire node assets id mapping from memory")
|
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)
|
||||||
|
logger.debug(
|
||||||
|
"Expire node assets id mapping from memory of org={}, pid={}"
|
||||||
|
"".format(str(org_id), os.getpid())
|
||||||
|
)
|
||||||
|
|
||||||
def keep_subscribe_node_assets_relation():
|
def keep_subscribe_node_assets_relation():
|
||||||
while True:
|
node_assets_mapping_for_memory_pub_sub.keep_handle_msg(handle_node_relation_change)
|
||||||
try:
|
|
||||||
subscribe = node_assets_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
|
|
||||||
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())
|
|
||||||
)
|
|
||||||
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()
|
|
||||||
|
|
||||||
t = threading.Thread(target=keep_subscribe_node_assets_relation)
|
t = threading.Thread(target=keep_subscribe_node_assets_relation)
|
||||||
t.daemon = True
|
t.daemon = True
|
||||||
|
|
|
@ -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>/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>/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('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'),
|
path('accounts/tasks/', api.AccountTaskCreateAPI.as_view(), name='account-task-create'),
|
||||||
|
|
||||||
|
|
|
@ -2,9 +2,10 @@
|
||||||
#
|
#
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import json
|
import json
|
||||||
import base64
|
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
import os
|
import os
|
||||||
|
import base64
|
||||||
|
import ctypes
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.cache import cache
|
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.exceptions import PermissionDenied
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from applications.models import Application
|
||||||
from authentication.signals import post_auth_failed, post_auth_success
|
from authentication.signals import post_auth_failed, post_auth_success
|
||||||
from common.utils import get_logger, random_string
|
from common.utils import get_logger, random_string
|
||||||
from common.mixins.api import SerializerMixin
|
from common.mixins.api import SerializerMixin
|
||||||
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
|
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
|
||||||
|
from common.utils.common import get_file_by_arch
|
||||||
from orgs.mixins.api import RootOrgViewMixin
|
from orgs.mixins.api import RootOrgViewMixin
|
||||||
from common.http import is_true
|
from common.http import is_true
|
||||||
from perms.utils.asset.permission import get_asset_system_user_ids_with_actions_by_user
|
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['session bpp:i'] = os.getenv('JUMPSERVER_COLOR_DEPTH', '32')
|
||||||
options['audiomode:i'] = self.parse_env_bool('JUMPSERVER_DISABLE_AUDIO', 'false', '2', '0')
|
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:
|
if asset:
|
||||||
name = asset.hostname
|
name = asset.hostname
|
||||||
elif application:
|
elif application:
|
||||||
name = application.name
|
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:
|
else:
|
||||||
name = '*'
|
name = '*'
|
||||||
|
|
||||||
|
content = ''
|
||||||
|
for k, v in options.items():
|
||||||
|
content += f'{k}:{v}\n'
|
||||||
return name, content
|
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])
|
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file', permission_classes=[IsValidUser])
|
||||||
def get_rdp_file(self, request, *args, **kwargs):
|
def get_rdp_file(self, request, *args, **kwargs):
|
||||||
if self.request.method == 'GET':
|
if self.request.method == 'GET':
|
||||||
|
|
|
@ -40,5 +40,7 @@ class TokenCreateApi(AuthMixin, CreateAPIView):
|
||||||
return Response(e.as_data(), status=400)
|
return Response(e.as_data(), status=400)
|
||||||
except errors.NeedMoreInfoError as e:
|
except errors.NeedMoreInfoError as e:
|
||||||
return Response(e.as_data(), status=200)
|
return Response(e.as_data(), status=200)
|
||||||
except errors.PasswordTooSimple as e:
|
except errors.MFAUnsetError:
|
||||||
return redirect(e.url)
|
return Response({'error': 'MFA unset, please set first'}, status=400)
|
||||||
|
except Exception as e:
|
||||||
|
return Response({"error": str(e)}, status=400)
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
from .backends import *
|
|
@ -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):
|
||||||
|
@staticmethod
|
||||||
|
def user_can_authenticate(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.debug(log_prompt.format('saml_user_data is missing'))
|
||||||
|
return None
|
||||||
|
|
||||||
|
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
|
|
@ -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
|
|
@ -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'))
|
|
@ -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'),
|
||||||
|
]
|
|
@ -0,0 +1,269 @@
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
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 prepare_django_request(request):
|
||||||
|
result = {
|
||||||
|
'https': 'on' if request.is_secure() else 'off',
|
||||||
|
'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')
|
||||||
|
|
||||||
|
try:
|
||||||
|
xml_idp_settings = IdPMetadataParse.parse(idp_metadata_xml)
|
||||||
|
except Exception as err:
|
||||||
|
xml_idp_settings = None
|
||||||
|
logger.warning('Failed to get IDP metadata XML settings, error: %s', str(err))
|
||||||
|
|
||||||
|
try:
|
||||||
|
url_idp_settings = IdPMetadataParse.parse_remote(
|
||||||
|
idp_metadata_url, timeout=20
|
||||||
|
)
|
||||||
|
except Exception as err:
|
||||||
|
url_idp_settings = None
|
||||||
|
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():
|
||||||
|
other_settings = {}
|
||||||
|
other_settings_path = settings.SAML2_OTHER_SETTINGS_PATH
|
||||||
|
if os.path.exists(other_settings_path):
|
||||||
|
with open(other_settings_path, 'r') as json_data:
|
||||||
|
try:
|
||||||
|
other_settings = json.loads(json_data.read())
|
||||||
|
except Exception as error:
|
||||||
|
logger.error('Get other settings error: %s', error)
|
||||||
|
|
||||||
|
default = {
|
||||||
|
"organization": {
|
||||||
|
"en": {
|
||||||
|
"name": "JumpServer",
|
||||||
|
"displayname": "JumpServer",
|
||||||
|
"url": "https://jumpserver.org/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default.update(other_settings)
|
||||||
|
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()
|
||||||
|
|
||||||
|
for attr, value in attrs.items():
|
||||||
|
attr = attr[real_key_index:]
|
||||||
|
user_attrs[attr] = self.value_to_str(value)
|
||||||
|
return user_attrs
|
||||||
|
|
||||||
|
|
||||||
|
class Saml2AuthRequestView(View, PrepareRequestMixin):
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
log_prompt = "Process GET requests [SAML2AuthRequestView]: {}"
|
||||||
|
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 GET requests [SAML2EndSessionView]: {}"
|
||||||
|
logger.debug(log_prompt.format('Start'))
|
||||||
|
return self.post(request)
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
log_prompt = "Process POST requests [SAML2EndSessionView]: {}"
|
||||||
|
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 POST requests [SAML2AuthCallbackView]: {}"
|
||||||
|
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_errors()
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
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)
|
||||||
|
logger.error(log_prompt.format('Saml response has error: %s' % str(errors)))
|
||||||
|
return HttpResponseRedirect(settings.AUTH_SAML2_AUTHENTICATION_FAILURE_REDIRECT_URI)
|
||||||
|
|
||||||
|
@csrf_exempt
|
||||||
|
def dispatch(self, *args, **kwargs):
|
||||||
|
return super().dispatch(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class Saml2AuthMetadataView(View, PrepareRequestMixin):
|
||||||
|
|
||||||
|
def get(self, _):
|
||||||
|
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)
|
||||||
|
|
||||||
|
if len(errors) == 0:
|
||||||
|
resp = HttpResponse(content=metadata, content_type='text/xml')
|
||||||
|
else:
|
||||||
|
resp = HttpResponseServerError(content=', '.join(errors))
|
||||||
|
return resp
|
|
@ -51,10 +51,14 @@ invalid_login_msg = _(
|
||||||
"You can also try {times_try} times "
|
"You can also try {times_try} times "
|
||||||
"(The account will be temporarily locked for {block_time} minutes)"
|
"(The account will be temporarily locked for {block_time} minutes)"
|
||||||
)
|
)
|
||||||
block_login_msg = _(
|
block_user_login_msg = _(
|
||||||
"The account has been locked "
|
"The account has been locked "
|
||||||
"(please contact admin to unlock it or try again after {} minutes)"
|
"(please contact admin to unlock it or try again after {} minutes)"
|
||||||
)
|
)
|
||||||
|
block_ip_login_msg = _(
|
||||||
|
"The ip has been locked "
|
||||||
|
"(please contact admin to unlock it or try again after {} minutes)"
|
||||||
|
)
|
||||||
block_mfa_msg = _(
|
block_mfa_msg = _(
|
||||||
"The account has been locked "
|
"The account has been locked "
|
||||||
"(please contact admin to unlock it or try again after {} minutes)"
|
"(please contact admin to unlock it or try again after {} minutes)"
|
||||||
|
@ -118,7 +122,7 @@ class BlockGlobalIpLoginError(AuthFailedError):
|
||||||
error = 'block_global_ip_login'
|
error = 'block_global_ip_login'
|
||||||
|
|
||||||
def __init__(self, username, ip, **kwargs):
|
def __init__(self, username, ip, **kwargs):
|
||||||
self.msg = _("IP is not allowed")
|
self.msg = block_ip_login_msg.format(settings.SECURITY_LOGIN_IP_LIMIT_TIME)
|
||||||
LoginIpBlockUtil(ip).set_block_if_need()
|
LoginIpBlockUtil(ip).set_block_if_need()
|
||||||
super().__init__(username=username, ip=ip, **kwargs)
|
super().__init__(username=username, ip=ip, **kwargs)
|
||||||
|
|
||||||
|
@ -133,7 +137,7 @@ class CredentialError(
|
||||||
block_time = settings.SECURITY_LOGIN_LIMIT_TIME
|
block_time = settings.SECURITY_LOGIN_LIMIT_TIME
|
||||||
|
|
||||||
if times_remainder < 1:
|
if times_remainder < 1:
|
||||||
self.msg = block_login_msg.format(settings.SECURITY_LOGIN_LIMIT_TIME)
|
self.msg = block_user_login_msg.format(settings.SECURITY_LOGIN_LIMIT_TIME)
|
||||||
return
|
return
|
||||||
|
|
||||||
default_msg = invalid_login_msg.format(
|
default_msg = invalid_login_msg.format(
|
||||||
|
@ -184,7 +188,7 @@ class BlockLoginError(AuthFailedNeedBlockMixin, AuthFailedError):
|
||||||
error = 'block_login'
|
error = 'block_login'
|
||||||
|
|
||||||
def __init__(self, username, ip):
|
def __init__(self, username, ip):
|
||||||
self.msg = block_login_msg.format(settings.SECURITY_LOGIN_LIMIT_TIME)
|
self.msg = block_user_login_msg.format(settings.SECURITY_LOGIN_LIMIT_TIME)
|
||||||
super().__init__(username=username, ip=ip)
|
super().__init__(username=username, ip=ip)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -43,8 +43,8 @@ class UserLoginForm(forms.Form):
|
||||||
|
|
||||||
|
|
||||||
class UserCheckOtpCodeForm(forms.Form):
|
class UserCheckOtpCodeForm(forms.Form):
|
||||||
code = forms.CharField(label=_('MFA Code'), max_length=6, required=False)
|
code = forms.CharField(label=_('MFA Code'), max_length=128, required=False)
|
||||||
mfa_type = forms.CharField(label=_('MFA type'), max_length=6)
|
mfa_type = forms.CharField(label=_('MFA type'), max_length=128)
|
||||||
|
|
||||||
|
|
||||||
class CustomCaptchaTextInput(CaptchaTextInput):
|
class CustomCaptchaTextInput(CaptchaTextInput):
|
||||||
|
@ -57,7 +57,7 @@ class CaptchaMixin(forms.Form):
|
||||||
|
|
||||||
class ChallengeMixin(forms.Form):
|
class ChallengeMixin(forms.Form):
|
||||||
challenge = forms.CharField(
|
challenge = forms.CharField(
|
||||||
label=_('MFA code'), max_length=6, required=False,
|
label=_('MFA code'), max_length=128, required=False,
|
||||||
widget=forms.TextInput(attrs={
|
widget=forms.TextInput(attrs={
|
||||||
'placeholder': _("Dynamic code"),
|
'placeholder': _("Dynamic code"),
|
||||||
'style': 'width: 50%'
|
'style': 'width: 50%'
|
||||||
|
|
|
@ -1,14 +1,36 @@
|
||||||
from django.shortcuts import redirect
|
from django.shortcuts import redirect, reverse
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
|
|
||||||
class MFAMiddleware:
|
class MFAMiddleware:
|
||||||
|
"""
|
||||||
|
这个 中间件 是用来全局拦截开启了 MFA 却没有认证的,如 OIDC, CAS,使用第三方库做的登录,直接 login 了,
|
||||||
|
所以只能在 Middleware 中控制
|
||||||
|
"""
|
||||||
def __init__(self, get_response):
|
def __init__(self, get_response):
|
||||||
self.get_response = get_response
|
self.get_response = get_response
|
||||||
|
|
||||||
def __call__(self, request):
|
def __call__(self, request):
|
||||||
response = self.get_response(request)
|
response = self.get_response(request)
|
||||||
if request.path.find('/auth/login/otp/') > -1:
|
# 没有校验
|
||||||
|
if not request.session.get('auth_mfa_required'):
|
||||||
return response
|
return response
|
||||||
if request.session.get('auth_mfa_required'):
|
# 没有认证过,证明不是从 第三方 来的
|
||||||
return redirect('authentication:login-mfa')
|
if request.user.is_anonymous:
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
# 这个是 mfa 登录页需要的请求, 也得放出来, 用户其实已经在 CAS/OIDC 中完成登录了
|
||||||
|
white_urls = [
|
||||||
|
'login/mfa', 'mfa/select', 'jsi18n/', '/static/',
|
||||||
|
'/profile/otp', '/logout/',
|
||||||
|
]
|
||||||
|
for url in white_urls:
|
||||||
|
if request.path.find(url) > -1:
|
||||||
|
return response
|
||||||
|
|
||||||
|
# 因为使用 CAS/OIDC 登录的,不小心去了别的页面就回不来了
|
||||||
|
if request.path.find('users/profile') > -1:
|
||||||
|
return HttpResponse('', status=401)
|
||||||
|
|
||||||
|
url = reverse('authentication:login-mfa') + '?_=middleware'
|
||||||
|
return redirect(url)
|
||||||
|
|
|
@ -257,7 +257,8 @@ class MFAMixin:
|
||||||
def _check_login_page_mfa_if_need(self, user):
|
def _check_login_page_mfa_if_need(self, user):
|
||||||
if not settings.SECURITY_MFA_IN_LOGIN_PAGE:
|
if not settings.SECURITY_MFA_IN_LOGIN_PAGE:
|
||||||
return
|
return
|
||||||
self._check_if_no_active_mfa(user)
|
if not user.active_mfa_backends:
|
||||||
|
return
|
||||||
|
|
||||||
request = self.request
|
request = self.request
|
||||||
data = request.data if hasattr(request, 'data') else request.POST
|
data = request.data if hasattr(request, 'data') else request.POST
|
||||||
|
@ -274,10 +275,8 @@ class MFAMixin:
|
||||||
if not user.mfa_enabled:
|
if not user.mfa_enabled:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._check_if_no_active_mfa(user)
|
active_mfa_names = user.active_mfa_backends_mapper.keys()
|
||||||
|
raise errors.MFARequiredError(mfa_types=tuple(active_mfa_names))
|
||||||
active_mfa_mapper = user.active_mfa_backends_mapper
|
|
||||||
raise errors.MFARequiredError(mfa_types=tuple(active_mfa_mapper.keys()))
|
|
||||||
|
|
||||||
def mark_mfa_ok(self, mfa_type):
|
def mark_mfa_ok(self, mfa_type):
|
||||||
self.request.session['auth_mfa'] = 1
|
self.request.session['auth_mfa'] = 1
|
||||||
|
@ -417,12 +416,10 @@ class AuthACLMixin:
|
||||||
self.request.session["auth_confirm"] = "1"
|
self.request.session["auth_confirm"] = "1"
|
||||||
return
|
return
|
||||||
elif ticket.state_reject:
|
elif ticket.state_reject:
|
||||||
self.clean_mfa_mark()
|
|
||||||
raise errors.LoginConfirmOtherError(
|
raise errors.LoginConfirmOtherError(
|
||||||
ticket.id, ticket.get_state_display()
|
ticket.id, ticket.get_state_display()
|
||||||
)
|
)
|
||||||
elif ticket.state_close:
|
elif ticket.state_close:
|
||||||
self.clean_mfa_mark()
|
|
||||||
raise errors.LoginConfirmOtherError(
|
raise errors.LoginConfirmOtherError(
|
||||||
ticket.id, ticket.get_state_display()
|
ticket.id, ticket.get_state_display()
|
||||||
)
|
)
|
||||||
|
|
|
@ -8,6 +8,9 @@ from django_cas_ng.signals import cas_user_authenticated
|
||||||
|
|
||||||
from jms_oidc_rp.signals import openid_user_login_failed, openid_user_login_success
|
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
|
from .signals import post_auth_success, post_auth_failed
|
||||||
|
|
||||||
|
|
||||||
|
@ -43,3 +46,15 @@ def on_oidc_user_login_failed(sender, username, request, reason, **kwargs):
|
||||||
def on_cas_user_login_success(sender, request, user, **kwargs):
|
def on_cas_user_login_success(sender, request, user, **kwargs):
|
||||||
request.session['auth_backend'] = settings.AUTH_BACKEND_CAS
|
request.session['auth_backend'] = settings.AUTH_BACKEND_CAS
|
||||||
post_auth_success.send(sender, user=user, request=request)
|
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)
|
||||||
|
|
|
@ -56,5 +56,6 @@ urlpatterns = [
|
||||||
# openid
|
# openid
|
||||||
path('cas/', include(('authentication.backends.cas.urls', 'authentication'), namespace='cas')),
|
path('cas/', include(('authentication.backends.cas.urls', 'authentication'), namespace='cas')),
|
||||||
path('openid/', include(('jms_oidc_rp.urls', 'authentication'), namespace='openid')),
|
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')),
|
path('captcha/', include('captcha.urls')),
|
||||||
]
|
]
|
||||||
|
|
|
@ -48,7 +48,6 @@ class UserLoginView(mixins.AuthMixin, FormView):
|
||||||
return None
|
return None
|
||||||
next_url = request.GET.get('next') or '/'
|
next_url = request.GET.get('next') or '/'
|
||||||
auth_type = ''
|
auth_type = ''
|
||||||
|
|
||||||
if settings.AUTH_OPENID:
|
if settings.AUTH_OPENID:
|
||||||
auth_type = 'OIDC'
|
auth_type = 'OIDC'
|
||||||
openid_auth_url = reverse(settings.AUTH_OPENID_AUTH_LOGIN_URL_NAME)
|
openid_auth_url = reverse(settings.AUTH_OPENID_AUTH_LOGIN_URL_NAME)
|
||||||
|
@ -62,7 +61,13 @@ class UserLoginView(mixins.AuthMixin, FormView):
|
||||||
else:
|
else:
|
||||||
cas_auth_url = None
|
cas_auth_url = None
|
||||||
|
|
||||||
if not any([openid_auth_url, cas_auth_url]):
|
if settings.AUTH_SAML2:
|
||||||
|
auth_type = 'saml2'
|
||||||
|
saml2_auth_url = reverse(settings.SAML2_LOGIN_URL_NAME) + f'?next={next_url}'
|
||||||
|
else:
|
||||||
|
saml2_auth_url = None
|
||||||
|
|
||||||
|
if not any([openid_auth_url, cas_auth_url, saml2_auth_url]):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
login_redirect = settings.LOGIN_REDIRECT_TO_BACKEND.lower()
|
login_redirect = settings.LOGIN_REDIRECT_TO_BACKEND.lower()
|
||||||
|
@ -72,8 +77,10 @@ class UserLoginView(mixins.AuthMixin, FormView):
|
||||||
auth_url = cas_auth_url
|
auth_url = cas_auth_url
|
||||||
elif login_redirect in ['openid', 'oidc'] and openid_auth_url:
|
elif login_redirect in ['openid', 'oidc'] and openid_auth_url:
|
||||||
auth_url = openid_auth_url
|
auth_url = openid_auth_url
|
||||||
|
elif login_redirect in ['saml2'] and saml2_auth_url:
|
||||||
|
auth_url = saml2_auth_url
|
||||||
else:
|
else:
|
||||||
auth_url = openid_auth_url or cas_auth_url
|
auth_url = openid_auth_url or cas_auth_url or saml2_auth_url
|
||||||
|
|
||||||
if settings.LOGIN_REDIRECT_TO_BACKEND or not settings.LOGIN_REDIRECT_MSG_ENABLED:
|
if settings.LOGIN_REDIRECT_TO_BACKEND or not settings.LOGIN_REDIRECT_MSG_ENABLED:
|
||||||
redirect_url = auth_url
|
redirect_url = auth_url
|
||||||
|
@ -166,6 +173,12 @@ class UserLoginView(mixins.AuthMixin, FormView):
|
||||||
'url': reverse('authentication:cas:cas-login'),
|
'url': reverse('authentication:cas:cas-login'),
|
||||||
'logo': static('img/login_cas_logo.png')
|
'logo': static('img/login_cas_logo.png')
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
'name': 'SAML2',
|
||||||
|
'enabled': settings.AUTH_SAML2,
|
||||||
|
'url': reverse('authentication:saml2:saml2-login'),
|
||||||
|
'logo': static('img/login_cas_logo.png')
|
||||||
|
},
|
||||||
{
|
{
|
||||||
'name': _('WeCom'),
|
'name': _('WeCom'),
|
||||||
'enabled': settings.AUTH_WECOM,
|
'enabled': settings.AUTH_WECOM,
|
||||||
|
@ -292,6 +305,8 @@ class UserLogoutView(TemplateView):
|
||||||
return settings.AUTH_OPENID_AUTH_LOGOUT_URL_NAME
|
return settings.AUTH_OPENID_AUTH_LOGOUT_URL_NAME
|
||||||
elif 'CAS' in backend:
|
elif 'CAS' in backend:
|
||||||
return settings.CAS_LOGOUT_URL_NAME
|
return settings.CAS_LOGOUT_URL_NAME
|
||||||
|
elif 'saml2' in backend:
|
||||||
|
return settings.SAML2_LOGOUT_URL_NAME
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
|
|
|
@ -3,6 +3,7 @@
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
from django.views.generic.edit import FormView
|
from django.views.generic.edit import FormView
|
||||||
|
from django.shortcuts import redirect
|
||||||
|
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
from .. import forms, errors, mixins
|
from .. import forms, errors, mixins
|
||||||
|
@ -19,9 +20,15 @@ class UserLoginMFAView(mixins.AuthMixin, FormView):
|
||||||
|
|
||||||
def get(self, *args, **kwargs):
|
def get(self, *args, **kwargs):
|
||||||
try:
|
try:
|
||||||
self.get_user_from_session()
|
user = self.get_user_from_session()
|
||||||
except errors.SessionEmptyError:
|
except errors.SessionEmptyError:
|
||||||
return redirect_to_guard_view()
|
return redirect_to_guard_view('session_empty')
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._check_if_no_active_mfa(user)
|
||||||
|
except errors.MFAUnsetError as e:
|
||||||
|
return redirect(e.url + '?_=login_mfa')
|
||||||
|
|
||||||
return super().get(*args, **kwargs)
|
return super().get(*args, **kwargs)
|
||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
|
@ -30,17 +37,17 @@ class UserLoginMFAView(mixins.AuthMixin, FormView):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._do_check_user_mfa(code, mfa_type)
|
self._do_check_user_mfa(code, mfa_type)
|
||||||
return redirect_to_guard_view()
|
return redirect_to_guard_view('mfa_ok')
|
||||||
except (errors.MFAFailedError, errors.BlockMFAError) as e:
|
except (errors.MFAFailedError, errors.BlockMFAError) as e:
|
||||||
form.add_error('code', e.msg)
|
form.add_error('code', e.msg)
|
||||||
return super().form_invalid(form)
|
return super().form_invalid(form)
|
||||||
except errors.SessionEmptyError:
|
except errors.SessionEmptyError:
|
||||||
return redirect_to_guard_view()
|
return redirect_to_guard_view('session_empty')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
import traceback
|
import traceback
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
return redirect_to_guard_view()
|
return redirect_to_guard_view('unexpect')
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
user = self.get_user_from_session()
|
user = self.get_user_from_session()
|
||||||
|
|
|
@ -3,6 +3,6 @@
|
||||||
from django.shortcuts import reverse, redirect
|
from django.shortcuts import reverse, redirect
|
||||||
|
|
||||||
|
|
||||||
def redirect_to_guard_view():
|
def redirect_to_guard_view(comment=''):
|
||||||
continue_url = reverse('authentication:login-guard')
|
continue_url = reverse('authentication:login-guard') + '?_=' + comment
|
||||||
return redirect(continue_url)
|
return redirect(continue_url)
|
||||||
|
|
|
@ -1,6 +1,9 @@
|
||||||
from common.utils import get_logger
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from django.db import connections
|
from django.db import connections
|
||||||
|
|
||||||
|
from common.utils import get_logger
|
||||||
|
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
|
||||||
|
@ -44,3 +47,10 @@ def get_objects(model, pks):
|
||||||
def close_old_connections():
|
def close_old_connections():
|
||||||
for conn in connections.all():
|
for conn in connections.all():
|
||||||
conn.close_if_unusable_or_obsolete()
|
conn.close_if_unusable_or_obsolete()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def safe_db_connection():
|
||||||
|
close_old_connections()
|
||||||
|
yield
|
||||||
|
close_old_connections()
|
||||||
|
|
|
@ -37,12 +37,17 @@ class SendAndVerifySMSUtil:
|
||||||
self.code = ''
|
self.code = ''
|
||||||
self.timeout = timeout or self.TIMEOUT
|
self.timeout = timeout or self.TIMEOUT
|
||||||
self.key_suffix = key_suffix or str(phone)
|
self.key_suffix = key_suffix or str(phone)
|
||||||
self.key = self.KEY_TMPL.format(key_suffix)
|
self.key = self.KEY_TMPL.format(self.key_suffix)
|
||||||
|
|
||||||
def gen_and_send(self):
|
def gen_and_send(self):
|
||||||
"""
|
"""
|
||||||
生成,保存,发送
|
生成,保存,发送
|
||||||
"""
|
"""
|
||||||
|
ttl = self.ttl()
|
||||||
|
if ttl > 0:
|
||||||
|
logger.error('Send sms too frequently, delay {}'.format(ttl))
|
||||||
|
raise CodeSendTooFrequently(ttl)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
code = self.generate()
|
code = self.generate()
|
||||||
self.send(code)
|
self.send(code)
|
||||||
|
@ -62,10 +67,6 @@ class SendAndVerifySMSUtil:
|
||||||
"""
|
"""
|
||||||
发送信息的方法,如果有错误直接抛出 api 异常
|
发送信息的方法,如果有错误直接抛出 api 异常
|
||||||
"""
|
"""
|
||||||
ttl = self.ttl()
|
|
||||||
if ttl > 0:
|
|
||||||
logger.error('Send sms too frequently, delay {}'.format(ttl))
|
|
||||||
raise CodeSendTooFrequently(ttl)
|
|
||||||
sms = SMS()
|
sms = SMS()
|
||||||
sms.send_verify_code(self.phone, code)
|
sms.send_verify_code(self.phone, code)
|
||||||
cache.set(self.key, self.code, self.timeout)
|
cache.set(self.key, self.code, self.timeout)
|
||||||
|
|
|
@ -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 django.conf import settings
|
||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
|
|
||||||
|
@ -24,11 +26,31 @@ def send_mail_async(*args, **kwargs):
|
||||||
if len(args) == 3:
|
if len(args) == 3:
|
||||||
args = list(args)
|
args = list(args)
|
||||||
args[0] = (settings.EMAIL_SUBJECT_PREFIX or '') + args[0]
|
args[0] = (settings.EMAIL_SUBJECT_PREFIX or '') + args[0]
|
||||||
email_from = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
|
from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER
|
||||||
args.insert(2, email_from)
|
args.insert(2, from_email)
|
||||||
args = tuple(args)
|
args = tuple(args)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return send_mail(*args, **kwargs)
|
return send_mail(*args, **kwargs)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("Sending mail error: {}".format(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))
|
||||||
|
|
|
@ -10,7 +10,10 @@ from functools import wraps
|
||||||
import time
|
import time
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import psutil
|
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}')
|
UUID_PATTERN = re.compile(r'\w{8}(-\w{4}){3}-\w{12}')
|
||||||
ipip_db = None
|
ipip_db = None
|
||||||
|
@ -252,7 +255,40 @@ def get_cpu_load():
|
||||||
return float(single_cpu_load_1)
|
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:
|
||||||
|
logger.debug(f'Get memory usage by docker limit: {e}')
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def get_memory_usage():
|
def get_memory_usage():
|
||||||
|
usage = get_docker_mem_usage_if_limit()
|
||||||
|
if usage is not None:
|
||||||
|
return usage
|
||||||
return psutil.virtual_memory().percent
|
return psutil.virtual_memory().percent
|
||||||
|
|
||||||
|
|
||||||
|
@ -293,3 +329,13 @@ def unique(objects, key=None):
|
||||||
if v not in seen:
|
if v not in seen:
|
||||||
seen[v] = obj
|
seen[v] = obj
|
||||||
return list(seen.values())
|
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
|
||||||
|
|
|
@ -1,6 +1,13 @@
|
||||||
|
import json
|
||||||
|
|
||||||
import redis
|
import redis
|
||||||
from django.conf import settings
|
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):
|
def get_redis_client(db):
|
||||||
rc = redis.StrictRedis(
|
rc = redis.StrictRedis(
|
||||||
|
@ -23,5 +30,38 @@ class RedisPubSub:
|
||||||
return ps
|
return ps
|
||||||
|
|
||||||
def publish(self, data):
|
def publish(self, data):
|
||||||
self.redis.publish(self.ch, data)
|
data_json = json.dumps(data)
|
||||||
|
self.redis.publish(self.ch, data_json)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def keep_handle_msg(self, handle):
|
||||||
|
"""
|
||||||
|
handle arg is the pub published
|
||||||
|
|
||||||
|
:param handle: lambda item: do_something
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
sub = self.subscribe()
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
|
@ -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())
|
|
@ -1,7 +1,10 @@
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
import threading
|
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 redis import Redis
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
|
|
||||||
|
@ -49,7 +52,8 @@ class DistributedLock(RedisLock):
|
||||||
else:
|
else:
|
||||||
auto_renewal = False
|
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_on_transaction_commit = release_on_transaction_commit
|
||||||
self._release_raise_exc = release_raise_exc
|
self._release_raise_exc = release_raise_exc
|
||||||
self._reentrant = reentrant
|
self._reentrant = reentrant
|
||||||
|
@ -71,8 +75,16 @@ class DistributedLock(RedisLock):
|
||||||
# 要创建一个新的锁对象
|
# 要创建一个新的锁对象
|
||||||
with self.__class__(**self.kwargs_copy):
|
with self.__class__(**self.kwargs_copy):
|
||||||
return func(*args, **kwds)
|
return func(*args, **kwds)
|
||||||
|
|
||||||
return inner
|
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):
|
def locked_by_me(self):
|
||||||
if self.locked():
|
if self.locked():
|
||||||
if self.get_owner_id() == self.id:
|
if self.get_owner_id() == self.id:
|
||||||
|
@ -92,8 +104,7 @@ class DistributedLock(RedisLock):
|
||||||
if self._reentrant:
|
if self._reentrant:
|
||||||
if self.locked_by_current_thread():
|
if self.locked_by_current_thread():
|
||||||
self._acquired_reentrant_lock = True
|
self._acquired_reentrant_lock = True
|
||||||
logger.debug(
|
logger.debug(f'Reentry lock ok: lock_id={self.id} owner_id={self.get_owner_id()} lock={self.name} thread={self._thread_id}')
|
||||||
f'Reentry lock ok: lock_id={self.id} owner_id={self.get_owner_id()} lock={self.name} thread={self._thread_id}')
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
logger.debug(f'Attempt acquire reentrant-lock: lock_id={self.id} lock={self.name} thread={self._thread_id}')
|
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}')
|
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)
|
setattr(thread_local, self.name, self.id)
|
||||||
else:
|
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
|
return acquired
|
||||||
else:
|
else:
|
||||||
logger.debug(f'Attempt acquire lock: lock_id={self.id} lock={self.name} thread={self._thread_id}')
|
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:
|
else:
|
||||||
_release = self._release_on_reentrant_locked_by_brother
|
_release = self._release_on_reentrant_locked_by_brother
|
||||||
else:
|
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:
|
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)
|
transaction.on_commit(_release)
|
||||||
else:
|
else:
|
||||||
_release()
|
_release()
|
||||||
|
|
|
@ -229,6 +229,19 @@ class Config(dict):
|
||||||
'AUTH_SSO': False,
|
'AUTH_SSO': False,
|
||||||
'AUTH_SSO_AUTHKEY_TTL': 60 * 15,
|
'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_OTHER_SETTINGS_PATH': '',
|
||||||
|
'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,
|
'AUTH_WECOM': False,
|
||||||
'WECOM_CORPID': '',
|
'WECOM_CORPID': '',
|
||||||
|
@ -246,7 +259,7 @@ class Config(dict):
|
||||||
'FEISHU_APP_ID': '',
|
'FEISHU_APP_ID': '',
|
||||||
'FEISHU_APP_SECRET': '',
|
'FEISHU_APP_SECRET': '',
|
||||||
|
|
||||||
'LOGIN_REDIRECT_TO_BACKEND': '', # 'OPENID / CAS
|
'LOGIN_REDIRECT_TO_BACKEND': '', # 'OPENID / CAS / SAML2
|
||||||
'LOGIN_REDIRECT_MSG_ENABLED': True,
|
'LOGIN_REDIRECT_MSG_ENABLED': True,
|
||||||
|
|
||||||
'SMS_ENABLED': False,
|
'SMS_ENABLED': False,
|
||||||
|
@ -291,9 +304,6 @@ class Config(dict):
|
||||||
'SECURITY_COMMAND_EXECUTION': True,
|
'SECURITY_COMMAND_EXECUTION': True,
|
||||||
'SECURITY_SERVICE_ACCOUNT_REGISTRATION': True,
|
'SECURITY_SERVICE_ACCOUNT_REGISTRATION': True,
|
||||||
'SECURITY_VIEW_AUTH_NEED_MFA': True,
|
'SECURITY_VIEW_AUTH_NEED_MFA': True,
|
||||||
'SECURITY_LOGIN_LIMIT_COUNT': 7,
|
|
||||||
'SECURITY_LOGIN_IP_BLACK_LIST': [],
|
|
||||||
'SECURITY_LOGIN_LIMIT_TIME': 30,
|
|
||||||
'SECURITY_MAX_IDLE_TIME': 30,
|
'SECURITY_MAX_IDLE_TIME': 30,
|
||||||
'SECURITY_PASSWORD_EXPIRATION_TIME': 9999,
|
'SECURITY_PASSWORD_EXPIRATION_TIME': 9999,
|
||||||
'SECURITY_PASSWORD_MIN_LENGTH': 6,
|
'SECURITY_PASSWORD_MIN_LENGTH': 6,
|
||||||
|
@ -318,6 +328,14 @@ class Config(dict):
|
||||||
'USER_LOGIN_SINGLE_MACHINE_ENABLED': False,
|
'USER_LOGIN_SINGLE_MACHINE_ENABLED': False,
|
||||||
'ONLY_ALLOW_EXIST_USER_AUTH': False,
|
'ONLY_ALLOW_EXIST_USER_AUTH': False,
|
||||||
'ONLY_ALLOW_AUTH_FROM_SOURCE': False,
|
'ONLY_ALLOW_AUTH_FROM_SOURCE': False,
|
||||||
|
# 用户登录限制的规则
|
||||||
|
'SECURITY_LOGIN_LIMIT_COUNT': 7,
|
||||||
|
'SECURITY_LOGIN_LIMIT_TIME': 30,
|
||||||
|
# 登录IP限制的规则
|
||||||
|
'SECURITY_LOGIN_IP_BLACK_LIST': [],
|
||||||
|
'SECURITY_LOGIN_IP_WHITE_LIST': [],
|
||||||
|
'SECURITY_LOGIN_IP_LIMIT_COUNT': 99999,
|
||||||
|
'SECURITY_LOGIN_IP_LIMIT_TIME': 30,
|
||||||
|
|
||||||
# 启动前
|
# 启动前
|
||||||
'HTTP_BIND_HOST': '0.0.0.0',
|
'HTTP_BIND_HOST': '0.0.0.0',
|
||||||
|
|
|
@ -4,7 +4,7 @@ import os
|
||||||
import ldap
|
import ldap
|
||||||
from django.utils.translation import ugettext_lazy as _
|
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 settings
|
||||||
OTP_ISSUER_NAME = CONFIG.OTP_ISSUER_NAME
|
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_ID = CONFIG.FEISHU_APP_ID
|
||||||
FEISHU_APP_SECRET = CONFIG.FEISHU_APP_SECRET
|
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_OTHER_SETTINGS_PATH = CONFIG.SAML2_OTHER_SETTINGS_PATH
|
||||||
|
SAML2_LOGIN_URL_NAME = "authentication:saml2:saml2-login"
|
||||||
|
SAML2_LOGOUT_URL_NAME = "authentication:saml2:saml2-logout"
|
||||||
|
|
||||||
# Other setting
|
# Other setting
|
||||||
TOKEN_EXPIRATION = CONFIG.TOKEN_EXPIRATION
|
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_DINGTALK = 'authentication.backends.api.DingTalkAuthentication'
|
||||||
AUTH_BACKEND_FEISHU = 'authentication.backends.api.FeiShuAuthentication'
|
AUTH_BACKEND_FEISHU = 'authentication.backends.api.FeiShuAuthentication'
|
||||||
AUTH_BACKEND_AUTH_TOKEN = 'authentication.backends.api.AuthorizationTokenAuthentication'
|
AUTH_BACKEND_AUTH_TOKEN = 'authentication.backends.api.AuthorizationTokenAuthentication'
|
||||||
|
AUTH_BACKEND_SAML2 = 'authentication.backends.saml2.SAML2Backend'
|
||||||
|
|
||||||
|
|
||||||
AUTHENTICATION_BACKENDS = [
|
AUTHENTICATION_BACKENDS = [
|
||||||
|
@ -156,7 +166,11 @@ if AUTH_OPENID:
|
||||||
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_OIDC_CODE)
|
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_OIDC_CODE)
|
||||||
if AUTH_RADIUS:
|
if AUTH_RADIUS:
|
||||||
AUTHENTICATION_BACKENDS.insert(0, AUTH_BACKEND_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_EXIST_USER_AUTH = CONFIG.ONLY_ALLOW_EXIST_USER_AUTH
|
||||||
ONLY_ALLOW_AUTH_FROM_SOURCE = CONFIG.ONLY_ALLOW_AUTH_FROM_SOURCE
|
ONLY_ALLOW_AUTH_FROM_SOURCE = CONFIG.ONLY_ALLOW_AUTH_FROM_SOURCE
|
||||||
|
|
||||||
|
SAML_FOLDER = os.path.join(BASE_DIR, 'authentication', 'backends', 'saml2')
|
||||||
|
|
|
@ -32,11 +32,8 @@ TERMINAL_REPLAY_STORAGE = CONFIG.TERMINAL_REPLAY_STORAGE
|
||||||
|
|
||||||
# Security settings
|
# Security settings
|
||||||
SECURITY_MFA_AUTH = CONFIG.SECURITY_MFA_AUTH
|
SECURITY_MFA_AUTH = CONFIG.SECURITY_MFA_AUTH
|
||||||
SECURITY_COMMAND_EXECUTION = CONFIG.SECURITY_COMMAND_EXECUTION
|
|
||||||
SECURITY_LOGIN_LIMIT_COUNT = CONFIG.SECURITY_LOGIN_LIMIT_COUNT
|
|
||||||
SECURITY_LOGIN_IP_BLACK_LIST = CONFIG.SECURITY_LOGIN_IP_BLACK_LIST
|
|
||||||
SECURITY_LOGIN_LIMIT_TIME = CONFIG.SECURITY_LOGIN_LIMIT_TIME # Unit: minute
|
|
||||||
SECURITY_MAX_IDLE_TIME = CONFIG.SECURITY_MAX_IDLE_TIME # Unit: minute
|
SECURITY_MAX_IDLE_TIME = CONFIG.SECURITY_MAX_IDLE_TIME # Unit: minute
|
||||||
|
SECURITY_COMMAND_EXECUTION = CONFIG.SECURITY_COMMAND_EXECUTION
|
||||||
SECURITY_PASSWORD_EXPIRATION_TIME = CONFIG.SECURITY_PASSWORD_EXPIRATION_TIME # Unit: day
|
SECURITY_PASSWORD_EXPIRATION_TIME = CONFIG.SECURITY_PASSWORD_EXPIRATION_TIME # Unit: day
|
||||||
SECURITY_PASSWORD_MIN_LENGTH = CONFIG.SECURITY_PASSWORD_MIN_LENGTH # Unit: bit
|
SECURITY_PASSWORD_MIN_LENGTH = CONFIG.SECURITY_PASSWORD_MIN_LENGTH # Unit: bit
|
||||||
SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH = CONFIG.SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH # Unit: bit
|
SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH = CONFIG.SECURITY_ADMIN_USER_PASSWORD_MIN_LENGTH # Unit: bit
|
||||||
|
@ -63,6 +60,14 @@ SECURITY_INSECURE_COMMAND = CONFIG.SECURITY_INSECURE_COMMAND
|
||||||
SECURITY_INSECURE_COMMAND_LEVEL = CONFIG.SECURITY_INSECURE_COMMAND_LEVEL
|
SECURITY_INSECURE_COMMAND_LEVEL = CONFIG.SECURITY_INSECURE_COMMAND_LEVEL
|
||||||
SECURITY_INSECURE_COMMAND_EMAIL_RECEIVER = CONFIG.SECURITY_INSECURE_COMMAND_EMAIL_RECEIVER
|
SECURITY_INSECURE_COMMAND_EMAIL_RECEIVER = CONFIG.SECURITY_INSECURE_COMMAND_EMAIL_RECEIVER
|
||||||
SECURITY_CHECK_DIFFERENT_CITY_LOGIN = CONFIG.SECURITY_CHECK_DIFFERENT_CITY_LOGIN
|
SECURITY_CHECK_DIFFERENT_CITY_LOGIN = CONFIG.SECURITY_CHECK_DIFFERENT_CITY_LOGIN
|
||||||
|
# 用户登录限制的规则
|
||||||
|
SECURITY_LOGIN_LIMIT_COUNT = CONFIG.SECURITY_LOGIN_LIMIT_COUNT
|
||||||
|
SECURITY_LOGIN_LIMIT_TIME = CONFIG.SECURITY_LOGIN_LIMIT_TIME # Unit: minute
|
||||||
|
# 登录IP限制的规则
|
||||||
|
SECURITY_LOGIN_IP_BLACK_LIST = CONFIG.SECURITY_LOGIN_IP_BLACK_LIST
|
||||||
|
SECURITY_LOGIN_IP_WHITE_LIST = CONFIG.SECURITY_LOGIN_IP_WHITE_LIST
|
||||||
|
SECURITY_LOGIN_IP_LIMIT_COUNT = CONFIG.SECURITY_LOGIN_IP_LIMIT_COUNT
|
||||||
|
SECURITY_LOGIN_IP_LIMIT_TIME = CONFIG.SECURITY_LOGIN_IP_LIMIT_TIME # Unit: minute
|
||||||
|
|
||||||
# Terminal other setting
|
# Terminal other setting
|
||||||
TERMINAL_PASSWORD_AUTH = CONFIG.TERMINAL_PASSWORD_AUTH
|
TERMINAL_PASSWORD_AUTH = CONFIG.TERMINAL_PASSWORD_AUTH
|
||||||
|
|
|
@ -55,7 +55,7 @@ api_info = openapi.Info(
|
||||||
description="JumpServer Restful api docs",
|
description="JumpServer Restful api docs",
|
||||||
terms_of_service="https://www.jumpserver.org",
|
terms_of_service="https://www.jumpserver.org",
|
||||||
contact=openapi.Contact(email="support@fit2cloud.com"),
|
contact=openapi.Contact(email="support@fit2cloud.com"),
|
||||||
license=openapi.License(name="GPLv2 License"),
|
license=openapi.License(name="GPLv3 License"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,3 @@
|
||||||
version https://git-lfs.github.com/spec/v1
|
version https://git-lfs.github.com/spec/v1
|
||||||
oid sha256:4fea2cdf5a5477757cb95ff36016ed754fd65f839c12adbac9247ebdcca138ef
|
oid sha256:9a8f5840c041b5f3188621ec731fa1b4a5da20730ea6394cf5e2b5c9c241a00e
|
||||||
size 93440
|
size 94712
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,5 +1,4 @@
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.translation import gettext_lazy as _
|
|
||||||
|
|
||||||
from common.db.models import JMSModel
|
from common.db.models import JMSModel
|
||||||
|
|
||||||
|
|
|
@ -46,7 +46,6 @@ def on_site_message_create(sender, instance, created, **kwargs):
|
||||||
'message': instance.message,
|
'message': instance.message,
|
||||||
'users': user_ids
|
'users': user_ids
|
||||||
}
|
}
|
||||||
data = json.dumps(data)
|
|
||||||
new_site_msg_chan.publish(data)
|
new_site_msg_chan.publish(data)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,10 +1,9 @@
|
||||||
import threading
|
import threading
|
||||||
import json
|
import json
|
||||||
from redis.exceptions import ConnectionError
|
|
||||||
from channels.generic.websocket import JsonWebsocketConsumer
|
from channels.generic.websocket import JsonWebsocketConsumer
|
||||||
|
|
||||||
from common.db.utils import close_old_connections
|
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
|
from common.db.utils import safe_db_connection
|
||||||
from .site_msg import SiteMessageUtil
|
from .site_msg import SiteMessageUtil
|
||||||
from .signals_handler import new_site_msg_chan
|
from .signals_handler import new_site_msg_chan
|
||||||
|
|
||||||
|
@ -13,15 +12,13 @@ logger = get_logger(__name__)
|
||||||
|
|
||||||
class SiteMsgWebsocket(JsonWebsocketConsumer):
|
class SiteMsgWebsocket(JsonWebsocketConsumer):
|
||||||
refresh_every_seconds = 10
|
refresh_every_seconds = 10
|
||||||
chan = None
|
|
||||||
|
|
||||||
def connect(self):
|
def connect(self):
|
||||||
user = self.scope["user"]
|
user = self.scope["user"]
|
||||||
if user.is_authenticated:
|
if user.is_authenticated:
|
||||||
self.accept()
|
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()
|
thread.start()
|
||||||
else:
|
else:
|
||||||
self.close()
|
self.close()
|
||||||
|
@ -45,45 +42,18 @@ class SiteMsgWebsocket(JsonWebsocketConsumer):
|
||||||
logger.debug('Send unread count to user: {} {}'.format(user_id, unread_count))
|
logger.debug('Send unread count to user: {} {}'.format(user_id, unread_count))
|
||||||
self.send_json({'type': 'unread_count', 'unread_count': 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)
|
user_id = str(self.scope["user"].id)
|
||||||
self.send_unread_msg_count()
|
|
||||||
|
|
||||||
try:
|
|
||||||
msgs = self.chan.listen()
|
|
||||||
# 开始之前关闭连接,因为server端可能关闭了连接,而 client 还在 CONN_MAX_AGE 中
|
|
||||||
close_old_connections()
|
|
||||||
for message in msgs:
|
|
||||||
if message['type'] != 'message':
|
|
||||||
continue
|
|
||||||
|
|
||||||
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()
|
|
||||||
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()
|
||||||
|
|
||||||
|
new_site_msg_chan.keep_handle_msg(handle_new_site_msg_recv)
|
||||||
|
|
|
@ -6,9 +6,8 @@ from functools import partial
|
||||||
|
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.utils.functional import LazyObject
|
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 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.utils import tmp_to_org
|
||||||
from orgs.models import Organization, OrganizationMember
|
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")
|
logger.debug("Start subscribe for expire orgs mapping from memory")
|
||||||
|
|
||||||
def keep_subscribe_org_mapping():
|
def keep_subscribe_org_mapping():
|
||||||
while True:
|
orgs_mapping_for_memory_pub_sub.keep_handle_msg(
|
||||||
try:
|
lambda org_id: Organization.expire_orgs_mapping()
|
||||||
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()
|
|
||||||
|
|
||||||
t = threading.Thread(target=keep_subscribe_org_mapping)
|
t = threading.Thread(target=keep_subscribe_org_mapping)
|
||||||
t.daemon = True
|
t.daemon = True
|
||||||
|
|
|
@ -143,7 +143,7 @@ class AssetPermissionFilter(PermissionBaseFilter):
|
||||||
if not _nodes:
|
if not _nodes:
|
||||||
return queryset.none()
|
return queryset.none()
|
||||||
|
|
||||||
node = _nodes.get()
|
node = _nodes.first()
|
||||||
|
|
||||||
if not is_query_all:
|
if not is_query_all:
|
||||||
queryset = queryset.filter(nodes=node)
|
queryset = queryset.filter(nodes=node)
|
||||||
|
@ -170,13 +170,13 @@ class AssetPermissionFilter(PermissionBaseFilter):
|
||||||
return queryset
|
return queryset
|
||||||
if not assets:
|
if not assets:
|
||||||
return queryset.none()
|
return queryset.none()
|
||||||
asset = assets.get()
|
assetids = list(assets.values_list('id', flat=True))
|
||||||
|
|
||||||
if not is_query_all:
|
if not is_query_all:
|
||||||
queryset = queryset.filter(assets=asset)
|
queryset = queryset.filter(assets__in=assetids)
|
||||||
return queryset
|
return queryset
|
||||||
inherit_all_nodekeys = set()
|
inherit_all_nodekeys = set()
|
||||||
inherit_nodekeys = asset.nodes.values_list('key', flat=True)
|
inherit_nodekeys = set(assets.values_list('nodes__key', flat=True))
|
||||||
|
|
||||||
for key in inherit_nodekeys:
|
for key in inherit_nodekeys:
|
||||||
ancestor_keys = Node.get_node_ancestor_keys(key, with_self=True)
|
ancestor_keys = Node.get_node_ancestor_keys(key, with_self=True)
|
||||||
|
@ -185,8 +185,8 @@ class AssetPermissionFilter(PermissionBaseFilter):
|
||||||
inherit_all_nodeids = Node.objects.filter(key__in=inherit_all_nodekeys).values_list('id', flat=True)
|
inherit_all_nodeids = Node.objects.filter(key__in=inherit_all_nodekeys).values_list('id', flat=True)
|
||||||
inherit_all_nodeids = list(inherit_all_nodeids)
|
inherit_all_nodeids = list(inherit_all_nodeids)
|
||||||
|
|
||||||
qs1 = queryset.filter(assets=asset).distinct()
|
qs1 = queryset.filter(assets__in=assetids).distinct()
|
||||||
qs2 = queryset.filter(nodes__id__in=inherit_all_nodeids).distinct()
|
qs2 = queryset.filter(nodes__in=inherit_all_nodeids).distinct()
|
||||||
|
|
||||||
qs = UnionQuerySet(qs1, qs2)
|
qs = UnionQuerySet(qs1, qs2)
|
||||||
return qs
|
return qs
|
||||||
|
|
|
@ -32,6 +32,7 @@ class SettingsApi(generics.RetrieveUpdateAPIView):
|
||||||
'radius': serializers.RadiusSettingSerializer,
|
'radius': serializers.RadiusSettingSerializer,
|
||||||
'cas': serializers.CASSettingSerializer,
|
'cas': serializers.CASSettingSerializer,
|
||||||
'sso': serializers.SSOSettingSerializer,
|
'sso': serializers.SSOSettingSerializer,
|
||||||
|
'saml2': serializers.SAML2SettingSerializer,
|
||||||
'clean': serializers.CleaningSerializer,
|
'clean': serializers.CleaningSerializer,
|
||||||
'other': serializers.OtherSettingSerializer,
|
'other': serializers.OtherSettingSerializer,
|
||||||
'sms': serializers.SMSSettingSerializer,
|
'sms': serializers.SMSSettingSerializer,
|
||||||
|
|
|
@ -97,6 +97,7 @@ class Setting(models.Model):
|
||||||
'AUTH_OPENID': [settings.AUTH_BACKEND_OIDC_CODE, settings.AUTH_BACKEND_OIDC_PASSWORD],
|
'AUTH_OPENID': [settings.AUTH_BACKEND_OIDC_CODE, settings.AUTH_BACKEND_OIDC_PASSWORD],
|
||||||
'AUTH_RADIUS': [settings.AUTH_BACKEND_RADIUS],
|
'AUTH_RADIUS': [settings.AUTH_BACKEND_RADIUS],
|
||||||
'AUTH_CAS': [settings.AUTH_BACKEND_CAS],
|
'AUTH_CAS': [settings.AUTH_BACKEND_CAS],
|
||||||
|
'AUTH_SAML2': [settings.AUTH_BACKEND_SAML2],
|
||||||
}
|
}
|
||||||
setting_backends = backends_map[name]
|
setting_backends = backends_map[name]
|
||||||
auth_backends = settings.AUTHENTICATION_BACKENDS
|
auth_backends = settings.AUTHENTICATION_BACKENDS
|
||||||
|
@ -130,6 +131,10 @@ class Setting(models.Model):
|
||||||
def refresh_AUTH_OPENID(cls):
|
def refresh_AUTH_OPENID(cls):
|
||||||
cls.refresh_authentications('AUTH_OPENID')
|
cls.refresh_authentications('AUTH_OPENID')
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def refresh_AUTH_SAML2(cls):
|
||||||
|
cls.refresh_authentications('AUTH_SAML2')
|
||||||
|
|
||||||
def refresh_keycloak_to_openid_if_need(self):
|
def refresh_keycloak_to_openid_if_need(self):
|
||||||
watch_config_names = [
|
watch_config_names = [
|
||||||
'AUTH_OPENID', 'AUTH_OPENID_REALM_NAME', 'AUTH_OPENID_SERVER_URL',
|
'AUTH_OPENID', 'AUTH_OPENID_REALM_NAME', 'AUTH_OPENID_SERVER_URL',
|
||||||
|
|
|
@ -8,3 +8,4 @@ from .wecom import *
|
||||||
from .sso import *
|
from .sso import *
|
||||||
from .base import *
|
from .base import *
|
||||||
from .sms import *
|
from .sms import *
|
||||||
|
from .saml2 import *
|
||||||
|
|
|
@ -14,6 +14,7 @@ class AuthSettingSerializer(serializers.Serializer):
|
||||||
AUTH_FEISHU = serializers.BooleanField(default=False, label=_('FeiShu Auth'))
|
AUTH_FEISHU = serializers.BooleanField(default=False, label=_('FeiShu Auth'))
|
||||||
AUTH_WECOM = serializers.BooleanField(default=False, label=_('WeCom Auth'))
|
AUTH_WECOM = serializers.BooleanField(default=False, label=_('WeCom Auth'))
|
||||||
AUTH_SSO = serializers.BooleanField(default=False, label=_("SSO Auth"))
|
AUTH_SSO = serializers.BooleanField(default=False, label=_("SSO Auth"))
|
||||||
|
AUTH_SAML2 = serializers.BooleanField(default=False, label=_("SAML2 Auth"))
|
||||||
FORGOT_PASSWORD_URL = serializers.CharField(
|
FORGOT_PASSWORD_URL = serializers.CharField(
|
||||||
required=False, allow_blank=True, max_length=1024,
|
required=False, allow_blank=True, max_length=1024,
|
||||||
label=_("Forgot password url")
|
label=_("Forgot password url")
|
||||||
|
|
|
@ -0,0 +1,30 @@
|
||||||
|
|
||||||
|
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_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 Public 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'))
|
|
@ -1,7 +1,7 @@
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
from common.utils.ip import is_ip_address, is_ip_network, is_ip_segment
|
from acls.serializers.rules import ip_group_help_text, ip_group_child_validator
|
||||||
|
|
||||||
|
|
||||||
class SecurityPasswordRuleSerializer(serializers.Serializer):
|
class SecurityPasswordRuleSerializer(serializers.Serializer):
|
||||||
|
@ -27,13 +27,10 @@ class SecurityPasswordRuleSerializer(serializers.Serializer):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def ip_child_validator(ip_child):
|
login_ip_limit_time_help_text = _(
|
||||||
is_valid = is_ip_address(ip_child) \
|
'Unit: minute, If the user has failed to log in for a limited number of times, '
|
||||||
or is_ip_network(ip_child) \
|
'no login is allowed during this time interval.'
|
||||||
or is_ip_segment(ip_child)
|
)
|
||||||
if not is_valid:
|
|
||||||
error = _('IP address invalid: `{}`').format(ip_child)
|
|
||||||
raise serializers.ValidationError(error)
|
|
||||||
|
|
||||||
|
|
||||||
class SecurityAuthSerializer(serializers.Serializer):
|
class SecurityAuthSerializer(serializers.Serializer):
|
||||||
|
@ -47,23 +44,31 @@ class SecurityAuthSerializer(serializers.Serializer):
|
||||||
)
|
)
|
||||||
SECURITY_LOGIN_LIMIT_COUNT = serializers.IntegerField(
|
SECURITY_LOGIN_LIMIT_COUNT = serializers.IntegerField(
|
||||||
min_value=3, max_value=99999,
|
min_value=3, max_value=99999,
|
||||||
label=_('Limit the number of login failures')
|
label=_('Limit the number of user login failures')
|
||||||
)
|
)
|
||||||
SECURITY_LOGIN_LIMIT_TIME = serializers.IntegerField(
|
SECURITY_LOGIN_LIMIT_TIME = serializers.IntegerField(
|
||||||
min_value=5, max_value=99999, required=True,
|
min_value=5, max_value=99999, required=True,
|
||||||
label=_('Block logon interval'),
|
label=_('Block user login interval'),
|
||||||
help_text=_(
|
help_text=login_ip_limit_time_help_text
|
||||||
'Unit: minute, If the user has failed to log in for a limited number of times, '
|
)
|
||||||
'no login is allowed during this time interval.'
|
SECURITY_LOGIN_IP_LIMIT_COUNT = serializers.IntegerField(
|
||||||
)
|
min_value=3, max_value=99999,
|
||||||
|
label=_('Limit the number of IP login failures')
|
||||||
|
)
|
||||||
|
SECURITY_LOGIN_IP_LIMIT_TIME = serializers.IntegerField(
|
||||||
|
min_value=5, max_value=99999, required=True,
|
||||||
|
label=_('Block IP login interval'),
|
||||||
|
help_text=login_ip_limit_time_help_text
|
||||||
|
)
|
||||||
|
SECURITY_LOGIN_IP_WHITE_LIST = serializers.ListField(
|
||||||
|
default=[], label=_('Login IP White List'), allow_empty=True,
|
||||||
|
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator]),
|
||||||
|
help_text=ip_group_help_text
|
||||||
)
|
)
|
||||||
SECURITY_LOGIN_IP_BLACK_LIST = serializers.ListField(
|
SECURITY_LOGIN_IP_BLACK_LIST = serializers.ListField(
|
||||||
default=[], label=_('Login IP Black List'), allow_empty=True,
|
default=[], label=_('Login IP Black List'), allow_empty=True,
|
||||||
child=serializers.CharField(max_length=1024, validators=[ip_child_validator]),
|
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator]),
|
||||||
help_text=_(
|
help_text=ip_group_help_text
|
||||||
'Format for comma-delimited string. Such as: '
|
|
||||||
'192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64'
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
SECURITY_PASSWORD_EXPIRATION_TIME = serializers.IntegerField(
|
SECURITY_PASSWORD_EXPIRATION_TIME = serializers.IntegerField(
|
||||||
min_value=1, max_value=99999, required=True,
|
min_value=1, max_value=99999, required=True,
|
||||||
|
|
|
@ -11,7 +11,6 @@ from jumpserver.utils import current_request
|
||||||
from common.decorator import on_transaction_commit
|
from common.decorator import on_transaction_commit
|
||||||
from common.utils import get_logger, ssh_key_gen
|
from common.utils import get_logger, ssh_key_gen
|
||||||
from common.utils.connection import RedisPubSub
|
from common.utils.connection import RedisPubSub
|
||||||
from common.db.utils import close_old_connections
|
|
||||||
from common.signals import django_ready
|
from common.signals import django_ready
|
||||||
from .models import Setting
|
from .models import Setting
|
||||||
|
|
||||||
|
@ -81,23 +80,9 @@ def subscribe_settings_change(sender, **kwargs):
|
||||||
logger.debug("Start subscribe setting change")
|
logger.debug("Start subscribe setting change")
|
||||||
|
|
||||||
def keep_subscribe_settings_change():
|
def keep_subscribe_settings_change():
|
||||||
while True:
|
setting_pub_sub.keep_handle_msg(
|
||||||
try:
|
lambda name: Setting.refresh_item(name)
|
||||||
sub = setting_pub_sub.subscribe()
|
)
|
||||||
msgs = sub.listen()
|
|
||||||
# 开始之前关闭连接,因为server端可能关闭了连接,而 client 还在 CONN_MAX_AGE 中
|
|
||||||
close_old_connections()
|
|
||||||
for msg in msgs:
|
|
||||||
if msg["type"] != "message":
|
|
||||||
continue
|
|
||||||
item = msg['data'].decode()
|
|
||||||
logger.debug("Found setting change: {}".format(str(item)))
|
|
||||||
Setting.refresh_item(item)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(f'subscribe_settings_change: {e}')
|
|
||||||
Setting.refresh_all_settings()
|
|
||||||
finally:
|
|
||||||
close_old_connections()
|
|
||||||
|
|
||||||
t = threading.Thread(target=keep_subscribe_settings_change)
|
t = threading.Thread(target=keep_subscribe_settings_change)
|
||||||
t.daemon = True
|
t.daemon = True
|
||||||
|
|
|
@ -136,6 +136,10 @@ article ul li:last-child{
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.next:hover {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
/*绑定TOTP*/
|
/*绑定TOTP*/
|
||||||
|
|
||||||
/*版权信息*/
|
/*版权信息*/
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
{% load i18n %}
|
{% load i18n %}
|
||||||
<div class="footer fixed">
|
<div class="footer fixed">
|
||||||
<div class="pull-right">
|
<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">-->
|
<!--<img style="display: none" src="http://www.jumpserver.org/img/evaluate_avatar1.jpg">-->
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
|
|
@ -28,7 +28,6 @@ from ..hands import SystemUser
|
||||||
from ..models import Session
|
from ..models import Session
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'SessionViewSet', 'SessionReplayViewSet', 'SessionJoinValidateAPI'
|
'SessionViewSet', 'SessionReplayViewSet', 'SessionJoinValidateAPI'
|
||||||
]
|
]
|
||||||
|
@ -41,7 +40,7 @@ class SessionViewSet(OrgBulkModelViewSet):
|
||||||
'default': serializers.SessionSerializer,
|
'default': serializers.SessionSerializer,
|
||||||
'display': serializers.SessionDisplaySerializer,
|
'display': serializers.SessionDisplaySerializer,
|
||||||
}
|
}
|
||||||
permission_classes = (IsOrgAdminOrAppUser, )
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
search_fields = [
|
search_fields = [
|
||||||
"user", "asset", "system_user", "remote_addr", "protocol", "is_finished", 'login_from',
|
"user", "asset", "system_user", "remote_addr", "protocol", "is_finished", 'login_from',
|
||||||
]
|
]
|
||||||
|
@ -71,7 +70,8 @@ class SessionViewSet(OrgBulkModelViewSet):
|
||||||
os.chdir(current_dir)
|
os.chdir(current_dir)
|
||||||
return file
|
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):
|
def download(self, request, *args, **kwargs):
|
||||||
session = self.get_object()
|
session = self.get_object()
|
||||||
local_path, url = utils.get_session_replay_url(session)
|
local_path, url = utils.get_session_replay_url(session)
|
||||||
|
@ -102,7 +102,7 @@ class SessionViewSet(OrgBulkModelViewSet):
|
||||||
|
|
||||||
def get_permissions(self):
|
def get_permissions(self):
|
||||||
if self.request.method.lower() in ['get', 'options']:
|
if self.request.method.lower() in ['get', 'options']:
|
||||||
self.permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor, )
|
self.permission_classes = (IsOrgAdminOrAppUser | IsOrgAuditor,)
|
||||||
return super().get_permissions()
|
return super().get_permissions()
|
||||||
|
|
||||||
|
|
||||||
|
@ -119,7 +119,9 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
|
||||||
|
|
||||||
if serializer.is_valid():
|
if serializer.is_valid():
|
||||||
file = serializer.validated_data['file']
|
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:
|
if not name:
|
||||||
msg = "Failed save replay `{}`: {}".format(session_id, err)
|
msg = "Failed save replay `{}`: {}".format(session_id, err)
|
||||||
logger.error(msg)
|
logger.error(msg)
|
||||||
|
@ -137,6 +139,8 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
|
||||||
if session.protocol in ('rdp', 'vnc'):
|
if session.protocol in ('rdp', 'vnc'):
|
||||||
# 需要考虑录像播放和离线播放器的约定,暂时不处理
|
# 需要考虑录像播放和离线播放器的约定,暂时不处理
|
||||||
tp = 'guacamole'
|
tp = 'guacamole'
|
||||||
|
if url.endswith('.cast.gz'):
|
||||||
|
tp = 'asciicast'
|
||||||
|
|
||||||
download_url = reverse('api-terminal:session-replay-download', kwargs={'pk': session.id})
|
download_url = reverse('api-terminal:session-replay-download', kwargs={'pk': session.id})
|
||||||
data = {
|
data = {
|
||||||
|
@ -168,7 +172,7 @@ class SessionReplayViewSet(AsyncApiMixin, viewsets.ViewSet):
|
||||||
|
|
||||||
|
|
||||||
class SessionJoinValidateAPI(views.APIView):
|
class SessionJoinValidateAPI(views.APIView):
|
||||||
permission_classes = (IsAppUser, )
|
permission_classes = (IsAppUser,)
|
||||||
serializer_class = serializers.SessionJoinValidateSerializer
|
serializer_class = serializers.SessionJoinValidateSerializer
|
||||||
|
|
||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
|
|
|
@ -56,26 +56,65 @@ class Session(OrgModelMixin):
|
||||||
upload_to = 'replay'
|
upload_to = 'replay'
|
||||||
ACTIVE_CACHE_KEY_PREFIX = 'SESSION_ACTIVE_{}'
|
ACTIVE_CACHE_KEY_PREFIX = 'SESSION_ACTIVE_{}'
|
||||||
_DATE_START_FIRST_HAS_REPLAY_RDP_SESSION = None
|
_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:
|
:return:
|
||||||
"""
|
"""
|
||||||
suffix = '.replay.gz'
|
|
||||||
if version == 1:
|
|
||||||
suffix = '.gz'
|
|
||||||
date = self.date_start.strftime('%Y-%m-%d')
|
date = self.date_start.strftime('%Y-%m-%d')
|
||||||
return os.path.join(date, str(self.id) + suffix)
|
return os.path.join(date, str(self.id) + suffix)
|
||||||
|
|
||||||
def get_local_path(self, version=2):
|
def get_local_path_by_relative_path(self, rel_path):
|
||||||
rel_path = self.get_rel_replay_path(version=version)
|
"""
|
||||||
if version == 2:
|
2021-12-08/session_id.cast.gz
|
||||||
local_path = os.path.join(self.upload_to, rel_path)
|
:param rel_path:
|
||||||
else:
|
:return: replay/2021-12-08/session_id.cast.gz
|
||||||
local_path = rel_path
|
"""
|
||||||
return local_path
|
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
|
@property
|
||||||
def asset_obj(self):
|
def asset_obj(self):
|
||||||
|
@ -133,8 +172,9 @@ class Session(OrgModelMixin):
|
||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def save_replay_to_storage(self, f):
|
def save_replay_to_storage_with_version(self, f, version=2):
|
||||||
local_path = self.get_local_path()
|
suffix = self.SUFFIX_MAP.get(version, '.cast.gz')
|
||||||
|
local_path = self.get_local_storage_path_by_suffix(suffix)
|
||||||
try:
|
try:
|
||||||
name = default_storage.save(local_path, f)
|
name = default_storage.save(local_path, f)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
|
@ -148,7 +188,7 @@ class Session(OrgModelMixin):
|
||||||
@classmethod
|
@classmethod
|
||||||
def set_sessions_active(cls, session_ids):
|
def set_sessions_active(cls, session_ids):
|
||||||
data = {cls.ACTIVE_CACHE_KEY_PREFIX.format(i): i for i in 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
|
@classmethod
|
||||||
def get_active_sessions(cls):
|
def get_active_sessions(cls):
|
||||||
|
@ -195,7 +235,7 @@ class Session(OrgModelMixin):
|
||||||
for user, asset, system_user in ziped:
|
for user, asset, system_user in ziped:
|
||||||
ip = random_ip()
|
ip = random_ip()
|
||||||
date_start = random_datetime(month_ago, now)
|
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(
|
data = dict(
|
||||||
user=str(user), user_id=user.id,
|
user=str(user), user_id=user.id,
|
||||||
asset=str(asset), asset_id=asset.id,
|
asset=str(asset), asset_id=asset.id,
|
||||||
|
|
|
@ -50,6 +50,7 @@ class SessionDisplaySerializer(SessionSerializer):
|
||||||
|
|
||||||
class ReplaySerializer(serializers.Serializer):
|
class ReplaySerializer(serializers.Serializer):
|
||||||
file = serializers.FileField(allow_empty_file=True)
|
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):
|
class SessionJoinValidateSerializer(serializers.Serializer):
|
||||||
|
|
|
@ -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}')
|
logger.error(f'Session replay not found, may be upload error: {local_path}')
|
||||||
return
|
return
|
||||||
abs_path = default_storage.path(local_path)
|
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)
|
ok, err = server_replay_storage.upload(abs_path, remote_path)
|
||||||
if not ok:
|
if not ok:
|
||||||
logger.error(f'Session replay upload to external error: {err}')
|
logger.error(f'Session replay upload to external error: {err}')
|
||||||
|
|
|
@ -1,30 +1,28 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
import os
|
import os
|
||||||
from itertools import groupby
|
from itertools import groupby, chain
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.files.storage import default_storage
|
from django.core.files.storage import default_storage
|
||||||
from django.utils.translation import ugettext as _
|
|
||||||
|
|
||||||
import jms_storage
|
import jms_storage
|
||||||
|
|
||||||
from common.tasks import send_mail_async
|
from common.utils import get_logger
|
||||||
from common.utils import get_logger, reverse
|
|
||||||
from . import const
|
from . import const
|
||||||
from .models import ReplayStorage, Session, Command
|
from .models import ReplayStorage
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def find_session_replay_local(session):
|
def find_session_replay_local(session):
|
||||||
# 新版本和老版本的文件后缀不同
|
# 存在外部存储上,所有可能的路径名
|
||||||
session_path = session.get_rel_replay_path() # 存在外部存储上的路径
|
session_paths = session.get_all_possible_relative_path()
|
||||||
local_path = session.get_local_path()
|
|
||||||
local_path_v1 = session.get_local_path(version=1)
|
|
||||||
|
|
||||||
# 去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):
|
if default_storage.exists(_local_path):
|
||||||
url = default_storage.url(_local_path)
|
url = default_storage.url(_local_path)
|
||||||
return _local_path, url
|
return _local_path, url
|
||||||
|
@ -32,8 +30,6 @@ def find_session_replay_local(session):
|
||||||
|
|
||||||
|
|
||||||
def download_session_replay(session):
|
def download_session_replay(session):
|
||||||
session_path = session.get_rel_replay_path() # 存在外部存储上的路径
|
|
||||||
local_path = session.get_local_path()
|
|
||||||
replay_storages = ReplayStorage.objects.all()
|
replay_storages = ReplayStorage.objects.all()
|
||||||
configs = {
|
configs = {
|
||||||
storage.name: storage.config
|
storage.name: storage.config
|
||||||
|
@ -45,13 +41,23 @@ def download_session_replay(session):
|
||||||
if not configs:
|
if not configs:
|
||||||
msg = "Not found replay file, and not remote storage set"
|
msg = "Not found replay file, and not remote storage set"
|
||||||
return None, msg
|
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的路径
|
# 保存到storage的路径
|
||||||
target_path = os.path.join(default_storage.base_location, local_path)
|
target_path = os.path.join(default_storage.base_location, local_path)
|
||||||
target_dir = os.path.dirname(target_path)
|
target_dir = os.path.dirname(target_path)
|
||||||
if not os.path.isdir(target_dir):
|
if not os.path.isdir(target_dir):
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
storage = jms_storage.get_multi_object_storage(configs)
|
|
||||||
ok, err = storage.download(session_path, target_path)
|
ok, err = storage.download(session_path, target_path)
|
||||||
if not ok:
|
if not ok:
|
||||||
msg = "Failed download replay file: {}".format(err)
|
msg = "Failed download replay file: {}".format(err)
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
|
|
||||||
from orgs.utils import tmp_to_org, tmp_to_root_org
|
from orgs.utils import tmp_to_org, tmp_to_root_org
|
||||||
from applications.const import AppCategory, AppType
|
from applications.const import AppCategory, AppType
|
||||||
from applications.models import Application
|
from applications.models import Application
|
||||||
|
|
|
@ -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 django.utils.translation import ugettext as _
|
||||||
|
|
||||||
|
from assets.models import Node, Asset, SystemUser
|
||||||
from perms.models import AssetPermission, Action
|
from perms.models import AssetPermission, Action
|
||||||
from orgs.utils import tmp_to_org, tmp_to_root_org
|
from orgs.utils import tmp_to_org, tmp_to_root_org
|
||||||
|
from .base import BaseHandler
|
||||||
|
|
||||||
|
|
||||||
class Handler(BaseHandler):
|
class Handler(BaseHandler):
|
||||||
|
@ -22,17 +20,22 @@ class Handler(BaseHandler):
|
||||||
apply_actions_display = Action.value_to_choices_display(apply_actions)
|
apply_actions_display = Action.value_to_choices_display(apply_actions)
|
||||||
meta_display_values = [apply_actions_display]
|
meta_display_values = [apply_actions_display]
|
||||||
meta_display = dict(zip(meta_display_fields, meta_display_values))
|
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')
|
apply_system_users = self.ticket.meta.get('apply_system_users')
|
||||||
with tmp_to_org(self.ticket.org_id):
|
with tmp_to_org(self.ticket.org_id):
|
||||||
meta_display.update({
|
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_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
|
return meta_display
|
||||||
|
|
||||||
# body
|
# body
|
||||||
def _construct_meta_body_of_open(self):
|
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_assets = self.ticket.meta.get('apply_assets_display', [])
|
||||||
apply_system_users = self.ticket.meta.get('apply_system_users_display', [])
|
apply_system_users = self.ticket.meta.get('apply_system_users_display', [])
|
||||||
apply_actions_display = self.ticket.meta.get('apply_actions_display', [])
|
apply_actions_display = self.ticket.meta.get('apply_actions_display', [])
|
||||||
|
@ -44,6 +47,7 @@ class Handler(BaseHandler):
|
||||||
{}: {},
|
{}: {},
|
||||||
{}: {}
|
{}: {}
|
||||||
'''.format(
|
'''.format(
|
||||||
|
_("Applied node group"), ','.join(apply_nodes),
|
||||||
_("Applied hostname group"), ','.join(apply_assets),
|
_("Applied hostname group"), ','.join(apply_assets),
|
||||||
_("Applied system user group"), ','.join(apply_system_users),
|
_("Applied system user group"), ','.join(apply_system_users),
|
||||||
_("Applied actions"), ','.join(apply_actions_display),
|
_("Applied actions"), ','.join(apply_actions_display),
|
||||||
|
@ -60,6 +64,7 @@ class Handler(BaseHandler):
|
||||||
return asset_permission
|
return asset_permission
|
||||||
|
|
||||||
apply_permission_name = self.ticket.meta.get('apply_permission_name', )
|
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_assets = self.ticket.meta.get('apply_assets', [])
|
||||||
apply_system_users = self.ticket.meta.get('apply_system_users', [])
|
apply_system_users = self.ticket.meta.get('apply_system_users', [])
|
||||||
apply_actions = self.ticket.meta.get('apply_actions', Action.NONE)
|
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):
|
with tmp_to_org(self.ticket.org_id):
|
||||||
asset_permission = AssetPermission.objects.create(**permission_data)
|
asset_permission = AssetPermission.objects.create(**permission_data)
|
||||||
asset_permission.users.add(self.ticket.applicant)
|
asset_permission.users.add(self.ticket.applicant)
|
||||||
|
asset_permission.nodes.set(apply_nodes)
|
||||||
asset_permission.assets.set(apply_assets)
|
asset_permission.assets.set(apply_assets)
|
||||||
asset_permission.system_users.set(apply_system_users)
|
asset_permission.system_users.set(apply_system_users)
|
||||||
|
|
||||||
|
|
|
@ -1,13 +1,11 @@
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from rest_framework import serializers
|
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
from perms.models import ApplicationPermission
|
from perms.models import ApplicationPermission
|
||||||
from applications.const import AppCategory, AppType
|
from applications.const import AppCategory, AppType
|
||||||
from orgs.utils import tmp_to_org
|
from orgs.utils import tmp_to_org
|
||||||
from tickets.models import Ticket
|
from tickets.models import Ticket
|
||||||
from applications.models import Application
|
from applications.models import Application
|
||||||
from assets.models import SystemUser
|
|
||||||
from .common import DefaultPermissionName
|
from .common import DefaultPermissionName
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
from perms.serializers import ActionsField
|
from perms.serializers import ActionsField
|
||||||
from perms.models import AssetPermission
|
from perms.models import AssetPermission
|
||||||
from orgs.utils import tmp_to_org
|
from orgs.utils import tmp_to_org
|
||||||
|
@ -12,23 +11,34 @@ __all__ = [
|
||||||
'ApplySerializer',
|
'ApplySerializer',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
asset_or_node_help_text = _("Select at least one asset or node")
|
||||||
|
|
||||||
|
|
||||||
class ApplySerializer(serializers.Serializer):
|
class ApplySerializer(serializers.Serializer):
|
||||||
apply_permission_name = serializers.CharField(
|
apply_permission_name = serializers.CharField(
|
||||||
max_length=128, default=DefaultPermissionName(), label=_('Apply name')
|
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(
|
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(
|
apply_assets_display = serializers.ListField(
|
||||||
required=False, read_only=True, child=serializers.CharField(),
|
required=False, read_only=True, child=serializers.CharField(),
|
||||||
label=_('Approve assets display'), allow_null=True,
|
label=_('Apply assets display'), allow_null=True,
|
||||||
default=list,
|
default=list
|
||||||
)
|
)
|
||||||
apply_system_users = serializers.ListField(
|
apply_system_users = serializers.ListField(
|
||||||
required=True, allow_null=True, child=serializers.UUIDField(),
|
required=True, allow_null=True, child=serializers.UUIDField(),
|
||||||
label=_('Approve system users')
|
label=_('Apply system users')
|
||||||
)
|
)
|
||||||
apply_system_users_display = serializers.ListField(
|
apply_system_users_display = serializers.ListField(
|
||||||
required=False, read_only=True, child=serializers.CharField(),
|
required=False, read_only=True, child=serializers.CharField(),
|
||||||
|
@ -64,6 +74,12 @@ class ApplySerializer(serializers.Serializer):
|
||||||
))
|
))
|
||||||
|
|
||||||
def validate(self, attrs):
|
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_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')
|
apply_date_expired = attrs['apply_date_expired'].strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,8 @@ from .mixins import UserQuerysetMixin
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'UserResetPasswordApi', 'UserResetPKApi',
|
'UserResetPasswordApi', 'UserResetPKApi',
|
||||||
'UserProfileApi', 'UserUpdatePKApi',
|
'UserProfileApi', 'UserUpdatePKApi',
|
||||||
'UserPasswordApi', 'UserPublicKeyApi'
|
'UserPasswordApi', 'UserSecretKeyApi',
|
||||||
|
'UserPublicKeyApi'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@ -81,6 +82,14 @@ class UserPasswordApi(generics.RetrieveUpdateAPIView):
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
class UserSecretKeyApi(generics.RetrieveUpdateAPIView):
|
||||||
|
permission_classes = (IsAuthenticated,)
|
||||||
|
serializer_class = serializers.UserUpdateSecretKeySerializer
|
||||||
|
|
||||||
|
def get_object(self):
|
||||||
|
return self.request.user
|
||||||
|
|
||||||
|
|
||||||
class UserPublicKeyApi(generics.RetrieveUpdateAPIView):
|
class UserPublicKeyApi(generics.RetrieveUpdateAPIView):
|
||||||
permission_classes = (IsAuthenticated,)
|
permission_classes = (IsAuthenticated,)
|
||||||
serializer_class = serializers.UserUpdatePublicKeySerializer
|
serializer_class = serializers.UserUpdatePublicKeySerializer
|
||||||
|
|
|
@ -207,10 +207,10 @@ class UserResetMFAApi(UserQuerysetMixin, generics.RetrieveAPIView):
|
||||||
user = self.get_object() if kwargs.get('pk') else request.user
|
user = self.get_object() if kwargs.get('pk') else request.user
|
||||||
if user == request.user:
|
if user == request.user:
|
||||||
msg = _("Could not reset self otp, use profile reset instead")
|
msg = _("Could not reset self otp, use profile reset instead")
|
||||||
return Response({"error": msg}, status=401)
|
return Response({"error": msg}, status=400)
|
||||||
|
|
||||||
backends = user.active_mfa_backends_mapper
|
backends = user.active_mfa_backends_mapper
|
||||||
for backend in backends:
|
for backend in backends.values():
|
||||||
if backend.can_disable():
|
if backend.can_disable():
|
||||||
backend.disable()
|
backend.disable()
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
# Generated by Django 3.1.13 on 2021-12-07 08:23
|
||||||
|
|
||||||
|
import common.fields.model
|
||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('users', '0036_user_feishu_id'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='user',
|
||||||
|
name='secret_key',
|
||||||
|
field=common.fields.model.EncryptCharField(blank=True, max_length=256, null=True, verbose_name='Secret key'),
|
||||||
|
),
|
||||||
|
]
|
|
@ -0,0 +1,18 @@
|
||||||
|
# Generated by Django 3.1.13 on 2021-12-09 03:40
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('users', '0037_user_secret_key'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='user',
|
||||||
|
name='source',
|
||||||
|
field=models.CharField(choices=[('local', 'Local'), ('ldap', 'LDAP/AD'), ('openid', 'OpenID'), ('radius', 'Radius'), ('cas', 'CAS'), ('saml2', 'SAML2')], default='local', max_length=30, verbose_name='Source'),
|
||||||
|
),
|
||||||
|
]
|
|
@ -528,6 +528,7 @@ class User(AuthMixin, TokenMixin, RoleMixin, MFAMixin, AbstractUser):
|
||||||
openid = 'openid', 'OpenID'
|
openid = 'openid', 'OpenID'
|
||||||
radius = 'radius', 'Radius'
|
radius = 'radius', 'Radius'
|
||||||
cas = 'cas', 'CAS'
|
cas = 'cas', 'CAS'
|
||||||
|
saml2 = 'saml2', 'SAML2'
|
||||||
|
|
||||||
SOURCE_BACKEND_MAPPING = {
|
SOURCE_BACKEND_MAPPING = {
|
||||||
Source.local: [
|
Source.local: [
|
||||||
|
@ -538,6 +539,7 @@ class User(AuthMixin, TokenMixin, RoleMixin, MFAMixin, AbstractUser):
|
||||||
Source.openid: [settings.AUTH_BACKEND_OIDC_PASSWORD, settings.AUTH_BACKEND_OIDC_CODE],
|
Source.openid: [settings.AUTH_BACKEND_OIDC_PASSWORD, settings.AUTH_BACKEND_OIDC_CODE],
|
||||||
Source.radius: [settings.AUTH_BACKEND_RADIUS],
|
Source.radius: [settings.AUTH_BACKEND_RADIUS],
|
||||||
Source.cas: [settings.AUTH_BACKEND_CAS],
|
Source.cas: [settings.AUTH_BACKEND_CAS],
|
||||||
|
Source.saml2: [settings.AUTH_BACKEND_SAML2],
|
||||||
}
|
}
|
||||||
|
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
|
@ -576,6 +578,9 @@ class User(AuthMixin, TokenMixin, RoleMixin, MFAMixin, AbstractUser):
|
||||||
public_key = fields.EncryptTextField(
|
public_key = fields.EncryptTextField(
|
||||||
blank=True, null=True, verbose_name=_('Public key')
|
blank=True, null=True, verbose_name=_('Public key')
|
||||||
)
|
)
|
||||||
|
secret_key = fields.EncryptCharField(
|
||||||
|
max_length=256, blank=True, null=True, verbose_name=_('Secret key')
|
||||||
|
)
|
||||||
comment = models.TextField(
|
comment = models.TextField(
|
||||||
blank=True, null=True, verbose_name=_('Comment')
|
blank=True, null=True, verbose_name=_('Comment')
|
||||||
)
|
)
|
||||||
|
|
|
@ -53,6 +53,27 @@ class UserUpdatePasswordSerializer(serializers.ModelSerializer):
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdateSecretKeySerializer(serializers.ModelSerializer):
|
||||||
|
new_secret_key = serializers.CharField(required=True, max_length=128, write_only=True)
|
||||||
|
new_secret_key_again = serializers.CharField(required=True, max_length=128, write_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ['new_secret_key', 'new_secret_key_again']
|
||||||
|
|
||||||
|
def validate_new_secret_key_again(self, value):
|
||||||
|
if value != self.initial_data.get('new_secret_key', ''):
|
||||||
|
msg = _('The newly set password is inconsistent')
|
||||||
|
raise serializers.ValidationError(msg)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def update(self, instance, validated_data):
|
||||||
|
new_secret_key = self.validated_data.get('new_secret_key')
|
||||||
|
instance.secret_key = new_secret_key
|
||||||
|
instance.save()
|
||||||
|
return instance
|
||||||
|
|
||||||
|
|
||||||
class UserUpdatePublicKeySerializer(serializers.ModelSerializer):
|
class UserUpdatePublicKeySerializer(serializers.ModelSerializer):
|
||||||
public_key_comment = serializers.CharField(
|
public_key_comment = serializers.CharField(
|
||||||
source='get_public_key_comment', required=False, read_only=True, max_length=128
|
source='get_public_key_comment', required=False, read_only=True, max_length=128
|
||||||
|
@ -165,7 +186,6 @@ class UserPKUpdateSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
|
|
||||||
class ChangeUserPasswordSerializer(serializers.ModelSerializer):
|
class ChangeUserPasswordSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = User
|
model = User
|
||||||
fields = ['password']
|
fields = ['password']
|
||||||
|
|
|
@ -10,6 +10,7 @@ from django.db.models.signals import post_save
|
||||||
|
|
||||||
from jms_oidc_rp.signals import openid_create_or_update_user
|
from jms_oidc_rp.signals import openid_create_or_update_user
|
||||||
|
|
||||||
|
from authentication.backends.saml2.signals import saml2_create_or_update_user
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
from .signals import post_user_create
|
from .signals import post_user_create
|
||||||
from .models import User, UserPasswordHistory
|
from .models import User, UserPasswordHistory
|
||||||
|
@ -18,6 +19,28 @@ from .models import User, UserPasswordHistory
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
|
||||||
|
def user_authenticated_handle(user, created, source, attrs=None, **kwargs):
|
||||||
|
if created and settings.ONLY_ALLOW_EXIST_USER_AUTH:
|
||||||
|
user.delete()
|
||||||
|
raise PermissionDenied(f'Not allow non-exist user auth: {user.username}')
|
||||||
|
if created:
|
||||||
|
user.source = source
|
||||||
|
user.save()
|
||||||
|
elif not created and settings.AUTH_SAML2_ALWAYS_UPDATE_USER:
|
||||||
|
attr_whitelist = ('user', 'username', 'email', 'phone', 'comment')
|
||||||
|
logger.debug(
|
||||||
|
"Receive saml2 user updated signal: {}, "
|
||||||
|
"Update user info: {},"
|
||||||
|
"(Update only properties in the whitelist. [{}])"
|
||||||
|
"".format(user, str(attrs), ','.join(attr_whitelist))
|
||||||
|
)
|
||||||
|
if attrs is not None:
|
||||||
|
for key, value in attrs.items():
|
||||||
|
if key in attr_whitelist and value:
|
||||||
|
setattr(user, key, value)
|
||||||
|
user.save()
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save, sender=User)
|
@receiver(post_save, sender=User)
|
||||||
def save_passwd_change(sender, instance: User, **kwargs):
|
def save_passwd_change(sender, instance: User, **kwargs):
|
||||||
passwds = UserPasswordHistory.objects.filter(user=instance).order_by('-date_created')\
|
passwds = UserPasswordHistory.objects.filter(user=instance).order_by('-date_created')\
|
||||||
|
@ -44,12 +67,14 @@ def on_user_create(sender, user=None, **kwargs):
|
||||||
|
|
||||||
@receiver(cas_user_authenticated)
|
@receiver(cas_user_authenticated)
|
||||||
def on_cas_user_authenticated(sender, user, created, **kwargs):
|
def on_cas_user_authenticated(sender, user, created, **kwargs):
|
||||||
if created and settings.ONLY_ALLOW_EXIST_USER_AUTH:
|
source = user.Source.cas.value
|
||||||
user.delete()
|
user_authenticated_handle(user, created, source)
|
||||||
raise PermissionDenied(f'Not allow non-exist user auth: {user.username}')
|
|
||||||
if created:
|
|
||||||
user.source = user.Source.cas.value
|
@receiver(saml2_create_or_update_user)
|
||||||
user.save()
|
def on_saml2_create_or_update_user(sender, user, created, attrs, **kwargs):
|
||||||
|
source = user.Source.saml2.value
|
||||||
|
user_authenticated_handle(user, created, source, attrs, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
@receiver(populate_user)
|
@receiver(populate_user)
|
||||||
|
|
|
@ -7,36 +7,8 @@
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="verify">{% trans 'Please enter the password of' %} {% trans 'account' %} <span>{{ user.username }}</span> {% trans 'to complete the binding operation' %}</div>
|
<hr style="width: 500px; margin: 10px auto auto;">
|
||||||
<hr style="width: 500px; margin: auto; margin-top: 10px;">
|
<a type="submit" class="next" href="{% url 'authentication:user-otp-enable-install-app' %}" >
|
||||||
<form id="verify-form" class="" role="form" method="post" action="">
|
{% trans 'Next' %}
|
||||||
{% csrf_token %}
|
</a>
|
||||||
<div class="form-input">
|
|
||||||
<input id="password" type="password" class="" placeholder="{% trans 'Password' %}" required="" autofocus="autofocus">
|
|
||||||
<input id="password-hidden" type="text" style="display:none" name="{{ form.password.html_name }}">
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="next" onclick="doVerify();return false;">{% trans 'Next' %}</button>
|
|
||||||
{% if 'password' in form.errors %}
|
|
||||||
<p class="red-fonts">{{ form.password.errors.as_text }}</p>
|
|
||||||
{% endif %}
|
|
||||||
</form>
|
|
||||||
<script type="text/javascript" src="/static/js/plugins/jsencrypt/jsencrypt.min.js"></script>
|
|
||||||
<script>
|
|
||||||
function encryptLoginPassword(password, rsaPublicKey) {
|
|
||||||
var jsencrypt = new JSEncrypt(); //加密对象
|
|
||||||
jsencrypt.setPublicKey(rsaPublicKey); // 设置密钥
|
|
||||||
return jsencrypt.encrypt(password); //加密
|
|
||||||
}
|
|
||||||
function doVerify() {
|
|
||||||
//公钥加密
|
|
||||||
var rsaPublicKey = "{{ rsa_public_key }}"
|
|
||||||
var password = $('#password').val(); //明文密码
|
|
||||||
var passwordEncrypted = encryptLoginPassword(password, rsaPublicKey)
|
|
||||||
$('#password-hidden').val(passwordEncrypted); //返回给密码输入input
|
|
||||||
$('#verify-form').submit();//post提交
|
|
||||||
}
|
|
||||||
|
|
||||||
$(document).ready(function () {
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
|
@ -16,12 +16,12 @@
|
||||||
|
|
||||||
<div id="qr_code"></div>
|
<div id="qr_code"></div>
|
||||||
<div style="display: block; margin: 0">Secret: {{ otp_secret_key }}</div>
|
<div style="display: block; margin: 0">Secret: {{ otp_secret_key }}</div>
|
||||||
<form class="" role="form" method="post" action="">
|
<form id="bind-form" class="" role="form" method="post" action="">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="form-input">
|
<div class="form-input">
|
||||||
<input type="text" class="" name="otp_code" placeholder="{% trans 'Six figures' %}" required="">
|
<input type="text" class="" name="otp_code" placeholder="{% trans 'Six figures' %}" required="">
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="next">{% trans 'Next' %}</button>
|
<a type="submit" class="next button" onclick="submitForm()">{% trans 'Next' %}</a>
|
||||||
{% if 'otp_code' in form.errors %}
|
{% if 'otp_code' in form.errors %}
|
||||||
<p style="color: #ed5565">{{ form.otp_code.errors.as_text }}</p>
|
<p style="color: #ed5565">{{ form.otp_code.errors.as_text }}</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
@ -33,6 +33,10 @@
|
||||||
$('.change-color li:eq(1) i').css('color', '#1ab394');
|
$('.change-color li:eq(1) i').css('color', '#1ab394');
|
||||||
$('.change-color li:eq(2) i').css('color', '#1ab394');
|
$('.change-color li:eq(2) i').css('color', '#1ab394');
|
||||||
|
|
||||||
|
function submitForm() {
|
||||||
|
$('#bind-form').submit()
|
||||||
|
}
|
||||||
|
|
||||||
$(document).ready(function() {
|
$(document).ready(function() {
|
||||||
// 生成用户绑定otp的二维码
|
// 生成用户绑定otp的二维码
|
||||||
var qrcode = new QRCode(document.getElementById('qr_code'), {
|
var qrcode = new QRCode(document.getElementById('qr_code'), {
|
||||||
|
|
|
@ -22,6 +22,7 @@ router.register(r'connection-token', auth_api.UserConnectionTokenViewSet, 'conne
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('profile/', api.UserProfileApi.as_view(), name='user-profile'),
|
path('profile/', api.UserProfileApi.as_view(), name='user-profile'),
|
||||||
path('profile/password/', api.UserPasswordApi.as_view(), name='user-password'),
|
path('profile/password/', api.UserPasswordApi.as_view(), name='user-password'),
|
||||||
|
path('profile/secret-key/', api.UserSecretKeyApi.as_view(), name='user-secret-key'),
|
||||||
path('profile/public-key/', api.UserPublicKeyApi.as_view(), name='user-public-key'),
|
path('profile/public-key/', api.UserPublicKeyApi.as_view(), name='user-public-key'),
|
||||||
path('profile/mfa/reset/', api.UserResetMFAApi.as_view(), name='my-mfa-reset'),
|
path('profile/mfa/reset/', api.UserResetMFAApi.as_view(), name='my-mfa-reset'),
|
||||||
path('users/<uuid:pk>/mfa/reset/', api.UserResetMFAApi.as_view(), name='user-reset-mfa'),
|
path('users/<uuid:pk>/mfa/reset/', api.UserResetMFAApi.as_view(), name='user-reset-mfa'),
|
||||||
|
|
|
@ -11,7 +11,7 @@ from django.conf import settings
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
|
|
||||||
from common.tasks import send_mail_async
|
from common.tasks import send_mail_async
|
||||||
from common.utils import reverse, get_object_or_none
|
from common.utils import reverse, get_object_or_none, ip
|
||||||
from .models import User
|
from .models import User
|
||||||
|
|
||||||
logger = logging.getLogger('jumpserver')
|
logger = logging.getLogger('jumpserver')
|
||||||
|
@ -180,33 +180,37 @@ class BlockGlobalIpUtilBase:
|
||||||
self.ip = ip
|
self.ip = ip
|
||||||
self.limit_key = self.LIMIT_KEY_TMPL.format(ip)
|
self.limit_key = self.LIMIT_KEY_TMPL.format(ip)
|
||||||
self.block_key = self.BLOCK_KEY_TMPL.format(ip)
|
self.block_key = self.BLOCK_KEY_TMPL.format(ip)
|
||||||
self.key_ttl = int(settings.SECURITY_LOGIN_LIMIT_TIME) * 60
|
self.key_ttl = int(settings.SECURITY_LOGIN_IP_LIMIT_TIME) * 60
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def ip_in_black_list(self):
|
def ip_in_black_list(self):
|
||||||
return self.ip in settings.SECURITY_LOGIN_IP_BLACK_LIST
|
return ip.contains_ip(self.ip, settings.SECURITY_LOGIN_IP_BLACK_LIST)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ip_in_white_list(self):
|
||||||
|
return ip.contains_ip(self.ip, settings.SECURITY_LOGIN_IP_WHITE_LIST)
|
||||||
|
|
||||||
def set_block_if_need(self):
|
def set_block_if_need(self):
|
||||||
if not self.ip_in_black_list:
|
if self.ip_in_white_list or self.ip_in_black_list:
|
||||||
return
|
return
|
||||||
count = cache.get(self.limit_key, 0)
|
count = cache.get(self.limit_key, 0)
|
||||||
count += 1
|
count += 1
|
||||||
cache.set(self.limit_key, count, self.key_ttl)
|
cache.set(self.limit_key, count, self.key_ttl)
|
||||||
|
|
||||||
limit_count = settings.SECURITY_LOGIN_LIMIT_COUNT
|
limit_count = settings.SECURITY_LOGIN_IP_LIMIT_COUNT
|
||||||
if count < limit_count:
|
if count < limit_count:
|
||||||
return
|
return
|
||||||
cache.set(self.block_key, True, self.key_ttl)
|
cache.set(self.block_key, True, self.key_ttl)
|
||||||
|
|
||||||
def clean_block_if_need(self):
|
def clean_block_if_need(self):
|
||||||
if not self.ip_in_black_list:
|
|
||||||
return
|
|
||||||
cache.delete(self.limit_key)
|
cache.delete(self.limit_key)
|
||||||
cache.delete(self.block_key)
|
cache.delete(self.block_key)
|
||||||
|
|
||||||
def is_block(self):
|
def is_block(self):
|
||||||
if not self.ip_in_black_list:
|
if self.ip_in_white_list:
|
||||||
return False
|
return False
|
||||||
|
if self.ip_in_black_list:
|
||||||
|
return True
|
||||||
return bool(cache.get(self.block_key))
|
return bool(cache.get(self.block_key))
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -6,10 +6,12 @@ from django.utils.translation import ugettext as _
|
||||||
from django.views.generic.base import TemplateView
|
from django.views.generic.base import TemplateView
|
||||||
from django.views.generic.edit import FormView
|
from django.views.generic.edit import FormView
|
||||||
from django.contrib.auth import logout as auth_logout
|
from django.contrib.auth import logout as auth_logout
|
||||||
|
from django.shortcuts import redirect
|
||||||
from django.http.response import HttpResponseRedirect
|
from django.http.response import HttpResponseRedirect
|
||||||
|
|
||||||
from authentication.mixins import AuthMixin
|
from authentication.mixins import AuthMixin
|
||||||
from authentication.mfa import MFAOtp, otp_failed_msg
|
from authentication.mfa import MFAOtp, otp_failed_msg
|
||||||
|
from authentication.errors import SessionEmptyError
|
||||||
from common.utils import get_logger, FlashMessageUtil
|
from common.utils import get_logger, FlashMessageUtil
|
||||||
from common.mixins.views import PermissionsMixin
|
from common.mixins.views import PermissionsMixin
|
||||||
from common.permissions import IsValidUser
|
from common.permissions import IsValidUser
|
||||||
|
@ -30,11 +32,15 @@ __all__ = [
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class UserOtpEnableStartView(UserVerifyPasswordView):
|
class UserOtpEnableStartView(AuthMixin, TemplateView):
|
||||||
template_name = 'users/user_otp_check_password.html'
|
template_name = 'users/user_otp_check_password.html'
|
||||||
|
|
||||||
def get_success_url(self):
|
def get(self, request, *args, **kwargs):
|
||||||
return reverse('authentication:user-otp-enable-install-app')
|
try:
|
||||||
|
self.get_user_from_session()
|
||||||
|
except SessionEmptyError:
|
||||||
|
return redirect('authentication:login') + '?_=otp_enable_start'
|
||||||
|
return super().get(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class UserOtpEnableInstallAppView(TemplateView):
|
class UserOtpEnableInstallAppView(TemplateView):
|
||||||
|
|
1
jms
1
jms
|
@ -113,7 +113,6 @@ def compile_i81n_file():
|
||||||
def upgrade_db():
|
def upgrade_db():
|
||||||
collect_static()
|
collect_static()
|
||||||
perform_db_migrate()
|
perform_db_migrate()
|
||||||
collect_static()
|
|
||||||
|
|
||||||
|
|
||||||
def prepare():
|
def prepare():
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
gcc make python3-dev python3 libffi-dev mariadb-dev libc-dev libffi-dev krb5-dev openldap-dev jpeg-dev linux-headers sshpass openssh-client
|
gcc make python3-dev python3 libffi-dev mariadb-dev libc-dev krb5-dev openldap-dev jpeg-dev linux-headers sshpass openssh-client build-base libressl libffi-dev libressl-dev libxslt-dev libxml2-dev xmlsec-dev xmlsec
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
g++ make iputils-ping default-libmysqlclient-dev libpq-dev libffi-dev libldap2-dev libsasl2-dev sshpass
|
g++ make iputils-ping default-libmysqlclient-dev libpq-dev libffi-dev libldap2-dev libsasl2-dev sshpass pkg-config libxml2-dev libxmlsec1-dev libxmlsec1-openssl
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
echo "安装依赖"
|
echo "安装依赖"
|
||||||
brew install libtiff libjpeg webp little-cms2 openssl gettext git git-lfs mysql
|
brew install libtiff libjpeg webp little-cms2 openssl gettext git git-lfs mysql libxml2 libxmlsec1 pkg-config
|
||||||
|
|
||||||
echo "安装依赖的插件"
|
echo "安装依赖的插件"
|
||||||
git lfs install
|
git lfs install
|
||||||
|
|
|
@ -95,7 +95,7 @@ python-cas==1.5.0
|
||||||
ipython
|
ipython
|
||||||
huaweicloud-sdk-python==1.0.21
|
huaweicloud-sdk-python==1.0.21
|
||||||
django-redis==4.11.0
|
django-redis==4.11.0
|
||||||
python-redis-lock==3.5.0
|
python-redis-lock==3.7.0
|
||||||
jumpserver-django-oidc-rp==0.3.7.8
|
jumpserver-django-oidc-rp==0.3.7.8
|
||||||
django-mysql==3.9.0
|
django-mysql==3.9.0
|
||||||
gmssl==3.2.1
|
gmssl==3.2.1
|
||||||
|
@ -120,3 +120,7 @@ psycopg2-binary==2.9.1
|
||||||
alibabacloud_dysmsapi20170525==2.0.2
|
alibabacloud_dysmsapi20170525==2.0.2
|
||||||
geoip2==4.4.0
|
geoip2==4.4.0
|
||||||
html2text==2020.1.16
|
html2text==2020.1.16
|
||||||
|
python-novaclient==11.0.1
|
||||||
|
pyzipper==0.3.5
|
||||||
|
python3-saml==1.12.0
|
||||||
|
python-keystoneclient==4.3.0
|
|
@ -1 +1 @@
|
||||||
gcc-c++ sshpass mariadb-devel openldap-devel
|
gcc-c++ sshpass mariadb-devel openldap-devel libxml2-devel xmlsec1-devel xmlsec1-openssl-devel libtool-ltdl-devel
|
||||||
|
|
Loading…
Reference in New Issue