Compare commits
189 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
06931551d0 | ||
|
3aff1daaf2 | ||
|
918859cc62 | ||
|
9f98f71210 | ||
|
116c04f8b1 | ||
|
4b36577b00 | ||
|
f208be9126 | ||
|
2b9c0fdca8 | ||
|
04d025c68b | ||
|
7f1e769377 | ||
|
c76b074893 | ||
|
54f7a59a91 | ||
|
25cb1fc19a | ||
|
6a997bfd46 | ||
|
68076f58eb | ||
|
e24aa2d900 | ||
|
9dad2c08a5 | ||
|
8ede613488 | ||
|
f46a30488a | ||
|
b06c035cce | ||
|
730c34b2a4 | ||
|
c38f1e9b8c | ||
|
a450fe3eef | ||
|
e9c55a0853 | ||
|
f560fc459b | ||
|
d4f266de66 | ||
|
3e491d33c6 | ||
|
77e507fab7 | ||
|
9d5b9c4ded | ||
|
a0830f0440 | ||
|
3de75285de | ||
|
cde46c5765 | ||
|
f325970089 | ||
|
f6996363e3 | ||
|
90aa6c272d | ||
|
2964b34087 | ||
|
625e4eecf4 | ||
|
522be82a31 | ||
|
ccce143f85 | ||
|
01431b2230 | ||
|
7a92aa8dff | ||
|
2b580067a2 | ||
|
500a11612c | ||
|
64fc4d082e | ||
|
cf507d204b | ||
|
fd7242dbba | ||
|
9a712ca489 | ||
|
e44e1dcf2a | ||
|
fce96753c5 | ||
|
77efe7583d | ||
|
1cbe9bfc30 | ||
|
2e7afa9c35 | ||
|
a58507f5a6 | ||
|
1989b235fe | ||
|
21b047b307 | ||
|
2daad88159 | ||
|
7c86513b0c | ||
|
4b41e6c5b9 | ||
|
684fea69d0 | ||
|
85e2ba0b0f | ||
|
3fff44dde5 | ||
|
8b2b058450 | ||
|
f0305415ae | ||
|
ea84a29350 | ||
|
6c5969c5ea | ||
|
f267891f19 | ||
|
d1167650a3 | ||
|
f7c8fb8d9d | ||
|
e780afe18c | ||
|
aadfa7b70c | ||
|
73d5a1be69 | ||
|
3cb22172b1 | ||
|
f42176299d | ||
|
edcfd5d8f2 | ||
|
3697227f7a | ||
|
11cbfbc91d | ||
|
4518959bf9 | ||
|
4f1d345256 | ||
|
7fc9f73512 | ||
|
5c3dfeb3af | ||
|
ca4626879d | ||
|
a0065ade42 | ||
|
a47cdc9a00 | ||
|
c07914d568 | ||
|
df94afdfd0 | ||
|
b4f88e154c | ||
|
e4270f724b | ||
|
e9a27fd833 | ||
|
9865d54f5c | ||
|
8453052d80 | ||
|
e0d5638c17 | ||
|
44adbe71ed | ||
|
246efe430d | ||
|
80ca45c6ea | ||
|
dfe61667cb | ||
|
d9a3b0152b | ||
|
6dcdc9766a | ||
|
a65d3d1054 | ||
|
831b6786c5 | ||
|
b4e2550911 | ||
|
60019f3cf4 | ||
|
d4f1793675 | ||
|
b2c171c39c | ||
|
35dd1dc4e1 | ||
|
bc64a9f8f6 | ||
|
65463fee6c | ||
|
8187fb548f | ||
|
5bd55d1fa8 | ||
|
42de4e6fd0 | ||
|
970b7d557a | ||
|
58cdcbe192 | ||
|
0ffa9578cf | ||
|
903554533b | ||
|
5010d2ecbd | ||
|
cc99a936a6 | ||
|
fd54783d48 | ||
|
af9845a012 | ||
|
d663c43f6d | ||
|
b9b852123e | ||
|
0d4d2bb3c4 | ||
|
1bb76e5d60 | ||
|
bf898ff34b | ||
|
0a35ee18f4 | ||
|
2e764f7ee7 | ||
|
d91d1a127e | ||
|
fef25da35c | ||
|
f3d6d23c3e | ||
|
88c1d09c8f | ||
|
12febf3723 | ||
|
c77a765ae9 | ||
|
6daf4e1b03 | ||
|
2a66df55b0 | ||
|
0f783cfaf6 | ||
|
afe447ada7 | ||
|
981f39799a | ||
|
60084d499a | ||
|
583ca4d635 | ||
|
3937d1eb65 | ||
|
c943b9ee9b | ||
|
d78deafc0c | ||
|
2bdaf4a52e | ||
|
d065a1f97f | ||
|
ba446b8a5c | ||
|
73467a39d9 | ||
|
96276b8cac | ||
|
d17271da2e | ||
|
dd16d52c95 | ||
|
eec3006b35 | ||
|
35c6d80c8d | ||
|
88a3d35784 | ||
|
712f57940c | ||
|
2ad65039f3 | ||
|
1940fcca87 | ||
|
e4f959cb69 | ||
|
8ff77626d0 | ||
|
ea4dda0fca | ||
|
5ffea2339e | ||
|
a8038f8fe9 | ||
|
e7ef29c4ad | ||
|
884f41d2f8 | ||
|
7e95b1261a | ||
|
6daf9cbfa3 | ||
|
31a5337ddf | ||
|
5bb44385b1 | ||
|
66ef639956 | ||
|
f6fd01d1e5 | ||
|
f50f00f464 | ||
|
1b4fe6e450 | ||
|
5289aa92eb | ||
|
d9af1254a4 | ||
|
94dfb8bc44 | ||
|
3243cb98ad | ||
|
67d44805ce | ||
|
22b42fa8b6 | ||
|
b0ff8ba1be | ||
|
1611f795d1 | ||
|
440b178232 | ||
|
42c898cfea | ||
|
1564f6e56c | ||
|
993cd40c41 | ||
|
0ef18ee2f9 | ||
|
a616e42432 | ||
|
cd8922237f | ||
|
4f3f22e6d3 | ||
|
44a7a4659f | ||
|
2b507206e6 | ||
|
b6ed5b14f2 | ||
|
ce2b657ab3 | ||
|
65bbb216fc |
71
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ dev ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ dev ]
|
||||
schedule:
|
||||
- cron: '32 12 * * 5'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'go', 'javascript' ]
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||
# Learn more:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
6
.github/workflows/go.yml
vendored
@@ -16,7 +16,7 @@ jobs:
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15
|
||||
go-version: 1.16
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
@@ -30,7 +30,9 @@ jobs:
|
||||
- name: Build
|
||||
run: |
|
||||
cd server
|
||||
go build -v -o anylink -ldflags "-X main.COMMIT_ID=`git rev-parse HEAD`"
|
||||
mkdir ui
|
||||
touch ui/index.html
|
||||
go build -v -o anylink -ldflags "-X main.CommitId=`git rev-parse HEAD`"
|
||||
./anylink tool -v
|
||||
|
||||
- name: Test coverage
|
||||
|
2
.gitignore
vendored
@@ -1,5 +1,5 @@
|
||||
# Binaries for programs and plugins
|
||||
.idea/
|
||||
anylink-deploy
|
||||
ui
|
||||
anylink-deploy.tar.gz
|
||||
|
||||
|
25
Dockerfile
@@ -2,24 +2,23 @@
|
||||
FROM node:lts-alpine as builder_node
|
||||
WORKDIR /web
|
||||
COPY ./web /web
|
||||
RUN npx browserslist@latest --update-db \
|
||||
&& npm install \
|
||||
&& npm run build \
|
||||
RUN yarn install \
|
||||
&& yarn run build \
|
||||
&& ls /web/ui
|
||||
|
||||
# server
|
||||
FROM golang:alpine as builder_golang
|
||||
FROM golang:1.17-alpine as builder_golang
|
||||
#TODO 本地打包时使用镜像
|
||||
#ENV GOPROXY=https://goproxy.io
|
||||
ENV GOPROXY=https://goproxy.io
|
||||
ENV GOOS=linux
|
||||
WORKDIR /anylink
|
||||
COPY . /anylink
|
||||
COPY --from=builder_node /web/ui /anylink/server/ui
|
||||
|
||||
#TODO 本地打包时使用镜像
|
||||
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
|
||||
RUN apk add --no-cache git
|
||||
RUN cd /anylink/server;go build -o anylink -ldflags "-X main.COMMIT_ID=$(git rev-parse HEAD)" \
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
|
||||
RUN apk add --no-cache git gcc musl-dev
|
||||
RUN cd /anylink/server;go mod tidy;go build -o anylink -ldflags "-X main.CommitId=$(git rev-parse HEAD)" \
|
||||
&& /anylink/server/anylink tool -v
|
||||
|
||||
# anylink
|
||||
@@ -29,14 +28,16 @@ LABEL maintainer="github.com/bjdgyc"
|
||||
ENV IPV4_CIDR="192.168.10.0/24"
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder_node /web/ui /app/ui
|
||||
COPY --from=builder_golang /anylink/server/anylink /app/
|
||||
COPY ./server/conf /app/conf
|
||||
COPY ./server/files /app/files
|
||||
COPY docker_entrypoint.sh /app/
|
||||
|
||||
COPY ./server/bridge-init.sh /app/
|
||||
COPY ./server/conf /app/conf
|
||||
COPY ./LICENSE /app/LICENSE
|
||||
|
||||
|
||||
#TODO 本地打包时使用镜像
|
||||
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
|
||||
RUN apk add --no-cache bash iptables \
|
||||
&& chmod +x /app/docker_entrypoint.sh \
|
||||
&& ls /app
|
||||
|
674
LICENSE
@@ -1,21 +1,661 @@
|
||||
MIT License
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (c) 2020 bjdgyc
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
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.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
235
README.md
@@ -5,10 +5,11 @@
|
||||
[](https://goreportcard.com/report/github.com/bjdgyc/anylink)
|
||||
[](https://codecov.io/gh/bjdgyc/anylink)
|
||||

|
||||

|
||||

|
||||
[](https://hub.docker.com/r/bjdgyc/anylink)
|
||||

|
||||
|
||||
AnyLink 是一个企业级远程办公sslvpn的软件,可以支持多人同时在线使用。
|
||||
AnyLink 是一个企业级远程办公 sslvpn 的软件,可以支持多人同时在线使用。
|
||||
|
||||
## Repo
|
||||
|
||||
@@ -21,23 +22,41 @@ AnyLink 是一个企业级远程办公sslvpn的软件,可以支持多人同时
|
||||
AnyLink 基于 [ietf-openconnect](https://tools.ietf.org/html/draft-mavrogiannopoulos-openconnect-02)
|
||||
协议开发,并且借鉴了 [ocserv](http://ocserv.gitlab.io/www/index.html) 的开发思路,使其可以同时兼容 AnyConnect 客户端。
|
||||
|
||||
AnyLink 使用TLS/DTLS进行数据加密,因此需要RSA或ECC证书,可以通过 Let's Encrypt 和 TrustAsia 申请免费的SSL证书。
|
||||
AnyLink 使用 TLS/DTLS 进行数据加密,因此需要 RSA 或 ECC 证书,可以通过 Let's Encrypt 和 TrustAsia 申请免费的 SSL 证书。
|
||||
|
||||
AnyLink 服务端仅在CentOS 7、Ubuntu 18.04测试通过,如需要安装在其他系统,需要服务端支持tun/tap功能、ip设置命令。
|
||||
AnyLink 服务端仅在 CentOS 7、Ubuntu 18.04 测试通过,如需要安装在其他系统,需要服务端支持 tun/tap 功能、ip 设置命令。
|
||||
|
||||
## Screenshot
|
||||
|
||||

|
||||

|
||||
|
||||
## Donate
|
||||
|
||||
> 如果您觉得 anylink 对你有帮助,欢迎给我们打赏,也是帮助 anylink 更好的发展。
|
||||
>
|
||||
> [查看打赏列表](doc/README.md)
|
||||
|
||||
<p>
|
||||
<img src="doc/screenshot/wxpay2.png" width="400" />
|
||||
</p>
|
||||
|
||||
## Installation
|
||||
|
||||
> 没有编程基础的同学建议直接下载release包,从下面的地址下载 anylink-deploy.tar.gz
|
||||
> 没有编程基础的同学建议直接下载 release 包,从下面的地址下载 anylink-deploy.tar.gz
|
||||
>
|
||||
> https://github.com/bjdgyc/anylink/releases
|
||||
|
||||
> 升级 go version = 1.15
|
||||
### 使用问题
|
||||
|
||||
> 对于测试环境,可以使用 vpn.test.vqilu.cn 绑定host进行测试
|
||||
>
|
||||
> 需要提前安装好 golang 和 nodejs
|
||||
> 对于线上环境,必须申请安全的 https 证书,不支持私有证书连接
|
||||
>
|
||||
> 客户端请使用群共享文件的版本,其他版本没有测试过,不保证使用正常
|
||||
|
||||
### 自行编译安装
|
||||
|
||||
> 需要提前安装好 golang >= 1.17 和 nodejs >= 14.x 和 yarn >= v1.22.x
|
||||
|
||||
```shell
|
||||
git clone https://github.com/bjdgyc/anylink.git
|
||||
@@ -47,35 +66,42 @@ sh build.sh
|
||||
|
||||
# 注意使用root权限运行
|
||||
cd anylink-deploy
|
||||
sudo ./anylink --conf="conf/server.toml"
|
||||
sudo ./anylink
|
||||
|
||||
# 默认管理后台访问地址
|
||||
# http://host:8800
|
||||
# 默认账号密码
|
||||
# https://host:8800
|
||||
# 默认账号 密码
|
||||
# admin 123456
|
||||
|
||||
```
|
||||
|
||||
## Feature
|
||||
|
||||
- [x] IP分配(实现IP、MAC映射信息的持久化)
|
||||
- [x] TLS-TCP通道
|
||||
- [x] DTLS-UDP通道
|
||||
- [x] 兼容AnyConnect
|
||||
- [x] 基于tun设备的nat访问模式
|
||||
- [x] 基于tap设备的桥接访问模式
|
||||
- [x] IP 分配(实现 IP、MAC 映射信息的持久化)
|
||||
- [x] TLS-TCP 通道
|
||||
- [x] DTLS-UDP 通道
|
||||
- [x] 兼容 AnyConnect
|
||||
- [x] 兼容 OpenConnect
|
||||
- [x] 基于 tun 设备的 nat 访问模式
|
||||
- [x] 基于 tap 设备的桥接访问模式
|
||||
- [x] 基于 macvtap 设备的桥接访问模式
|
||||
- [x] 支持 [proxy protocol v1](http://www.haproxy.org/download/2.2/doc/proxy-protocol.txt) 协议
|
||||
- [x] 用户组支持
|
||||
- [x] 多用户支持
|
||||
- [x] TOTP令牌支持
|
||||
- [x] TOTP令牌开关
|
||||
- [x] 流量控制
|
||||
- [x] 用户策略支持
|
||||
- [x] TOTP 令牌支持
|
||||
- [x] TOTP 令牌开关
|
||||
- [x] 流量速率限制
|
||||
- [x] 后台管理界面
|
||||
- [x] 访问权限管理
|
||||
- [x] IP 访问审计功能
|
||||
- [x] 域名动态拆分隧道(域名路由功能)
|
||||
- [x] radius认证支持
|
||||
- [ ] 基于 ipvtap 设备的桥接访问模式
|
||||
|
||||
## Config
|
||||
|
||||
默认配置文件内有详细的注释,根据注释填写配置即可。
|
||||
> 示例配置文件内有详细的注释,根据注释填写配置即可。
|
||||
|
||||
```shell
|
||||
# 生成后台密码
|
||||
@@ -85,37 +111,76 @@ sudo ./anylink --conf="conf/server.toml"
|
||||
./anylink tool -s
|
||||
```
|
||||
|
||||
[conf/server.toml](server/conf/server.toml)
|
||||
> 数据库配置示例
|
||||
|
||||
| db_type | db_source |
|
||||
| -------- | ------------------------------------------------------ |
|
||||
| sqlite3 | ./conf/anylink.db |
|
||||
| mysql | user:password@tcp(127.0.0.1:3306)/anylink?charset=utf8 |
|
||||
| postgres | user:password@localhost/anylink?sslmode=verify-full |
|
||||
|
||||
> 示例配置文件
|
||||
>
|
||||
> [conf/server-sample.toml](server/conf/server-sample.toml)
|
||||
|
||||
## Setting
|
||||
|
||||
网络模式选择,需要配置 `link_mode` 参数,如 `link_mode="tun"`,`link_mode="tap"` 两种参数。 不同的参数需要对服务器做相应的设置。
|
||||
> 以下参数必须设置其中之一
|
||||
|
||||
建议优先选择tun模式,因客户端传输的是IP层数据,无须进行数据转换。 tap模式是在用户态做的链路层到IP层的数据互相转换,性能会有所下降。 如果需要在虚拟机内开启tap模式,请确认虚拟机的网卡开启混杂模式。
|
||||
网络模式选择,需要配置 `link_mode` 参数,如 `link_mode="tun"`,`link_mode="macvtap"`,`link_mode="tap"(不推荐)` 等参数。 不同的参数需要对服务器做相应的设置。
|
||||
|
||||
### tun设置
|
||||
建议优先选择 tun 模式,其次选择 macvtap 模式,因客户端传输的是 IP 层数据,无须进行数据转换。 tap 模式是在用户态做的链路层到 IP 层的数据互相转换,性能会有所下降。 如果需要在虚拟机内开启 tap
|
||||
模式,请确认虚拟机的网卡开启混杂模式。
|
||||
|
||||
### tun 设置
|
||||
|
||||
1. 开启服务器转发
|
||||
|
||||
```shell
|
||||
# flie: /etc/sysctl.conf
|
||||
net.ipv4.ip_forward = 1
|
||||
|
||||
#执行如下命令
|
||||
sysctl -w net.ipv4.ip_forward=1
|
||||
```
|
||||
|
||||
2. 设置nat转发规则
|
||||
|
||||
```shell
|
||||
# eth0为服务器内网网卡
|
||||
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -o eth0 -j MASQUERADE
|
||||
# flie: /etc/sysctl.conf
|
||||
net.ipv4.ip_forward = 1
|
||||
|
||||
#执行如下命令
|
||||
sysctl -w net.ipv4.ip_forward=1
|
||||
|
||||
# 查看设置是否生效
|
||||
cat /proc/sys/net/ipv4/ip_forward
|
||||
```
|
||||
|
||||
3. 使用AnyConnect客户端连接即可
|
||||
2. 设置 nat 转发规则
|
||||
|
||||
### tap设置
|
||||
```shell
|
||||
systemctl stop firewalld.service
|
||||
systemctl disable firewalld.service
|
||||
|
||||
# 请根据服务器内网网卡替换 eth0
|
||||
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -o eth0 -j MASQUERADE
|
||||
# 如果执行第一个命令不生效,可以继续执行下面的命令
|
||||
# iptables -A FORWARD -i eth0 -s 192.168.10.0/24 -j ACCEPT
|
||||
# 查看设置是否生效
|
||||
iptables -nL -t nat
|
||||
```
|
||||
|
||||
3. 使用 AnyConnect 客户端连接即可
|
||||
|
||||
### macvtap 设置
|
||||
|
||||
1. 设置配置文件
|
||||
|
||||
> macvtap 设置相对比较简单,只需要配置相应的参数即可。
|
||||
> 以下参数可以通过执行 `ip a` 查看
|
||||
|
||||
```
|
||||
#内网主网卡名称
|
||||
ipv4_master = "eth0"
|
||||
#以下网段需要跟ipv4_master网卡设置成一样
|
||||
ipv4_cidr = "192.168.10.0/24"
|
||||
ipv4_gateway = "192.168.10.1"
|
||||
ipv4_start = "192.168.10.100"
|
||||
ipv4_end = "192.168.10.200"
|
||||
```
|
||||
|
||||
### ~~tap 设置~~
|
||||
|
||||
1. 创建桥接网卡
|
||||
|
||||
@@ -125,12 +190,13 @@ iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -o eth0 -j MASQUERADE
|
||||
|
||||
2. 修改 bridge-init.sh 内的参数
|
||||
|
||||
> 以下参数可以通过执行 `ip a` 查看
|
||||
|
||||
```
|
||||
eth="eth0"
|
||||
eth_ip="192.168.1.4"
|
||||
eth_netmask="255.255.255.0"
|
||||
eth_broadcast="192.168.1.255"
|
||||
eth_gateway="192.168.1.1"
|
||||
eth_ip="192.168.10.4/24"
|
||||
eth_broadcast="192.168.10.255"
|
||||
eth_gateway="192.168.10.1"
|
||||
```
|
||||
|
||||
3. 执行 bridge-init.sh 文件
|
||||
@@ -141,20 +207,20 @@ sh bridge-init.sh
|
||||
|
||||
## Systemd
|
||||
|
||||
添加 systemd脚本
|
||||
1. 添加 anylink 程序
|
||||
|
||||
* anylink 程序目录放入 `/usr/local/anylink-deploy`
|
||||
- anylink 程序目录放入 `/usr/local/anylink-deploy`
|
||||
|
||||
systemd 脚本放入:
|
||||
2. systemd/anylink.service 脚本放入:
|
||||
|
||||
* centos: `/usr/lib/systemd/system/`
|
||||
* ubuntu: `/lib/systemd/system/`
|
||||
- centos: `/usr/lib/systemd/system/`
|
||||
- ubuntu: `/lib/systemd/system/`
|
||||
|
||||
操作命令:
|
||||
3. 操作命令:
|
||||
|
||||
* 启动: `systemctl start anylink`
|
||||
* 停止: `systemctl stop anylink`
|
||||
* 开机自启: `systemctl enable anylink`
|
||||
- 启动: `systemctl start anylink`
|
||||
- 停止: `systemctl stop anylink`
|
||||
- 开机自启: `systemctl enable anylink`
|
||||
|
||||
## Docker
|
||||
|
||||
@@ -164,41 +230,49 @@ systemd 脚本放入:
|
||||
docker pull bjdgyc/anylink:latest
|
||||
```
|
||||
|
||||
2. 生成密码
|
||||
2. 查看命令信息
|
||||
|
||||
```bash
|
||||
docker run -it --rm bjdgyc/anylink -h
|
||||
```
|
||||
|
||||
3. 生成密码
|
||||
|
||||
```bash
|
||||
docker run -it --rm bjdgyc/anylink tool -p 123456
|
||||
#Passwd:$2a$10$lCWTCcGmQdE/4Kb1wabbLelu4vY/cUwBwN64xIzvXcihFgRzUvH2a
|
||||
```
|
||||
|
||||
3. 生成jwt secret
|
||||
4. 生成 jwt secret
|
||||
|
||||
```bash
|
||||
docker run -it --rm bjdgyc/anylink tool -s
|
||||
#Secret:9qXoIhY01jqhWIeIluGliOS4O_rhcXGGGu422uRZ1JjZxIZmh17WwzW36woEbA
|
||||
```
|
||||
|
||||
4. 启动容器
|
||||
5. 启动容器
|
||||
|
||||
```bash
|
||||
# -e IPV4_CIDR=192.168.10.0/24 这个参数要与配置文件内的网段一致
|
||||
docker run -itd --name anylink --privileged \
|
||||
-p 443:443 -p 8800:8800 \
|
||||
--restart=always \
|
||||
bjdgyc/anylink
|
||||
-e IPV4_CIDR=192.168.10.0/24
|
||||
-p 443:443 -p 8800:8800 \
|
||||
--restart=always \
|
||||
bjdgyc/anylink
|
||||
```
|
||||
|
||||
5. 使用自定义参数启动容器
|
||||
|
||||
6. 使用自定义参数启动容器
|
||||
```bash
|
||||
# 参数可以参考 -h 命令
|
||||
docker run -itd --name anylink --privileged \
|
||||
-e IPV4_CIDR=192.168.10.0/24 \
|
||||
-p 443:443 -p 8800:8800 \
|
||||
--restart=always \
|
||||
bjdgyc/anylink \
|
||||
-c=/etc/server.toml --admin_addr=:8080
|
||||
-e IPV4_CIDR=192.168.10.0/24 \
|
||||
-p 443:443 -p 8800:8800 \
|
||||
--restart=always \
|
||||
bjdgyc/anylink \
|
||||
-c=/etc/server.toml --ip_lease=1209600 # IP地址租约时长
|
||||
```
|
||||
|
||||
6. 构建镜像
|
||||
7. 构建镜像
|
||||
|
||||
```bash
|
||||
#获取仓库源码
|
||||
@@ -207,34 +281,33 @@ systemd 脚本放入:
|
||||
docker build -t anylink .
|
||||
```
|
||||
|
||||
|
||||
## 常见问题
|
||||
|
||||
请前往 [问题地址](question.md) 查看具体信息
|
||||
请前往 [问题地址](doc/question.md) 查看具体信息
|
||||
|
||||
## Discussion
|
||||
|
||||

|
||||
添加 QQ 群: 567510628
|
||||
|
||||
添加QQ群: 567510628
|
||||
|
||||
QQ群共享文件有相关软件下载
|
||||
QQ 群共享文件有相关软件下载
|
||||
|
||||
## Contribution
|
||||
|
||||
欢迎提交 PR、Issues,感谢为AnyLink做出贡献。
|
||||
欢迎提交 PR、Issues,感谢为 AnyLink 做出贡献。
|
||||
|
||||
注意新建PR,需要提交到dev分支,其他分支暂不会合并。
|
||||
注意新建 PR,需要提交到 dev 分支,其他分支暂不会合并。
|
||||
|
||||
## Other Screenshot
|
||||
|
||||
<details>
|
||||
<summary>展开查看</summary>
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
</details>
|
||||
|
||||
@@ -245,9 +318,5 @@ QQ群共享文件有相关软件下载
|
||||
## Thank
|
||||
|
||||
<a href="https://www.jetbrains.com">
|
||||
<img src="screenshot/jetbrains.png" width="200" height="200" alt="jetbrains.png" />
|
||||
<img src="doc/screenshot/jetbrains.png" width="200" alt="jetbrains.png" />
|
||||
</a>
|
||||
|
||||
|
||||
|
||||
|
||||
|
33
build.sh
@@ -12,35 +12,44 @@ function RETVAL() {
|
||||
#当前目录
|
||||
cpath=$(pwd)
|
||||
|
||||
echo "编译二进制文件"
|
||||
cd $cpath/server
|
||||
go build -o anylink -ldflags "-X main.COMMIT_ID=$(git rev-parse HEAD)"
|
||||
RETVAL $?
|
||||
|
||||
echo "编译前端项目"
|
||||
cd $cpath/web
|
||||
#国内可替换源加快速度
|
||||
npm install --registry=https://registry.npm.taobao.org
|
||||
npm run build --registry=https://registry.npm.taobao.org
|
||||
#npx browserslist@latest --update-db
|
||||
#npm install --registry=https://registry.npm.taobao.org
|
||||
#npm install
|
||||
#npm run build
|
||||
|
||||
yarn install
|
||||
yarn run build
|
||||
|
||||
RETVAL $?
|
||||
|
||||
echo "编译二进制文件"
|
||||
cd $cpath/server
|
||||
rm -rf ui
|
||||
cp -rf $cpath/web/ui .
|
||||
#国内可替换源加快速度
|
||||
export GOPROXY=https://goproxy.io
|
||||
go mod tidy
|
||||
go build -v -o anylink -ldflags "-X main.CommitId=$(git rev-parse HEAD)"
|
||||
RETVAL $?
|
||||
|
||||
cd $cpath
|
||||
|
||||
echo "整理部署文件"
|
||||
deploy="anylink-deploy"
|
||||
rm -rf $deploy
|
||||
rm -rf $deploy ${deploy}.tar.gz
|
||||
mkdir $deploy
|
||||
mkdir $deploy/log
|
||||
|
||||
cp -r server/anylink $deploy
|
||||
cp -r server/conf $deploy
|
||||
cp -r server/files $deploy
|
||||
cp -r server/bridge-init.sh $deploy
|
||||
cp -r server/conf $deploy
|
||||
|
||||
cp -r systemd $deploy
|
||||
cp -r web/ui $deploy
|
||||
cp -r LICENSE $deploy
|
||||
|
||||
tar zcvf ${deploy}.tar.gz $deploy
|
||||
|
||||
#注意使用root权限运行
|
||||
#cd anylink-deploy
|
||||
|
14
build_docker.sh
Normal file
@@ -0,0 +1,14 @@
|
||||
#!/bin/env bash
|
||||
|
||||
ver=`cat server/base/app_ver.go | grep APP_VER | awk '{print $3}' | sed 's/"//g'`
|
||||
echo $ver
|
||||
|
||||
#docker login -u bjdgyc
|
||||
|
||||
docker build -t bjdgyc/anylink .
|
||||
|
||||
docker tag bjdgyc/anylink:latest bjdgyc/anylink:$ver
|
||||
|
||||
docker push bjdgyc/anylink:$ver
|
||||
docker push bjdgyc/anylink:latest
|
||||
|
26
doc/README.md
Normal file
@@ -0,0 +1,26 @@
|
||||
## Donate
|
||||
|
||||
> 如果您觉得 AnyLink 对你有帮助,欢迎给我们打赏,也是帮助 AnyLink 更好的发展。
|
||||
|
||||
<p>
|
||||
<img src="screenshot/wxpay2.png" width="500" />
|
||||
</p>
|
||||
|
||||
## Donator
|
||||
|
||||
> 感谢以下同学的打赏,AnyLink 有你更美好!
|
||||
|
||||
| 昵称 | 主页 |
|
||||
| -- | ---------------------------- |
|
||||
| 代码oo8 | |
|
||||
| 甘磊 | https://github.com/ganlei333 |
|
||||
| Oo@ | https://github.com/chooop |
|
||||
| 虚极静笃 | |
|
||||
| 请喝可乐 | |
|
||||
| 加油加油 | |
|
||||
| 李建 | |
|
||||
| lanbin | |
|
||||
| 乐在东途 | |
|
||||
|
||||
|
||||
|
42
doc/question.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# 常见问题
|
||||
|
||||
### anyconnect 客户端问题
|
||||
> 客户端请使用群共享文件的版本,其他版本没有测试过,不保证使用正常
|
||||
>
|
||||
> 添加QQ群: 567510628
|
||||
|
||||
### OTP 动态码
|
||||
> 请使用手机安装 freeotp ,然后扫描otp二维码,生成的数字即是动态码
|
||||
|
||||
### 远程桌面连接
|
||||
> 本软件已经支持远程桌面里面连接anyconnect。
|
||||
|
||||
### 私有证书问题
|
||||
> anylink 默认不支持私有证书
|
||||
>
|
||||
> 其他使用私有证书的问题,请自行解决
|
||||
|
||||
### dpd timeout 设置问题
|
||||
```
|
||||
#客户端失效检测时间(秒) dpd > keepalive
|
||||
cstp_keepalive = 20
|
||||
cstp_dpd = 30
|
||||
mobile_keepalive = 40
|
||||
mobile_dpd = 50
|
||||
```
|
||||
> 以上dpd参数为客户端的超时检测时间, 如一段时间内,没有数据传输,防火墙会主动关闭连接
|
||||
>
|
||||
> 如经常出现 timeout 的错误信息,应根据当前防火墙的设置,适当减小dpd数值
|
||||
|
||||
### 性能问题
|
||||
```
|
||||
内网环境测试数据
|
||||
虚拟服务器: centos7 4C8G
|
||||
anylink: tun模式 tcp传输
|
||||
客户端文件下载速度:240Mb/s
|
||||
客户端网卡下载速度:270Mb/s
|
||||
服务端网卡上传速度:280Mb/s
|
||||
```
|
||||
> 客户端tls加密协议、隧道header头都会占用一定带宽
|
||||
|
||||
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 47 KiB |
Before Width: | Height: | Size: 164 KiB After Width: | Height: | Size: 164 KiB |
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
BIN
doc/screenshot/wxpay.png
Normal file
After Width: | Height: | Size: 135 KiB |
BIN
doc/screenshot/wxpay2.png
Normal file
After Width: | Height: | Size: 71 KiB |
@@ -16,8 +16,8 @@ case $var1 in
|
||||
*)
|
||||
sysctl -w net.ipv4.ip_forward=1
|
||||
iptables -t nat -A POSTROUTING -s "${IPV4_CIDR}" -o eth0+ -j MASQUERADE
|
||||
# iptables -nL -t nat
|
||||
iptables -nL -t nat
|
||||
|
||||
/app/anylink "$@"
|
||||
exec /app/anylink "$@"
|
||||
;;
|
||||
esac
|
||||
|
@@ -9,6 +9,7 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"math/big"
|
||||
@@ -70,6 +71,11 @@ func WithDNS(key crypto.PrivateKey, cn string, sans ...string) (tls.Certificate,
|
||||
names = append(names, sans...)
|
||||
|
||||
template := x509.Certificate{
|
||||
Subject: pkix.Name{
|
||||
// TODO anylink
|
||||
Organization: []string{cn},
|
||||
OrganizationalUnit: names,
|
||||
},
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{
|
||||
x509.ExtKeyUsageClientAuth,
|
||||
x509.ExtKeyUsageServerAuth,
|
||||
|
15
question.md
@@ -1,15 +0,0 @@
|
||||
# 常见问题
|
||||
|
||||
### anyconnect 客户端问题
|
||||
> 客户端请使用群共享文件的版本,其他版本没有测试过,不保证使用正常。
|
||||
>
|
||||
> 添加QQ群: 567510628
|
||||
|
||||
### 远程桌面连接
|
||||
> 本软件不支持远程桌面连接,请注意。
|
||||
|
||||
### 私有证书问题
|
||||
> anylink 默认不支持私有证书
|
||||
>
|
||||
> 仅测试的话,可以通过 https://github.com/square/certstrap 生成私有的证书, 然后把CA证书放在客户端机器上即可以连接。
|
||||
|
@@ -22,7 +22,7 @@ func GroupList(w http.ResponseWriter, r *http.Request) {
|
||||
count := dbdata.CountAll(&dbdata.Group{})
|
||||
|
||||
var datas []dbdata.Group
|
||||
err := dbdata.All(&datas, pageSize, page)
|
||||
err := dbdata.Find(&datas, pageSize, page)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
@@ -62,7 +62,9 @@ func GroupDetail(w http.ResponseWriter, r *http.Request) {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(data.Auth) == 0 {
|
||||
data.Auth["type"] = "local"
|
||||
}
|
||||
RespSucess(w, data)
|
||||
}
|
||||
|
||||
|
@@ -5,7 +5,6 @@ import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
)
|
||||
@@ -23,7 +22,7 @@ func UserIpMapList(w http.ResponseWriter, r *http.Request) {
|
||||
count := dbdata.CountAll(&dbdata.IpMap{})
|
||||
|
||||
var datas []dbdata.IpMap
|
||||
err := dbdata.All(&datas, pageSize, page)
|
||||
err := dbdata.Find(&datas, pageSize, page)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
@@ -75,14 +74,7 @@ func UserIpMapSet(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// fmt.Println(v, len(v.Ip), len(v.MacAddr))
|
||||
|
||||
if len(v.IpAddr) < 4 || len(v.MacAddr) < 6 {
|
||||
RespError(w, RespParamErr, "IP或MAC错误")
|
||||
return
|
||||
}
|
||||
|
||||
v.UpdatedAt = time.Now()
|
||||
err = dbdata.Save(v)
|
||||
|
||||
err = dbdata.SetIpMap(v)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
|
98
server/admin/api_policy.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
)
|
||||
|
||||
func PolicyList(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
pageS := r.FormValue("page")
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
var pageSize = dbdata.PageSize
|
||||
|
||||
count := dbdata.CountAll(&dbdata.Policy{})
|
||||
|
||||
var datas []dbdata.Policy
|
||||
err := dbdata.Find(&datas, pageSize, page)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"count": count,
|
||||
"page_size": pageSize,
|
||||
"datas": datas,
|
||||
}
|
||||
|
||||
RespSucess(w, data)
|
||||
}
|
||||
|
||||
func PolicyDetail(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
idS := r.FormValue("id")
|
||||
id, _ := strconv.Atoi(idS)
|
||||
if id < 1 {
|
||||
RespError(w, RespParamErr, "Id错误")
|
||||
return
|
||||
}
|
||||
|
||||
var data dbdata.Policy
|
||||
err := dbdata.One("Id", id, &data)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
RespSucess(w, data)
|
||||
}
|
||||
|
||||
func PolicySet(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
v := &dbdata.Policy{}
|
||||
err = json.Unmarshal(body, v)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = dbdata.SetPolicy(v)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
RespSucess(w, nil)
|
||||
}
|
||||
|
||||
func PolicyDel(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
idS := r.FormValue("id")
|
||||
id, _ := strconv.Atoi(idS)
|
||||
if id < 1 {
|
||||
RespError(w, RespParamErr, "Id错误")
|
||||
return
|
||||
}
|
||||
|
||||
data := dbdata.Policy{Id: id}
|
||||
err := dbdata.Del(&data)
|
||||
if err != nil {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
RespSucess(w, nil)
|
||||
}
|
@@ -5,11 +5,10 @@ import (
|
||||
"net/http"
|
||||
"runtime"
|
||||
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/disk"
|
||||
"github.com/shirou/gopsutil/host"
|
||||
@@ -67,10 +66,11 @@ func SetSystem(w http.ResponseWriter, r *http.Request) {
|
||||
hi, _ := host.Info()
|
||||
l, _ := load.Avg()
|
||||
data["sys"] = map[string]interface{}{
|
||||
"goOs": runtime.GOOS,
|
||||
"goArch": runtime.GOARCH,
|
||||
"goVersion": runtime.Version(),
|
||||
"goroutine": runtime.NumGoroutine(),
|
||||
"goOs": runtime.GOOS,
|
||||
"goArch": runtime.GOARCH,
|
||||
"goVersion": runtime.Version(),
|
||||
"goroutine": runtime.NumGoroutine(),
|
||||
"appVersion": "v" + base.APP_VER,
|
||||
|
||||
"hostname": hi.Hostname,
|
||||
"platform": fmt.Sprintf("%v %v %v", hi.Platform, hi.PlatformFamily, hi.PlatformVersion),
|
||||
|
33
server/admin/api_set_audit.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
)
|
||||
|
||||
func SetAuditList(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
pageS := r.FormValue("page")
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
var datas []dbdata.AccessAudit
|
||||
count := dbdata.CountAll(&dbdata.AccessAudit{})
|
||||
err := dbdata.Find(&datas, dbdata.PageSize, page)
|
||||
if err != nil && !dbdata.CheckErrNotFound(err) {
|
||||
RespError(w, RespInternalErr, err)
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"count": count,
|
||||
"page_size": dbdata.PageSize,
|
||||
"datas": datas,
|
||||
}
|
||||
|
||||
RespSucess(w, data)
|
||||
}
|
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
@@ -36,11 +37,11 @@ func UserList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 查询前缀匹配
|
||||
if len(prefix) > 0 {
|
||||
count = pageSize
|
||||
err = dbdata.Prefix("Username", prefix, &datas, pageSize, 1)
|
||||
count = dbdata.CountPrefix("username", prefix, &dbdata.User{})
|
||||
err = dbdata.Prefix("username", prefix, &datas, pageSize, 1)
|
||||
} else {
|
||||
count = dbdata.CountAll(&dbdata.User{})
|
||||
err = dbdata.All(&datas, pageSize, page)
|
||||
err = dbdata.Find(&datas, pageSize, page)
|
||||
}
|
||||
|
||||
if err != nil && !dbdata.CheckErrNotFound(err) {
|
||||
@@ -141,7 +142,7 @@ func UserOtpQr(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
issuer := base.Cfg.Issuer
|
||||
issuer := url.QueryEscape(base.Cfg.Issuer)
|
||||
qrstr := fmt.Sprintf("otpauth://totp/%s:%s?issuer=%s&secret=%s", issuer, user.Email, issuer, user.OtpSecret)
|
||||
qr, _ := qrcode.New(qrstr, qrcode.High)
|
||||
|
||||
|
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
mail "github.com/xhit/go-simple-mail/v2"
|
||||
// "github.com/mojocn/base64Captcha"
|
||||
)
|
||||
@@ -59,8 +59,14 @@ func SendMail(subject, to, htmlBody string) error {
|
||||
server.Port = dataSmtp.Port
|
||||
server.Username = dataSmtp.Username
|
||||
server.Password = dataSmtp.Password
|
||||
if dataSmtp.UseSSl {
|
||||
server.Encryption = mail.EncryptionSSL
|
||||
|
||||
switch dataSmtp.Encryption {
|
||||
case "SSLTLS":
|
||||
server.Encryption = mail.EncryptionSSLTLS
|
||||
case "STARTTLS":
|
||||
server.Encryption = mail.EncryptionSTARTTLS
|
||||
default:
|
||||
server.Encryption = mail.EncryptionNone
|
||||
}
|
||||
|
||||
// Since v2.3.0 you can specified authentication type:
|
||||
|
@@ -2,6 +2,8 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"embed"
|
||||
"net/http"
|
||||
"net/http/pprof"
|
||||
|
||||
@@ -9,15 +11,23 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
// 开启服务
|
||||
var UiData embed.FS
|
||||
|
||||
// StartAdmin 开启服务
|
||||
func StartAdmin() {
|
||||
|
||||
r := mux.NewRouter()
|
||||
r.Use(authMiddleware)
|
||||
|
||||
// 监控检测
|
||||
r.HandleFunc("/status.html", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("ok"))
|
||||
}).Name("index")
|
||||
|
||||
r.Handle("/", http.RedirectHandler("/ui/", http.StatusFound)).Name("index")
|
||||
r.PathPrefix("/ui/").Handler(
|
||||
http.StripPrefix("/ui/", http.FileServer(http.Dir(base.Cfg.UiPath))),
|
||||
// http.StripPrefix("/ui/", http.FileServer(http.Dir(base.Cfg.UiPath))),
|
||||
http.FileServer(http.FS(UiData)),
|
||||
).Name("static")
|
||||
r.HandleFunc("/base/login", Login).Name("login")
|
||||
|
||||
@@ -28,6 +38,7 @@ func StartAdmin() {
|
||||
r.HandleFunc("/set/other/edit", SetOtherEdit)
|
||||
r.HandleFunc("/set/other/smtp", SetOtherSmtp)
|
||||
r.HandleFunc("/set/other/smtp/edit", SetOtherSmtpEdit)
|
||||
r.HandleFunc("/set/audit/list", SetAuditList)
|
||||
|
||||
r.HandleFunc("/user/list", UserList)
|
||||
r.HandleFunc("/user/detail", UserDetail)
|
||||
@@ -41,6 +52,10 @@ func StartAdmin() {
|
||||
r.HandleFunc("/user/ip_map/detail", UserIpMapDetail)
|
||||
r.HandleFunc("/user/ip_map/set", UserIpMapSet)
|
||||
r.HandleFunc("/user/ip_map/del", UserIpMapDel)
|
||||
r.HandleFunc("/user/policy/list", PolicyList)
|
||||
r.HandleFunc("/user/policy/detail", PolicyDetail)
|
||||
r.HandleFunc("/user/policy/set", PolicySet)
|
||||
r.HandleFunc("/user/policy/del", PolicyDel)
|
||||
|
||||
r.HandleFunc("/group/list", GroupList)
|
||||
r.HandleFunc("/group/names", GroupNames)
|
||||
@@ -54,12 +69,30 @@ func StartAdmin() {
|
||||
r.HandleFunc("/debug/pprof/profile", pprof.Profile).Name("debug")
|
||||
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol).Name("debug")
|
||||
r.HandleFunc("/debug/pprof/trace", pprof.Trace).Name("debug")
|
||||
r.HandleFunc("/debug/pprof", location("/debug/pprof/"))
|
||||
r.HandleFunc("/debug/pprof", location("/debug/pprof/")).Name("debug")
|
||||
r.PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index).Name("debug")
|
||||
}
|
||||
|
||||
base.Info("Listen admin", base.Cfg.AdminAddr)
|
||||
err := http.ListenAndServe(base.Cfg.AdminAddr, r)
|
||||
|
||||
// 修复 CVE-2016-2183
|
||||
cipherSuites := tls.CipherSuites()
|
||||
selectedCipherSuites := make([]uint16, 0, len(cipherSuites))
|
||||
for _, s := range cipherSuites {
|
||||
selectedCipherSuites = append(selectedCipherSuites, s.ID)
|
||||
}
|
||||
// 设置tls信息
|
||||
tlsConfig := &tls.Config{
|
||||
NextProtos: []string{"http/1.1"},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CipherSuites: selectedCipherSuites,
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: base.Cfg.AdminAddr,
|
||||
Handler: r,
|
||||
TLSConfig: tlsConfig,
|
||||
}
|
||||
err := srv.ListenAndServeTLS(base.Cfg.CertFile, base.Cfg.CertKey)
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
|
@@ -2,5 +2,6 @@ package base
|
||||
|
||||
const (
|
||||
APP_NAME = "AnyLink"
|
||||
APP_VER = "0.3.1"
|
||||
// 添加radius支持
|
||||
APP_VER = "0.8.1"
|
||||
)
|
||||
|
@@ -5,13 +5,13 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
LinkModeTUN = "tun"
|
||||
LinkModeTAP = "tap"
|
||||
LinkModeTUN = "tun"
|
||||
LinkModeTAP = "tap"
|
||||
LinkModeMacvtap = "macvtap"
|
||||
LinkModeIpvtap = "ipvtap"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -31,15 +31,17 @@ var (
|
||||
|
||||
type ServerConfig struct {
|
||||
// LinkAddr string `json:"link_addr"`
|
||||
Conf string `json:"conf"`
|
||||
Profile string `json:"profile"`
|
||||
ServerAddr string `json:"server_addr"`
|
||||
ServerDTLSAddr string `json:"server_dtls_addr"`
|
||||
ServerDTLS bool `json:"server_dtls"`
|
||||
AdminAddr string `json:"admin_addr"`
|
||||
ProxyProtocol bool `json:"proxy_protocol"`
|
||||
DbFile string `json:"db_file"`
|
||||
DbType string `json:"db_type"`
|
||||
DbSource string `json:"db_source"`
|
||||
CertFile string `json:"cert_file"`
|
||||
CertKey string `json:"cert_key"`
|
||||
UiPath string `json:"ui_path"`
|
||||
FilesPath string `json:"files_path"`
|
||||
LogPath string `json:"log_path"`
|
||||
LogLevel string `json:"log_level"`
|
||||
@@ -49,11 +51,12 @@ type ServerConfig struct {
|
||||
AdminPass string `json:"admin_pass"`
|
||||
JwtSecret string `json:"jwt_secret"`
|
||||
|
||||
LinkMode string `json:"link_mode"` // tun tap
|
||||
Ipv4CIDR string `json:"ipv4_cidr"` // 192.168.1.0/24
|
||||
Ipv4Gateway string `json:"ipv4_gateway"`
|
||||
Ipv4Start string `json:"ipv4_start"` // 192.168.1.100
|
||||
Ipv4End string `json:"ipv4_end"` // 192.168.1.200
|
||||
LinkMode string `json:"link_mode"` // tun tap macvtap ipvtap
|
||||
Ipv4Master string `json:"ipv4_master"` // eth0
|
||||
Ipv4CIDR string `json:"ipv4_cidr"` // 192.168.10.0/24
|
||||
Ipv4Gateway string `json:"ipv4_gateway"` // 192.168.10.1
|
||||
Ipv4Start string `json:"ipv4_start"` // 192.168.10.100
|
||||
Ipv4End string `json:"ipv4_end"` // 192.168.10.200
|
||||
IpLease int `json:"ip_lease"`
|
||||
|
||||
MaxClient int `json:"max_client"`
|
||||
@@ -63,27 +66,33 @@ type ServerConfig struct {
|
||||
CstpDpd int `json:"cstp_dpd"` // Dead peer detection in seconds
|
||||
MobileKeepalive int `json:"mobile_keepalive"`
|
||||
MobileDpd int `json:"mobile_dpd"`
|
||||
Mtu int `json:"mtu"`
|
||||
|
||||
SessionTimeout int `json:"session_timeout"` // in seconds
|
||||
AuthTimeout int `json:"auth_timeout"` // in seconds
|
||||
// AuthTimeout int `json:"auth_timeout"` // in seconds
|
||||
AuditInterval int `json:"audit_interval"` // in seconds
|
||||
}
|
||||
|
||||
func initServerCfg() {
|
||||
|
||||
sf, _ := filepath.Abs(cfgFile)
|
||||
base := filepath.Dir(sf)
|
||||
// TODO 取消绝对地址转换
|
||||
// sf, _ := filepath.Abs(cfgFile)
|
||||
// base := filepath.Dir(sf)
|
||||
|
||||
// 转换成绝对路径
|
||||
Cfg.DbFile = getAbsPath(base, Cfg.DbFile)
|
||||
Cfg.CertFile = getAbsPath(base, Cfg.CertFile)
|
||||
Cfg.CertKey = getAbsPath(base, Cfg.CertKey)
|
||||
Cfg.UiPath = getAbsPath(base, Cfg.UiPath)
|
||||
Cfg.FilesPath = getAbsPath(base, Cfg.FilesPath)
|
||||
Cfg.LogPath = getAbsPath(base, Cfg.LogPath)
|
||||
// Cfg.DbFile = getAbsPath(base, Cfg.DbFile)
|
||||
// Cfg.CertFile = getAbsPath(base, Cfg.CertFile)
|
||||
// Cfg.CertKey = getAbsPath(base, Cfg.CertKey)
|
||||
// Cfg.UiPath = getAbsPath(base, Cfg.UiPath)
|
||||
// Cfg.FilesPath = getAbsPath(base, Cfg.FilesPath)
|
||||
// Cfg.LogPath = getAbsPath(base, Cfg.LogPath)
|
||||
|
||||
if len(Cfg.JwtSecret) < 20 {
|
||||
fmt.Println("请设置 jwt_secret 长度20位以上")
|
||||
os.Exit(0)
|
||||
if Cfg.AdminPass == defaultPwd {
|
||||
fmt.Fprintln(os.Stderr, "=== 使用默认的admin_pass有安全风险,请设置新的admin_pass ===")
|
||||
}
|
||||
|
||||
if Cfg.JwtSecret == defaultJwt {
|
||||
fmt.Fprintln(os.Stderr, "=== 使用默认的jwt_secret有安全风险,请设置新的jwt_secret ===")
|
||||
}
|
||||
|
||||
fmt.Printf("ServerCfg: %+v \n", Cfg)
|
||||
@@ -115,13 +124,13 @@ func initCfg() {
|
||||
for _, v := range configs {
|
||||
if v.Name == tag {
|
||||
if v.Typ == cfgStr {
|
||||
value.SetString(viper.GetString(v.Name))
|
||||
value.SetString(linkViper.GetString(v.Name))
|
||||
}
|
||||
if v.Typ == cfgInt {
|
||||
value.SetInt(int64(viper.GetInt(v.Name)))
|
||||
value.SetInt(int64(linkViper.GetInt(v.Name)))
|
||||
}
|
||||
if v.Typ == cfgBool {
|
||||
value.SetBool(viper.GetBool(v.Name))
|
||||
value.SetBool(linkViper.GetBool(v.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,9 +159,6 @@ func ServerCfg2Slice() []SCfg {
|
||||
value := s.Field(i)
|
||||
tag := field.Tag.Get("json")
|
||||
usage, env := getUsageEnv(tag)
|
||||
if usage == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
datas = append(datas, SCfg{Name: tag, Env: env, Info: usage, Data: value.Interface()})
|
||||
}
|
||||
|
@@ -1,12 +1,12 @@
|
||||
package base
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/spf13/cobra"
|
||||
@@ -16,25 +16,26 @@ import (
|
||||
var (
|
||||
// 提交id
|
||||
CommitId string
|
||||
// 配置文件
|
||||
cfgFile string
|
||||
// pass明文
|
||||
passwd string
|
||||
// 生成密钥
|
||||
secret bool
|
||||
// 显示版本信息
|
||||
rev bool
|
||||
// 获取env名称
|
||||
env bool
|
||||
// 输出debug信息
|
||||
debug bool
|
||||
|
||||
// Used for flags.
|
||||
runSrv bool
|
||||
|
||||
rootCmd *cobra.Command
|
||||
linkViper *viper.Viper
|
||||
rootCmd *cobra.Command
|
||||
)
|
||||
|
||||
// Execute executes the root command.
|
||||
func execute() {
|
||||
initCmd()
|
||||
|
||||
err := rootCmd.Execute()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
@@ -42,13 +43,25 @@ func execute() {
|
||||
}
|
||||
|
||||
// viper.Debug()
|
||||
ref := reflect.ValueOf(linkViper)
|
||||
s := ref.Elem()
|
||||
ee := s.FieldByName("env")
|
||||
if ee.Kind() != reflect.Map {
|
||||
panic("Viper env is err")
|
||||
}
|
||||
rr := ee.MapRange()
|
||||
for rr.Next() {
|
||||
// fmt.Println(rr.Key(), rr.Value().Index(0))
|
||||
envs[rr.Key().String()] = rr.Value().Index(0).String()
|
||||
}
|
||||
|
||||
if !runSrv {
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
func initCmd() {
|
||||
linkViper = viper.New()
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "anylink",
|
||||
Short: "AnyLink VPN Server",
|
||||
@@ -59,38 +72,44 @@ func init() {
|
||||
},
|
||||
}
|
||||
|
||||
cobra.OnInitialize(func() {
|
||||
viper.SetConfigFile(cfgFile)
|
||||
viper.AutomaticEnv()
|
||||
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
fmt.Println("Using config file:", err)
|
||||
}
|
||||
})
|
||||
|
||||
viper.SetEnvPrefix("link")
|
||||
linkViper.SetEnvPrefix("link")
|
||||
|
||||
// 基础配置
|
||||
rootCmd.Flags().StringVarP(&cfgFile, "config", "c", "./conf/server.toml", "config file")
|
||||
|
||||
for _, v := range configs {
|
||||
if v.Typ == cfgStr {
|
||||
rootCmd.Flags().String(v.Name, v.ValStr, v.Usage)
|
||||
rootCmd.Flags().StringP(v.Name, v.Short, v.ValStr, v.Usage)
|
||||
}
|
||||
if v.Typ == cfgInt {
|
||||
rootCmd.Flags().Int(v.Name, v.ValInt, v.Usage)
|
||||
rootCmd.Flags().IntP(v.Name, v.Short, v.ValInt, v.Usage)
|
||||
}
|
||||
if v.Typ == cfgBool {
|
||||
rootCmd.Flags().Bool(v.Name, v.ValBool, v.Usage)
|
||||
rootCmd.Flags().BoolP(v.Name, v.Short, v.ValBool, v.Usage)
|
||||
}
|
||||
|
||||
_ = viper.BindPFlag(v.Name, rootCmd.Flags().Lookup(v.Name))
|
||||
_ = viper.BindEnv(v.Name)
|
||||
_ = linkViper.BindPFlag(v.Name, rootCmd.Flags().Lookup(v.Name))
|
||||
_ = linkViper.BindEnv(v.Name)
|
||||
// viper.SetDefault(v.Name, v.Value)
|
||||
}
|
||||
|
||||
rootCmd.AddCommand(initToolCmd())
|
||||
|
||||
cobra.OnInitialize(func() {
|
||||
linkViper.AutomaticEnv()
|
||||
conf := linkViper.GetString("conf")
|
||||
|
||||
_, err := os.Stat(conf)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
// 没有配置文件,不做处理
|
||||
panic(err)
|
||||
}
|
||||
|
||||
linkViper.SetConfigFile(conf)
|
||||
err = linkViper.ReadInConfig()
|
||||
if err != nil {
|
||||
fmt.Println("Using config file:", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func initToolCmd() *cobra.Command {
|
||||
@@ -103,7 +122,7 @@ func initToolCmd() *cobra.Command {
|
||||
toolCmd.Flags().BoolVarP(&rev, "version", "v", false, "display version info")
|
||||
toolCmd.Flags().BoolVarP(&secret, "secret", "s", false, "generate a random jwt secret")
|
||||
toolCmd.Flags().StringVarP(&passwd, "passwd", "p", "", "convert the password plaintext")
|
||||
toolCmd.Flags().BoolVarP(&env, "env", "e", false, "list the config name and env key")
|
||||
toolCmd.Flags().BoolVarP(&debug, "debug", "d", false, "list the config viper.Debug() info")
|
||||
|
||||
toolCmd.Run = func(cmd *cobra.Command, args []string) {
|
||||
switch {
|
||||
@@ -111,17 +130,14 @@ func initToolCmd() *cobra.Command {
|
||||
fmt.Printf("%s v%s build on %s [%s, %s] commit_id(%s) \n",
|
||||
APP_NAME, APP_VER, runtime.Version(), runtime.GOOS, runtime.GOARCH, CommitId)
|
||||
case secret:
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
s, _ := utils.RandSecret(40, 60)
|
||||
s = strings.Trim(s, "=")
|
||||
fmt.Printf("Secret:%s\n", s)
|
||||
case passwd != "":
|
||||
pass, _ := utils.PasswordHash(passwd)
|
||||
fmt.Printf("Passwd:%s\n", pass)
|
||||
case env:
|
||||
for k, v := range envs {
|
||||
fmt.Printf("%s => %s\n", k, v)
|
||||
}
|
||||
case debug:
|
||||
linkViper.Debug()
|
||||
default:
|
||||
fmt.Println("Using [anylink tool -h] for help")
|
||||
}
|
||||
|
@@ -4,11 +4,15 @@ const (
|
||||
cfgStr = iota
|
||||
cfgInt
|
||||
cfgBool
|
||||
|
||||
defaultJwt = "abcdef.0123456789.abcdef"
|
||||
defaultPwd = "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Typ int
|
||||
Name string
|
||||
Short string
|
||||
Usage string
|
||||
ValStr string
|
||||
ValInt int
|
||||
@@ -16,24 +20,27 @@ type config struct {
|
||||
}
|
||||
|
||||
var configs = []config{
|
||||
{Typ: cfgStr, Name: "conf", Usage: "config file", ValStr: "./conf/server.toml", Short: "c"},
|
||||
{Typ: cfgStr, Name: "profile", Usage: "profile.xml file", ValStr: "./conf/profile.xml"},
|
||||
{Typ: cfgStr, Name: "server_addr", Usage: "服务监听地址", ValStr: ":443"},
|
||||
{Typ: cfgBool, Name: "server_dtls", Usage: "开启DTLS", ValBool: false},
|
||||
{Typ: cfgStr, Name: "server_dtls_addr", Usage: "DTLS监听地址", ValStr: ":4433"},
|
||||
{Typ: cfgStr, Name: "admin_addr", Usage: "后台服务监听地址", ValStr: ":8800"},
|
||||
{Typ: cfgBool, Name: "proxy_protocol", Usage: "TCP代理协议", ValBool: false},
|
||||
{Typ: cfgStr, Name: "db_file", Usage: "数据库地址", ValStr: "./data.db"},
|
||||
{Typ: cfgStr, Name: "cert_file", Usage: "证书文件", ValStr: "./vpn_cert.pem"},
|
||||
{Typ: cfgStr, Name: "cert_key", Usage: "证书密钥", ValStr: "./vpn_cert.key"},
|
||||
{Typ: cfgStr, Name: "ui_path", Usage: "ui文件路径", ValStr: "./ui"},
|
||||
{Typ: cfgStr, Name: "files_path", Usage: "外部下载文件路径", ValStr: "./files"},
|
||||
{Typ: cfgStr, Name: "log_path", Usage: "日志文件路径", ValStr: ""},
|
||||
{Typ: cfgStr, Name: "log_level", Usage: "日志等级", ValStr: "info"},
|
||||
{Typ: cfgStr, Name: "db_type", Usage: "数据库类型 [sqlite3 mysql postgres]", ValStr: "sqlite3"},
|
||||
{Typ: cfgStr, Name: "db_source", Usage: "数据库source", ValStr: "./conf/anylink.db"},
|
||||
{Typ: cfgStr, Name: "cert_file", Usage: "证书文件", ValStr: "./conf/vpn_cert.pem"},
|
||||
{Typ: cfgStr, Name: "cert_key", Usage: "证书密钥", ValStr: "./conf/vpn_cert.key"},
|
||||
{Typ: cfgStr, Name: "files_path", Usage: "外部下载文件路径", ValStr: "./conf/files"},
|
||||
{Typ: cfgStr, Name: "log_path", Usage: "日志文件路径,默认标准输出", ValStr: ""},
|
||||
{Typ: cfgStr, Name: "log_level", Usage: "日志等级 [debug info warn error]", ValStr: "info"},
|
||||
{Typ: cfgBool, Name: "pprof", Usage: "开启pprof", ValBool: false},
|
||||
{Typ: cfgStr, Name: "issuer", Usage: "系统名称", ValStr: "XX公司VPN"},
|
||||
{Typ: cfgStr, Name: "admin_user", Usage: "管理用户名", ValStr: "admin"},
|
||||
{Typ: cfgStr, Name: "admin_pass", Usage: "管理用户密码", ValStr: "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"},
|
||||
{Typ: cfgStr, Name: "jwt_secret", Usage: "JWT密钥", ValStr: "iLmspvOiz*%ovfcs*wersdf#heR8pNU4XxBm&mW$aPCjSRMbYH#&"},
|
||||
{Typ: cfgStr, Name: "link_mode", Usage: "虚拟网络类型", ValStr: "tun"},
|
||||
{Typ: cfgStr, Name: "admin_pass", Usage: "管理用户密码", ValStr: defaultPwd},
|
||||
{Typ: cfgStr, Name: "jwt_secret", Usage: "JWT密钥", ValStr: defaultJwt},
|
||||
{Typ: cfgStr, Name: "link_mode", Usage: "虚拟网络类型[tun tap macvtap ipvtap]", ValStr: "tun"},
|
||||
{Typ: cfgStr, Name: "ipv4_master", Usage: "ipv4主网卡名称", ValStr: "eth0"},
|
||||
{Typ: cfgStr, Name: "ipv4_cidr", Usage: "ip地址网段", ValStr: "192.168.10.0/24"},
|
||||
{Typ: cfgStr, Name: "ipv4_gateway", Usage: "ipv4_gateway", ValStr: "192.168.10.1"},
|
||||
{Typ: cfgStr, Name: "ipv4_start", Usage: "IPV4开始地址", ValStr: "192.168.10.100"},
|
||||
@@ -47,8 +54,10 @@ var configs = []config{
|
||||
{Typ: cfgInt, Name: "cstp_dpd", Usage: "死链接检测时间(秒)", ValInt: 30},
|
||||
{Typ: cfgInt, Name: "mobile_keepalive", Usage: "移动端keepalive接检测时间(秒)", ValInt: 50},
|
||||
{Typ: cfgInt, Name: "mobile_dpd", Usage: "移动端死链接检测时间(秒)", ValInt: 60},
|
||||
{Typ: cfgInt, Name: "mtu", Usage: "最大传输单元MTU", ValInt: 1460},
|
||||
{Typ: cfgInt, Name: "session_timeout", Usage: "session过期时间(秒)", ValInt: 3600},
|
||||
// {Typ: cfgInt, Name: "auth_timeout", Usage: "auth_timeout", ValInt: 0},
|
||||
{Typ: cfgInt, Name: "audit_interval", Usage: "审计去重间隔(秒),-1关闭", ValInt: -1},
|
||||
}
|
||||
|
||||
var envs = map[string]string{}
|
||||
|
@@ -1,19 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
#################################
|
||||
# Set up Ethernet bridge on Linux
|
||||
# Requires: bridge-utils
|
||||
#################################
|
||||
#yum install bridge-utils
|
||||
|
||||
# Define Bridge Interface
|
||||
br="anylink0"
|
||||
|
||||
# Define physical ethernet interface to be bridged
|
||||
# with TAP interface(s) above.
|
||||
|
||||
# 请根据sever服务器信息,更新下面的信息
|
||||
eth="eth0"
|
||||
eth_ip="192.168.10.4"
|
||||
eth_netmask="255.255.255.0"
|
||||
eth_ip="192.168.10.4/24"
|
||||
eth_broadcast="192.168.10.255"
|
||||
eth_gateway="192.168.10.1"
|
||||
|
||||
@@ -21,11 +15,14 @@ eth_gateway="192.168.10.1"
|
||||
brctl addbr $br
|
||||
brctl addif $br $eth
|
||||
|
||||
ifconfig $eth 0.0.0.0 up
|
||||
ip addr del $eth_ip dev $eth
|
||||
ip addr add 0.0.0.0 dev $eth
|
||||
ip link set dev $eth up promisc on
|
||||
|
||||
mac=`cat /sys/class/net/$eth/address`
|
||||
ifconfig $br hw ether $mac
|
||||
ifconfig $br $eth_ip netmask $eth_netmask broadcast $eth_broadcast up
|
||||
ip link set dev $br up address $mac promisc on
|
||||
ip addr add $eth_ip broadcast $eth_broadcast dev $br
|
||||
|
||||
|
||||
route add default gateway $eth_gateway
|
||||
|
||||
|
34
server/conf/profile.xml
Normal file
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<AnyConnectProfile xmlns="http://schemas.xmlsoap.org/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://schemas.xmlsoap.org/encoding/ AnyConnectProfile.xsd">
|
||||
|
||||
<ClientInitialization>
|
||||
<UseStartBeforeLogon UserControllable="false">false</UseStartBeforeLogon>
|
||||
<StrictCertificateTrust>false</StrictCertificateTrust>
|
||||
<RestrictPreferenceCaching>false</RestrictPreferenceCaching>
|
||||
<RestrictTunnelProtocols>IPSec</RestrictTunnelProtocols>
|
||||
<BypassDownloader>true</BypassDownloader>
|
||||
<WindowsVPNEstablishment>AllowRemoteUsers</WindowsVPNEstablishment>
|
||||
<LinuxVPNEstablishment>AllowRemoteUsers</LinuxVPNEstablishment>
|
||||
<CertEnrollmentPin>pinAllowed</CertEnrollmentPin>
|
||||
<CertificateMatch>
|
||||
<KeyUsage>
|
||||
<MatchKey>Digital_Signature</MatchKey>
|
||||
</KeyUsage>
|
||||
<ExtendedKeyUsage>
|
||||
<ExtendedMatchKey>ClientAuth</ExtendedMatchKey>
|
||||
</ExtendedKeyUsage>
|
||||
</CertificateMatch>
|
||||
|
||||
<BackupServerList>
|
||||
<HostAddress>localhost</HostAddress>
|
||||
</BackupServerList>
|
||||
</ClientInitialization>
|
||||
|
||||
<ServerList>
|
||||
<HostEntry>
|
||||
<HostName>VPN Server</HostName>
|
||||
<HostAddress>localhost</HostAddress>
|
||||
</HostEntry>
|
||||
</ServerList>
|
||||
</AnyConnectProfile>
|
74
server/conf/server-sample.toml
Normal file
@@ -0,0 +1,74 @@
|
||||
#示例配置信息
|
||||
|
||||
#其他配置文件,可以使用绝对路径
|
||||
#或者相对于 anylink 二进制文件的路径
|
||||
|
||||
#数据文件
|
||||
db_type = "sqlite3"
|
||||
db_source = "./conf/anylink.db"
|
||||
#证书文件 使用跟nginx一样的证书即可
|
||||
cert_file = "./conf/vpn_cert.crt"
|
||||
cert_key = "./conf/vpn_cert.key"
|
||||
files_path = "./conf/files"
|
||||
profile = "./conf/profile.xml"
|
||||
#日志目录,为空写入标准输出
|
||||
#log_path = "./log"
|
||||
log_path = ""
|
||||
log_level = "debug"
|
||||
pprof = false
|
||||
|
||||
#系统名称
|
||||
issuer = "XX公司VPN"
|
||||
#后台管理用户
|
||||
admin_user = "admin"
|
||||
#pass 123456
|
||||
admin_pass = "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"
|
||||
jwt_secret = "abcdef.0123456789.abcdef"
|
||||
|
||||
|
||||
#服务监听地址
|
||||
server_addr = ":443"
|
||||
#开启 DTLS, 默认关闭
|
||||
server_dtls = false
|
||||
server_dtls_addr = ":4433"
|
||||
#后台服务监听地址
|
||||
admin_addr = ":8800"
|
||||
#开启tcp proxy protocol协议
|
||||
proxy_protocol = false
|
||||
|
||||
link_mode = "tun"
|
||||
|
||||
#客户端分配的ip地址池
|
||||
ipv4_master = "eth0"
|
||||
ipv4_cidr = "192.168.10.0/24"
|
||||
ipv4_gateway = "192.168.10.1"
|
||||
ipv4_start = "192.168.10.100"
|
||||
ipv4_end = "192.168.10.200"
|
||||
|
||||
#最大客户端数量
|
||||
max_client = 100
|
||||
#单个用户同时在线数量
|
||||
max_user_client = 3
|
||||
#IP租期(秒)
|
||||
ip_lease = 1209600
|
||||
|
||||
#默认选择的组
|
||||
default_group = "one"
|
||||
|
||||
#客户端失效检测时间(秒) dpd > keepalive
|
||||
cstp_keepalive = 20
|
||||
cstp_dpd = 30
|
||||
mobile_keepalive = 40
|
||||
mobile_dpd = 50
|
||||
|
||||
#设置最大传输单元
|
||||
mtu = 1460
|
||||
|
||||
#session过期时间,用于断线重连,0永不过期
|
||||
session_timeout = 3600
|
||||
auth_timeout = 0
|
||||
audit_interval = -1
|
||||
|
||||
|
||||
|
||||
|
@@ -1,20 +1,16 @@
|
||||
#服务配置信息
|
||||
#示例配置信息
|
||||
|
||||
#其他配置文件,可以使用绝对路径
|
||||
#或者相对于server.toml的路径
|
||||
#或者相对于 anylink 二进制文件的路径
|
||||
|
||||
#数据文件
|
||||
db_file = "./data.db"
|
||||
db_type = "sqlite3"
|
||||
db_source = "./conf/anylink.db"
|
||||
#证书文件
|
||||
cert_file = "./test_vpn_cert.pem"
|
||||
cert_key = "./test_vpn_key.pem"
|
||||
ui_path = "../ui"
|
||||
files_path = "../files"
|
||||
#日志目录,为空写入标准输出
|
||||
#log_path = "../log"
|
||||
log_path = ""
|
||||
cert_file = "./conf/vpn_cert.crt"
|
||||
cert_key = "./conf/vpn_cert.key"
|
||||
files_path = "./conf/files"
|
||||
log_level = "debug"
|
||||
pprof = false
|
||||
|
||||
#系统名称
|
||||
issuer = "XX公司VPN"
|
||||
@@ -22,46 +18,12 @@ issuer = "XX公司VPN"
|
||||
admin_user = "admin"
|
||||
#pass 123456
|
||||
admin_pass = "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"
|
||||
jwt_secret = "iLmspvOiz*%ovfcs*wersdf#heR8pNU4XxBm&mW$aPCjSRMbYH#&"
|
||||
|
||||
jwt_secret = "abcdef.0123456789.abcdef"
|
||||
|
||||
#服务监听地址
|
||||
server_addr = ":443"
|
||||
#开启 DTLS, 默认关闭
|
||||
server_dtls = false
|
||||
server_dtls_addr = ":4433"
|
||||
#后台服务监听地址
|
||||
admin_addr = ":8800"
|
||||
#开启tcp proxy protocol协议
|
||||
proxy_protocol = false
|
||||
|
||||
link_mode = "tun"
|
||||
|
||||
#客户端分配的ip地址池
|
||||
ipv4_cidr = "192.168.10.0/24"
|
||||
ipv4_gateway = "192.168.10.1"
|
||||
ipv4_start = "192.168.10.100"
|
||||
ipv4_end = "192.168.10.200"
|
||||
|
||||
#最大客户端数量
|
||||
max_client = 100
|
||||
#单个用户同时在线数量
|
||||
max_user_client = 3
|
||||
#IP租期(秒)
|
||||
ip_lease = 1209600
|
||||
|
||||
#默认选择的组
|
||||
default_group = "one"
|
||||
|
||||
#客户端失效检测时间(秒) dpd > keepalive
|
||||
cstp_keepalive = 20
|
||||
cstp_dpd = 30
|
||||
mobile_keepalive = 40
|
||||
mobile_dpd = 50
|
||||
#session过期时间,用于断线重连,0永不过期
|
||||
session_timeout = 3600
|
||||
auth_timeout = 0
|
||||
|
||||
|
||||
|
||||
|
||||
|
@@ -1,19 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDGDCCAgACCQCecQDpy/8hRTANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJD
|
||||
TjELMAkGA1UECAwCQkoxCzAJBgNVBAcMAkJKMQswCQYDVQQKDAJCRDELMAkGA1UE
|
||||
CwwCQkQxCzAJBgNVBAMMAkNTMB4XDTIxMDMyNjA5MTkwNloXDTMxMDMyNDA5MTkw
|
||||
NlowTjELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAlNIMQswCQYDVQQHDAJTSDELMAkG
|
||||
A1UECgwCVE0xCzAJBgNVBAsMAlRNMQswCQYDVQQDDAJDUzCCASIwDQYJKoZIhvcN
|
||||
AQEBBQADggEPADCCAQoCggEBAJtDxHduS8gjI0P6txHS+cODxKjyjNiCBa7tFgSc
|
||||
d9hRrzCvK4Q4M5StKJoSczmHl0C3HVoq92Gv1vENxq4irYdCrwLeOZGyt7urUlbs
|
||||
PkvEoVXxfAkPpue+JewG/CvGArJeP7UGsP5IrD0Dt5X1DP677K6qf5igzyaJqYJu
|
||||
RDJ5wR84BoDvY66Zc578N9tK9XusdJ63gQ5jGcG4Dneu1UX3g8lQkJ6P0xLXTh7W
|
||||
u5Sjx8axbDcFxbDLxNGL1yPgAjhIRgMfaWLwuQQg4WKFsdMljv1Flz8/h91z2xo+
|
||||
+E/B4YF0UFWTcWQ2TQ8w8noDqnnXVVQyOvuI3aajodml/f0CAwEAATANBgkqhkiG
|
||||
9w0BAQsFAAOCAQEAd89n0eWXgO1lqMciWmS9xY8Sj/U840bPo/4Kclsm1vFNvIXu
|
||||
I50PeaNiU2E5+CMk8AwXaJ5gDO7vsRxvLLRAUWZeuxSror2a0RkViEFW+UKcBuuB
|
||||
Izl9giXUhB/P85+We1ma5jizqj7OpzgMkzkcTZL2M6Gw6IWY4jopvLQjiCooSiYF
|
||||
wtLZjuFKfpLrPw5RgpWI4L8Hftbkmh6Q8nqcoQvgwm7rLrD5VqiTu7Rk1SXTFuXn
|
||||
uuazXasWIWRVGFuFcYP1rwyOfp9HhCFKngi0w8IRnbOcaPdXydtbKMcKt5z9zQX5
|
||||
BqrZ3ZfPp5HeklG7L8eQrnp4ines6YDshPnaRQ==
|
||||
-----END CERTIFICATE-----
|
@@ -1,27 +0,0 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEogIBAAKCAQEAm0PEd25LyCMjQ/q3EdL5w4PEqPKM2IIFru0WBJx32FGvMK8r
|
||||
hDgzlK0omhJzOYeXQLcdWir3Ya/W8Q3GriKth0KvAt45kbK3u6tSVuw+S8ShVfF8
|
||||
CQ+m574l7Ab8K8YCsl4/tQaw/kisPQO3lfUM/rvsrqp/mKDPJompgm5EMnnBHzgG
|
||||
gO9jrplznvw320r1e6x0nreBDmMZwbgOd67VRfeDyVCQno/TEtdOHta7lKPHxrFs
|
||||
NwXFsMvE0YvXI+ACOEhGAx9pYvC5BCDhYoWx0yWO/UWXPz+H3XPbGj74T8HhgXRQ
|
||||
VZNxZDZNDzDyegOqeddVVDI6+4jdpqOh2aX9/QIDAQABAoIBADWT2fz4g5AJiAbS
|
||||
QlAVRHjSRI+kOzQPEhT93SY0NCribRjYqaSTnEEGy8b27OoCPxBm3+sYfosoGXzP
|
||||
Kys17jmJqkjMFIORb1OEWAKEvS56KM42aX3a99ZqSD29X1Ffn9ibK1K1f2gP/deE
|
||||
K9rEV/qjMJZJYYRyoWkEAglvMXtU/NMRoTuFYtrJPr9sFEfpBFq97WpWiyMdLKTG
|
||||
MmlN+T1CXFQj/+mpv+DDSXcwLPBxAttDYE2GeqlhntId0I6cgaEGMO42D6fnqrKi
|
||||
PDilA/D6zos4o/bpRGvVBdXHqOXvX2stNHK+PvEX46GRd+OZhLh0KEcrWAx8cXs9
|
||||
ZhugTyECgYEAyffRPd98acL0OhXJR9mZTgDdotl7iYq+RTZbmEvAFst3mL3LA6Ba
|
||||
BTrwRLh9x8lzxoTQHHFaJL63kIrN6QAR9e3+pR0e8IX3vYCVGIlRCYB5CrE/O3Pi
|
||||
B9R17tCI5dFrFXYiST38sjwrWG9+geKarbUH5AZrZEO5uw0q7+4F3TkCgYEAxM1h
|
||||
Xo+xRt8RXoWZ6Cl66HhZKIvDcxkBtoNh54YLzrVpv0D+RvAWNDzRVXbbIUUpBGPN
|
||||
pHrwU8G0qWr4Q/Zx+vnckqotGMTNCB7vcmB/qwF9grNW9E0rCyIYLXtJcEiclJIF
|
||||
Oe406YXl7mSG1I6QjAADz8PNb4++Ct1+hVS56uUCgYAx9g/Y0nQgZY2s4L7N+1Il
|
||||
LammI06gE6ZF0NCPuA1oliSbsDeMShp6uL2/AjR7O6ZcMXaZ0qCN/m/CXdPaE55d
|
||||
y+X2SmHg9gL26dv4Gd/mDdXjgz01I9GCRlh2Hzf+QfPPd027+I2OObwvQEV3M+s3
|
||||
lVTCX6QpRWeokfVRLPxeYQKBgDIYPVK+rNdnbJps05JfDKQkDj3d5bBkiyUUKFWw
|
||||
r0y8rOA8AP25m01MtdRVXs4HNruhU/UsPgRz6DK/wdY64ySJeXXzz2rgnXgVt8mb
|
||||
eqPiyzn7wISLKAu7cAATw8vLD+BZku7+DYXryW13NULhzzVzw4SdSKu/IRbO7qet
|
||||
u21pAoGAd2mBJ+PWKnUkARS8gQ3Y3cagA/qGGr094P9relglRDBv/Pm7kTUt6K8B
|
||||
NnpqWydcVtcrXmNzGRx4ftm18SzmTJEohF14nF9424q4aiWoNZyG8adxaI0Yqv3G
|
||||
LnH8n2fzC+pf31LijBRM8DRnepah64mLF+OM/SxgVg1nP9jVUG4=
|
||||
-----END RSA PRIVATE KEY-----
|
61
server/conf/vpn_cert.crt
Normal file
@@ -0,0 +1,61 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIF9zCCBN+gAwIBAgIQBNH+cm5YH1O2NhfT+zB+ATANBgkqhkiG9w0BAQsFADBu
|
||||
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
|
||||
d3cuZGlnaWNlcnQuY29tMS0wKwYDVQQDEyRFbmNyeXB0aW9uIEV2ZXJ5d2hlcmUg
|
||||
RFYgVExTIENBIC0gRzEwHhcNMjExMjEyMDAwMDAwWhcNMjIxMjEzMjM1OTU5WjAc
|
||||
MRowGAYDVQQDExF2cG4udGVzdC52cWlsdS5jbjCCASIwDQYJKoZIhvcNAQEBBQAD
|
||||
ggEPADCCAQoCggEBAK2XO6Na//i0sMiV0nF+aDTbDibGiTLr+LFlhTIi1KX9IAU2
|
||||
Xboz1B8cxDro3g+CzgrGg0YMI4CxBiY56UT3jUTsLYBNpWPkbhlH+mpf0J7fgH29
|
||||
V1LAZKm2qR28y/krKHIbcGrfMAbXi6iVkVHhc+edvGCdAiDSyJgVSZbYV/s0LXLF
|
||||
0B0BokagwtvGIx7ik5uG4exuRCUKE3z0n6RXdN0eWBvKKHFhWEeaBIGzHjoDgAx/
|
||||
4VJ8XsW0tcwByiVRqpMFa1eG3HLMvi34M1qLzNv7dGPIkr1zjvlvTqhDpimXOi9C
|
||||
4N5ZOfZfNAyR8zU5+tBqSCvByavxLJwC//F7VQcCAwEAAaOCAuEwggLdMB8GA1Ud
|
||||
IwQYMBaAFFV0T7JyT/VgulDR1+ZRXJoBhxrXMB0GA1UdDgQWBBQKyNOGPzBPyqY9
|
||||
nxahHC+B6xT83TAcBgNVHREEFTATghF2cG4udGVzdC52cWlsdS5jbjAOBgNVHQ8B
|
||||
Af8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMD4GA1UdIAQ3
|
||||
MDUwMwYGZ4EMAQIBMCkwJwYIKwYBBQUHAgEWG2h0dHA6Ly93d3cuZGlnaWNlcnQu
|
||||
Y29tL0NQUzCBgAYIKwYBBQUHAQEEdDByMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz
|
||||
cC5kaWdpY2VydC5jb20wSgYIKwYBBQUHMAKGPmh0dHA6Ly9jYWNlcnRzLmRpZ2lj
|
||||
ZXJ0LmNvbS9FbmNyeXB0aW9uRXZlcnl3aGVyZURWVExTQ0EtRzEuY3J0MAkGA1Ud
|
||||
EwQCMAAwggF+BgorBgEEAdZ5AgQCBIIBbgSCAWoBaAB2ACl5vvCeOTkh8FZzn2Ol
|
||||
d+W+V32cYAr4+U1dJlwlXceEAAABfa0lBgAAAAQDAEcwRQIgEQ4wS5gyLMK30aeD
|
||||
xF3kWvsUhkd94HKIl13ckYnukGMCIQD1/6fFUAPjdw2k8f/ctJ7STUHeA1WoBy5H
|
||||
O/iXBRCkWgB2AFGjsPX9AXmcVm24N3iPDKR6zBsny/eeiEKaDf7UiwXlAAABfa0l
|
||||
BmYAAAQDAEcwRQIgOoguGrrlpwoxGiJHJNcEWbuH2AOJCDSDiun80DX9hUwCIQCJ
|
||||
cFCOe5E5VbgHrTWbQ0OUFS0epDgUiG8y9kjfkN1M5QB2AEHIyrHfIkZKEMahOglC
|
||||
h15OMYsbA+vrS8do8JBilgb2AAABfa0lBfoAAAQDAEcwRQIhAIHCUjXv+M3/jFOU
|
||||
AzjjMCISczShjqQ5FKqsIYNTUN46AiAom+II914ifwdFiS2xWI0ncSj8cxH6f+WZ
|
||||
UUQj9RczMDANBgkqhkiG9w0BAQsFAAOCAQEALj5oEwyU+gxVKhLFrBBtkoi9F0HQ
|
||||
jjSQZvOcKApSXjKS11VdmLGKuy85FSocw7VvDtZ4o43OhO79GMAMiPXroTnPIS5O
|
||||
ZNxfuusF6HpS+2Dq9UidnlxQmIaJ4A7PkX+NqAI4V6yr839SXKyHJROfXf9hNoJZ
|
||||
PJeZ94oMwXdeNjFkOismFpvaZcYq7t51xi5tkH/NaJHV5FEU8Or4zk/OoaPe3r+b
|
||||
2hpltIIaapoNVYLWLW7YS7hlvhjfwPypsR3ev4bTRWvT1tu9+AE+TG0OZqeWGucP
|
||||
6MjZI5gecOnkQVmBovkRi2lr26PDWrwnAlyoMI3ioU1XaTftIrBL2YalfQ==
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEqjCCA5KgAwIBAgIQAnmsRYvBskWr+YBTzSybsTANBgkqhkiG9w0BAQsFADBh
|
||||
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
|
||||
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
|
||||
QTAeFw0xNzExMjcxMjQ2MTBaFw0yNzExMjcxMjQ2MTBaMG4xCzAJBgNVBAYTAlVT
|
||||
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
|
||||
b20xLTArBgNVBAMTJEVuY3J5cHRpb24gRXZlcnl3aGVyZSBEViBUTFMgQ0EgLSBH
|
||||
MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALPeP6wkab41dyQh6mKc
|
||||
oHqt3jRIxW5MDvf9QyiOR7VfFwK656es0UFiIb74N9pRntzF1UgYzDGu3ppZVMdo
|
||||
lbxhm6dWS9OK/lFehKNT0OYI9aqk6F+U7cA6jxSC+iDBPXwdF4rs3KRyp3aQn6pj
|
||||
pp1yr7IB6Y4zv72Ee/PlZ/6rK6InC6WpK0nPVOYR7n9iDuPe1E4IxUMBH/T33+3h
|
||||
yuH3dvfgiWUOUkjdpMbyxX+XNle5uEIiyBsi4IvbcTCh8ruifCIi5mDXkZrnMT8n
|
||||
wfYCV6v6kDdXkbgGRLKsR4pucbJtbKqIkUGxuZI2t7pfewKRc5nWecvDBZf3+p1M
|
||||
pA8CAwEAAaOCAU8wggFLMB0GA1UdDgQWBBRVdE+yck/1YLpQ0dfmUVyaAYca1zAf
|
||||
BgNVHSMEGDAWgBQD3lA1VtFMu2bwo+IbG8OXsj3RVTAOBgNVHQ8BAf8EBAMCAYYw
|
||||
HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMBIGA1UdEwEB/wQIMAYBAf8C
|
||||
AQAwNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdp
|
||||
Y2VydC5jb20wQgYDVR0fBDswOTA3oDWgM4YxaHR0cDovL2NybDMuZGlnaWNlcnQu
|
||||
Y29tL0RpZ2lDZXJ0R2xvYmFsUm9vdENBLmNybDBMBgNVHSAERTBDMDcGCWCGSAGG
|
||||
/WwBAjAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20vQ1BT
|
||||
MAgGBmeBDAECATANBgkqhkiG9w0BAQsFAAOCAQEAK3Gp6/aGq7aBZsxf/oQ+TD/B
|
||||
SwW3AU4ETK+GQf2kFzYZkby5SFrHdPomunx2HBzViUchGoofGgg7gHW0W3MlQAXW
|
||||
M0r5LUvStcr82QDWYNPaUy4taCQmyaJ+VB+6wxHstSigOlSNF2a6vg4rgexixeiV
|
||||
4YSB03Yqp2t3TeZHM9ESfkus74nQyW7pRGezj+TC44xCagCQQOzzNmzEAP2SnCrJ
|
||||
sNE2DpRVMnL8J6xBRdjmOsC3N6cQuKuRXbzByVBjCqAA8t1L0I+9wXJerLPyErjy
|
||||
rMKWaBFLmfK/AHNF4ZihwPGOc7w6UHczBZXH5RFzJNnww+WnKuTPI0HfnVH8lg==
|
||||
-----END CERTIFICATE-----
|
27
server/conf/vpn_cert.key
Normal file
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEArZc7o1r/+LSwyJXScX5oNNsOJsaJMuv4sWWFMiLUpf0gBTZd
|
||||
ujPUHxzEOujeD4LOCsaDRgwjgLEGJjnpRPeNROwtgE2lY+RuGUf6al/Qnt+Afb1X
|
||||
UsBkqbapHbzL+Ssochtwat8wBteLqJWRUeFz5528YJ0CINLImBVJlthX+zQtcsXQ
|
||||
HQGiRqDC28YjHuKTm4bh7G5EJQoTfPSfpFd03R5YG8oocWFYR5oEgbMeOgOADH/h
|
||||
UnxexbS1zAHKJVGqkwVrV4bccsy+LfgzWovM2/t0Y8iSvXOO+W9OqEOmKZc6L0Lg
|
||||
3lk59l80DJHzNTn60GpIK8HJq/EsnAL/8XtVBwIDAQABAoIBACXjPEELO5Ms3Ojq
|
||||
ymO7E0N2DECqVIeouT7+yXOH5qHT/YkltI9PgJzJyoqRCOaZxh7T9RL000rjWFQ/
|
||||
j4pd/ZdtdQDr8Y077kvWSfGtt/r1DTZkfQqys0XXeFHlQx+/K7S8CG1LCVB0+yZw
|
||||
fqdAbeu/ob30huJjHyUSgF1MGufYvuII6x0CGORwzruWWFniXkg2z+9SP4x4RSfm
|
||||
exMUE4T4tlzR63QaW02xWEDTWCSQw/FgjpCWwryDVCmnLf63UhI+4hITqZLL+ROd
|
||||
sG/8Yp284q7BYBKk4/N1HD4W1vU+dls3glxZ22NCQKx+2RVtqTrRUd/d4AnxOmMR
|
||||
dnfh4AECgYEA7cl9NIRrtQdW+KFcoSdyP2F+SU74nSAh6Uolzwr9lHB+NbMJ5g79
|
||||
eU1zp3RAvSFg249L4cnceaFL1LTPcNN0xhpaJ7v5FQWk5tkddSmy2T3CAh8VwLXF
|
||||
487pgakO1SpS6uz+BtwsAFOS8k/GjYeSbPR4e9F/FbYAvGYwOLNj2ocCgYEAuuL8
|
||||
xnFnt95TwWptu4T97YXTeZRB17jiH1BhX+QawsSafagsWlSKihKMxYhfCHiwztS/
|
||||
KsCnkS6cH9slU3y4gvCiT1S4z1Qkw93ljUQXCzRIVEd9SxXoQMeRi+/5c239Fhnu
|
||||
aoxESAFWNXJZ5r9Jp3qukHvEtYn2FoE1Zkmu0YECgYApULgDdvqr4pGW85p/mbX9
|
||||
Ezh5DlKeImYh/bMiDTvQHdegBvKyWWprOCzfLJDPC8yjeXtqyMMZExB07dGZPfRt
|
||||
M0j03HFD2M41GgZHRC6CFnvuGG6UJEE0+s+Rqskb+pWbof/lOz4d9Gd02K2cC7FC
|
||||
YxvID7dwE0Z/dZXtVCYGYwKBgQCjckPKtoIUcBBmV1NzLiP66REEAuL27Q5ufpk7
|
||||
CT9SWioXfc6Ujd3AVeriE5uxyAQyUCSFGosy0UXgIoRpmOmyMwxxP1KGmTuyRc4u
|
||||
l39j4Czl8MQmuBkxFpk3fwB2sJopCzLV4qkRJIImKkVwJpofLI+hc22dq/QayJRQ
|
||||
Sl7ngQKBgQCkfcbQDvhkL6QKUC/K7MDGw9JMICLUpRyp6D3ibeL7i6WO6dkKde2t
|
||||
O/oLz2XvG0NR0nulhThpWUdyUWco3FZ038jiuY8ZZum5wdVBDOcDcnuBisE3Kzh8
|
||||
p7WycoWItAVxmyTKzHJIZ7pFQULYjap7gFSUPE9uBQZu09VKBtGPHA==
|
||||
-----END RSA PRIVATE KEY-----
|
@@ -1,70 +1,128 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/asdine/storm/v3/codec/json"
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
bolt "go.etcd.io/bbolt"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/lib/pq"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
var (
|
||||
sdb *storm.DB
|
||||
xdb *xorm.Engine
|
||||
)
|
||||
|
||||
func GetXdb() *xorm.Engine {
|
||||
return xdb
|
||||
}
|
||||
|
||||
func initDb() {
|
||||
var err error
|
||||
sdb, err = storm.Open(base.Cfg.DbFile, storm.Codec(json.Codec),
|
||||
storm.BoltOptions(0600, &bolt.Options{Timeout: 10 * time.Second}))
|
||||
xdb, err = xorm.NewEngine(base.Cfg.DbType, base.Cfg.DbSource)
|
||||
// xdb.ShowSQL(true)
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
|
||||
// 初始化数据库
|
||||
err = sdb.Init(&User{})
|
||||
err = xdb.Sync2(&User{}, &Setting{}, &Group{}, &IpMap{}, &AccessAudit{}, &Policy{})
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
|
||||
// fmt.Println("s1")
|
||||
// fmt.Println("s1=============", err)
|
||||
}
|
||||
|
||||
func initData() {
|
||||
var (
|
||||
err error
|
||||
install bool
|
||||
err error
|
||||
)
|
||||
|
||||
// 判断是否初次使用
|
||||
err = Get(SettingBucket, Installed, &install)
|
||||
if err == nil && install {
|
||||
install := &SettingInstall{}
|
||||
err = SettingGet(install)
|
||||
|
||||
if err == nil && install.Installed {
|
||||
// 已经安装过
|
||||
return
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = Set(SettingBucket, Installed, true)
|
||||
}()
|
||||
|
||||
smtp := &SettingSmtp{
|
||||
Host: "127.0.0.1",
|
||||
Port: 25,
|
||||
From: "vpn@xx.com",
|
||||
// 发生错误
|
||||
if err != ErrNotFound {
|
||||
base.Fatal(err)
|
||||
}
|
||||
_ = SettingSet(smtp)
|
||||
|
||||
err = addInitData()
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func addInitData() error {
|
||||
var (
|
||||
err error
|
||||
)
|
||||
|
||||
sess := xdb.NewSession()
|
||||
defer sess.Close()
|
||||
|
||||
err = sess.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// SettingSmtp
|
||||
smtp := &SettingSmtp{
|
||||
Host: "127.0.0.1",
|
||||
Port: 25,
|
||||
From: "vpn@xx.com",
|
||||
Encryption: "None",
|
||||
}
|
||||
err = SettingSessAdd(sess, smtp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// SettingOther
|
||||
other := &SettingOther{
|
||||
LinkAddr: "vpn.xx.com",
|
||||
Banner: "您已接入公司网络,请按照公司规定使用。\n请勿进行非工作下载及视频行为!",
|
||||
AccountMail: accountMail,
|
||||
}
|
||||
_ = SettingSet(other)
|
||||
err = SettingSessAdd(sess, other)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Install
|
||||
install := &SettingInstall{Installed: true}
|
||||
err = SettingSessAdd(sess, install)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = sess.Commit()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
g1 := Group{
|
||||
Name: "ops",
|
||||
AllowLan: true,
|
||||
ClientDns: []ValData{{Val: "114.114.114.114"}},
|
||||
RouteInclude: []ValData{{Val: All}},
|
||||
}
|
||||
err = SetGroup(&g1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func CheckErrNotFound(err error) bool {
|
||||
return err == storm.ErrNotFound
|
||||
return err == ErrNotFound
|
||||
}
|
||||
|
||||
const accountMail = `<p>您好:</p>
|
||||
|
@@ -1,66 +1,84 @@
|
||||
package dbdata
|
||||
|
||||
import "github.com/asdine/storm/v3/index"
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
const PageSize = 10
|
||||
|
||||
func Save(data interface{}) error {
|
||||
return sdb.Save(data)
|
||||
var ErrNotFound = errors.New("ErrNotFound")
|
||||
|
||||
func Add(data interface{}) error {
|
||||
_, err := xdb.InsertOne(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func Update(data interface{}) error {
|
||||
return sdb.Update(data)
|
||||
}
|
||||
|
||||
func UpdateField(data interface{}, fieldName string, value interface{}) error {
|
||||
return sdb.UpdateField(data, fieldName, value)
|
||||
func Update(fieldName string, value interface{}, data interface{}) error {
|
||||
_, err := xdb.Where(fieldName+"=?", value).Update(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func Del(data interface{}) error {
|
||||
return sdb.DeleteStruct(data)
|
||||
_, err := xdb.Delete(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func Set(bucket, key string, data interface{}) error {
|
||||
return sdb.Set(bucket, key, data)
|
||||
func extract(data interface{}, fieldName string) interface{} {
|
||||
ref := reflect.ValueOf(data)
|
||||
r := &ref
|
||||
if r.Kind() == reflect.Ptr {
|
||||
e := r.Elem()
|
||||
r = &e
|
||||
}
|
||||
field := r.FieldByName(fieldName).Interface()
|
||||
return field
|
||||
}
|
||||
|
||||
func Get(bucket, key string, data interface{}) error {
|
||||
return sdb.Get(bucket, key, data)
|
||||
// 更新全部字段
|
||||
func Set(data interface{}) error {
|
||||
id := extract(data, "Id")
|
||||
_, err := xdb.ID(id).AllCols().Update(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func One(fieldName string, value interface{}, data interface{}) error {
|
||||
has, err := xdb.Where(fieldName+"=?", value).Get(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func CountAll(data interface{}) int {
|
||||
n, _ := sdb.Count(data)
|
||||
return n
|
||||
n, _ := xdb.Count(data)
|
||||
return int(n)
|
||||
}
|
||||
|
||||
func One(fieldName string, value interface{}, to interface{}) error {
|
||||
return sdb.One(fieldName, value, to)
|
||||
}
|
||||
|
||||
func Find(fieldName string, value interface{}, to interface{}, options ...func(q *index.Options)) error {
|
||||
return sdb.Find(fieldName, value, to, options...)
|
||||
}
|
||||
|
||||
func All(to interface{}, limit, page int) error {
|
||||
opt := getOpt(limit, page)
|
||||
return sdb.All(to, opt)
|
||||
}
|
||||
|
||||
func Prefix(fieldName string, prefix string, to interface{}, limit, page int) error {
|
||||
opt := getOpt(limit, page)
|
||||
return sdb.Prefix(fieldName, prefix, to, opt)
|
||||
}
|
||||
|
||||
func getOpt(limit, page int) func(*index.Options) {
|
||||
skip := (page - 1) * limit
|
||||
opt := func(opt *index.Options) {
|
||||
opt.Reverse = true
|
||||
if limit > 0 {
|
||||
opt.Limit = limit
|
||||
}
|
||||
if skip > 0 {
|
||||
opt.Skip = skip
|
||||
}
|
||||
func Find(data interface{}, limit, page int) error {
|
||||
if limit == 0 {
|
||||
return xdb.Find(data)
|
||||
}
|
||||
return opt
|
||||
|
||||
start := (page - 1) * limit
|
||||
return xdb.Limit(limit, start).Find(data)
|
||||
}
|
||||
|
||||
func CountPrefix(fieldName string, prefix string, data interface{}) int {
|
||||
n, _ := xdb.Where(fieldName+" like ?", prefix+"%").Count(data)
|
||||
return int(n)
|
||||
}
|
||||
|
||||
func Prefix(fieldName string, prefix string, data interface{}, limit, page int) error {
|
||||
where := xdb.Where(fieldName+" like ?", prefix+"%")
|
||||
if limit == 0 {
|
||||
return where.Find(data)
|
||||
}
|
||||
|
||||
start := (page - 1) * limit
|
||||
return where.Limit(limit, start).Find(data)
|
||||
}
|
||||
|
@@ -11,12 +11,13 @@ import (
|
||||
|
||||
func preIpData() {
|
||||
tmpDb := path.Join(os.TempDir(), "anylink_test.db")
|
||||
base.Cfg.DbFile = tmpDb
|
||||
base.Cfg.DbType = "sqlite3"
|
||||
base.Cfg.DbSource = tmpDb
|
||||
initDb()
|
||||
}
|
||||
|
||||
func closeIpdata() {
|
||||
sdb.Close()
|
||||
xdb.Close()
|
||||
tmpDb := path.Join(os.TempDir(), "anylink_test.db")
|
||||
os.Remove(tmpDb)
|
||||
}
|
||||
@@ -27,7 +28,7 @@ func TestDb(t *testing.T) {
|
||||
defer closeIpdata()
|
||||
|
||||
u := User{Username: "a"}
|
||||
err := Save(&u)
|
||||
err := Add(&u)
|
||||
ast.Nil(err)
|
||||
|
||||
ast.Equal(u.Id, 1)
|
||||
|
@@ -4,6 +4,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
const (
|
||||
Allow = "allow"
|
||||
Deny = "deny"
|
||||
All = "all"
|
||||
)
|
||||
|
||||
type GroupLinkAcl struct {
|
||||
@@ -29,24 +32,27 @@ type ValData struct {
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
Id int `json:"id" storm:"id,increment"`
|
||||
Name string `json:"name" storm:"unique"`
|
||||
Note string `json:"note"`
|
||||
AllowLan bool `json:"allow_lan"`
|
||||
ClientDns []ValData `json:"client_dns"`
|
||||
RouteInclude []ValData `json:"route_include"`
|
||||
RouteExclude []ValData `json:"route_exclude"`
|
||||
LinkAcl []GroupLinkAcl `json:"link_acl"`
|
||||
Bandwidth int `json:"bandwidth"` // 带宽限制
|
||||
Status int8 `json:"status"` // 1正常
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
// type Group struct {
|
||||
// Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
// Name string `json:"name" xorm:"varchar(60) not null unique"`
|
||||
// Note string `json:"note" xorm:"varchar(255)"`
|
||||
// AllowLan bool `json:"allow_lan" xorm:"Bool"`
|
||||
// ClientDns []ValData `json:"client_dns" xorm:"Text"`
|
||||
// RouteInclude []ValData `json:"route_include" xorm:"Text"`
|
||||
// RouteExclude []ValData `json:"route_exclude" xorm:"Text"`
|
||||
// DsExcludeDomains string `json:"ds_exclude_domains" xorm:"Text"`
|
||||
// DsIncludeDomains string `json:"ds_include_domains" xorm:"Text"`
|
||||
// LinkAcl []GroupLinkAcl `json:"link_acl" xorm:"Text"`
|
||||
// Bandwidth int `json:"bandwidth" xorm:"Int"` // 带宽限制
|
||||
// Auth map[string]interface{} `json:"auth" xorm:"not null default '{}' varchar(255)"` // 认证方式
|
||||
// Status int8 `json:"status" xorm:"Int"` // 1正常
|
||||
// CreatedAt time.Time `json:"created_at" xorm:"DateTime created"`
|
||||
// UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
// }
|
||||
|
||||
func GetGroupNames() []string {
|
||||
var datas []Group
|
||||
err := All(&datas, 0, 0)
|
||||
err := Find(&datas, 0, 0)
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
return nil
|
||||
@@ -65,20 +71,14 @@ func SetGroup(g *Group) error {
|
||||
}
|
||||
|
||||
// 判断数据
|
||||
clientDns := []ValData{}
|
||||
for _, v := range g.ClientDns {
|
||||
if v.Val != "" {
|
||||
clientDns = append(clientDns, v)
|
||||
}
|
||||
}
|
||||
if len(clientDns) == 0 {
|
||||
return errors.New("DNS 错误")
|
||||
}
|
||||
g.ClientDns = clientDns
|
||||
|
||||
routeInclude := []ValData{}
|
||||
for _, v := range g.RouteInclude {
|
||||
if v.Val != "" {
|
||||
if v.Val == All {
|
||||
routeInclude = append(routeInclude, v)
|
||||
continue
|
||||
}
|
||||
|
||||
ipMask, _, err := parseIpNet(v.Val)
|
||||
if err != nil {
|
||||
return errors.New("RouteInclude 错误" + err.Error())
|
||||
@@ -115,8 +115,67 @@ func SetGroup(g *Group) error {
|
||||
}
|
||||
g.LinkAcl = linkAcl
|
||||
|
||||
// DNS 判断
|
||||
clientDns := []ValData{}
|
||||
for _, v := range g.ClientDns {
|
||||
if v.Val != "" {
|
||||
ip := net.ParseIP(v.Val)
|
||||
if ip.String() != v.Val {
|
||||
return errors.New("DNS IP 错误")
|
||||
}
|
||||
clientDns = append(clientDns, v)
|
||||
}
|
||||
}
|
||||
if len(routeInclude) == 0 || (len(routeInclude) == 1 && routeInclude[0].Val == "all") {
|
||||
if len(clientDns) == 0 {
|
||||
return errors.New("默认路由,必须设置一个DNS")
|
||||
}
|
||||
}
|
||||
g.ClientDns = clientDns
|
||||
// 域名拆分隧道,不能同时填写
|
||||
g.DsIncludeDomains = strings.TrimSpace(g.DsIncludeDomains)
|
||||
g.DsExcludeDomains = strings.TrimSpace(g.DsExcludeDomains)
|
||||
if g.DsIncludeDomains != "" && g.DsExcludeDomains != "" {
|
||||
return errors.New("包含/排除域名不能同时填写")
|
||||
}
|
||||
// 校验包含域名的格式
|
||||
err = CheckDomainNames(g.DsIncludeDomains)
|
||||
if err != nil {
|
||||
return errors.New("包含域名有误:" + err.Error())
|
||||
}
|
||||
// 校验排除域名的格式
|
||||
err = CheckDomainNames(g.DsExcludeDomains)
|
||||
if err != nil {
|
||||
return errors.New("排除域名有误:" + err.Error())
|
||||
}
|
||||
// 处理登入方式的逻辑
|
||||
defAuth := map[string]interface{}{
|
||||
"type": "local",
|
||||
}
|
||||
if len(g.Auth) == 0 {
|
||||
g.Auth = defAuth
|
||||
}
|
||||
authType := g.Auth["type"].(string)
|
||||
if authType == "local" {
|
||||
g.Auth = defAuth
|
||||
} else {
|
||||
_, ok := authRegistry[authType]
|
||||
if !ok {
|
||||
return errors.New("未知的认证方式: " + authType)
|
||||
}
|
||||
auth := makeInstance(authType).(IUserAuth)
|
||||
err = auth.checkData(g.Auth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
g.UpdatedAt = time.Now()
|
||||
err = Save(g)
|
||||
if g.Id > 0 {
|
||||
err = Set(g)
|
||||
} else {
|
||||
err = Add(g)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -132,3 +191,24 @@ func parseIpNet(s string) (string, *net.IPNet, error) {
|
||||
|
||||
return ipMask, ipNet, nil
|
||||
}
|
||||
|
||||
func CheckDomainNames(domains string) error {
|
||||
if domains == "" {
|
||||
return nil
|
||||
}
|
||||
str_slice := strings.Split(domains, ",")
|
||||
for _, val := range str_slice {
|
||||
if val == "" {
|
||||
return errors.New(val + " 请以逗号分隔域名")
|
||||
}
|
||||
if !ValidateDomainName(val) {
|
||||
return errors.New(val + " 域名有误")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateDomainName(domain string) bool {
|
||||
RegExp := regexp.MustCompile(`^([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+[A-Za-z]{2,18}$`)
|
||||
return RegExp.MatchString(domain)
|
||||
}
|
||||
|
@@ -24,8 +24,25 @@ func TestGetGroupNames(t *testing.T) {
|
||||
err = SetGroup(&g3)
|
||||
ast.Nil(err)
|
||||
|
||||
authData := map[string]interface{}{
|
||||
"type": "radius",
|
||||
"radius": map[string]string{
|
||||
"addr": "192.168.8.12:1044",
|
||||
"secret": "43214132",
|
||||
},
|
||||
}
|
||||
g4 := Group{Name: "g4", ClientDns: []ValData{{Val: "114.114.114.114"}}, Auth: authData}
|
||||
err = SetGroup(&g4)
|
||||
ast.Nil(err)
|
||||
g5 := Group{Name: "g5", ClientDns: []ValData{{Val: "114.114.114.114"}}, DsIncludeDomains: "baidu.com,163.com"}
|
||||
err = SetGroup(&g5)
|
||||
ast.Nil(err)
|
||||
g6 := Group{Name: "g6", ClientDns: []ValData{{Val: "114.114.114.114"}}, DsExcludeDomains: "com.cn,qq.com"}
|
||||
err = SetGroup(&g6)
|
||||
ast.Nil(err)
|
||||
|
||||
// 判断所有数据
|
||||
gAll := []string{"g1", "g2", "g3"}
|
||||
gAll := []string{"g1", "g2", "g3", "g4", "g5", "g6"}
|
||||
gs := GetGroupNames()
|
||||
for _, v := range gs {
|
||||
ast.Equal(true, utils.InArrStr(gAll, v))
|
||||
|
@@ -1,18 +1,34 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"net"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type IpMap struct {
|
||||
Id int `json:"id" storm:"id,increment"`
|
||||
IpAddr net.IP `json:"ip_addr" storm:"unique"`
|
||||
MacAddr string `json:"mac_addr" storm:"unique"`
|
||||
Username string `json:"username"`
|
||||
Keep bool `json:"keep"` // 保留 ip-mac 绑定
|
||||
KeepTime time.Time `json:"keep_time"`
|
||||
Note string `json:"note"` // 备注
|
||||
LastLogin time.Time `json:"last_login"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// type IpMap struct {
|
||||
// Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
// IpAddr string `json:"ip_addr" xorm:"not null unique"`
|
||||
// MacAddr string `json:"mac_addr" xorm:"not null unique"`
|
||||
// Username string `json:"username"`
|
||||
// Keep bool `json:"keep"` // 保留 ip-mac 绑定
|
||||
// KeepTime time.Time `json:"keep_time"`
|
||||
// Note string `json:"note"` // 备注
|
||||
// LastLogin time.Time `json:"last_login"`
|
||||
// UpdatedAt time.Time `json:"updated_at"`
|
||||
// }
|
||||
|
||||
func SetIpMap(v *IpMap) error {
|
||||
var err error
|
||||
|
||||
if len(v.IpAddr) < 4 || len(v.MacAddr) < 6 {
|
||||
return errors.New("IP或MAC错误")
|
||||
}
|
||||
|
||||
v.UpdatedAt = time.Now()
|
||||
if v.Id > 0 {
|
||||
err = Set(v)
|
||||
} else {
|
||||
err = Add(v)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
101
server/dbdata/policy.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetPolicy(Username string) *Policy {
|
||||
policyData := &Policy{}
|
||||
err := One("Username", Username, policyData)
|
||||
if err != nil {
|
||||
return policyData
|
||||
}
|
||||
return policyData
|
||||
}
|
||||
|
||||
func SetPolicy(p *Policy) error {
|
||||
var err error
|
||||
if p.Username == "" {
|
||||
return errors.New("用户名错误")
|
||||
}
|
||||
|
||||
// 包含路由
|
||||
routeInclude := []ValData{}
|
||||
for _, v := range p.RouteInclude {
|
||||
if v.Val != "" {
|
||||
if v.Val == All {
|
||||
routeInclude = append(routeInclude, v)
|
||||
continue
|
||||
}
|
||||
|
||||
ipMask, _, err := parseIpNet(v.Val)
|
||||
if err != nil {
|
||||
return errors.New("RouteInclude 错误" + err.Error())
|
||||
}
|
||||
|
||||
v.IpMask = ipMask
|
||||
routeInclude = append(routeInclude, v)
|
||||
}
|
||||
}
|
||||
p.RouteInclude = routeInclude
|
||||
// 排除路由
|
||||
routeExclude := []ValData{}
|
||||
for _, v := range p.RouteExclude {
|
||||
if v.Val != "" {
|
||||
ipMask, _, err := parseIpNet(v.Val)
|
||||
if err != nil {
|
||||
return errors.New("RouteExclude 错误" + err.Error())
|
||||
}
|
||||
v.IpMask = ipMask
|
||||
routeExclude = append(routeExclude, v)
|
||||
}
|
||||
}
|
||||
p.RouteExclude = routeExclude
|
||||
|
||||
// DNS 判断
|
||||
clientDns := []ValData{}
|
||||
for _, v := range p.ClientDns {
|
||||
if v.Val != "" {
|
||||
ip := net.ParseIP(v.Val)
|
||||
if ip.String() != v.Val {
|
||||
return errors.New("DNS IP 错误")
|
||||
}
|
||||
clientDns = append(clientDns, v)
|
||||
}
|
||||
}
|
||||
if len(routeInclude) == 0 || (len(routeInclude) == 1 && routeInclude[0].Val == "all") {
|
||||
if len(clientDns) == 0 {
|
||||
return errors.New("默认路由,必须设置一个DNS")
|
||||
}
|
||||
}
|
||||
p.ClientDns = clientDns
|
||||
|
||||
// 域名拆分隧道,不能同时填写
|
||||
p.DsIncludeDomains = strings.TrimSpace(p.DsIncludeDomains)
|
||||
p.DsExcludeDomains = strings.TrimSpace(p.DsExcludeDomains)
|
||||
if p.DsIncludeDomains != "" && p.DsExcludeDomains != "" {
|
||||
return errors.New("包含/排除域名不能同时填写")
|
||||
}
|
||||
// 校验包含域名的格式
|
||||
err = CheckDomainNames(p.DsIncludeDomains)
|
||||
if err != nil {
|
||||
return errors.New("包含域名有误:" + err.Error())
|
||||
}
|
||||
// 校验排除域名的格式
|
||||
err = CheckDomainNames(p.DsExcludeDomains)
|
||||
if err != nil {
|
||||
return errors.New("排除域名有误:" + err.Error())
|
||||
}
|
||||
|
||||
p.UpdatedAt = time.Now()
|
||||
if p.Id > 0 {
|
||||
err = Set(p)
|
||||
} else {
|
||||
err = Add(p)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
45
server/dbdata/policy_test.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetPolicy(t *testing.T) {
|
||||
ast := assert.New(t)
|
||||
|
||||
preIpData()
|
||||
defer closeIpdata()
|
||||
|
||||
// 添加 Policy
|
||||
p1 := Policy{Username: "a1", ClientDns: []ValData{{Val: "114.114.114.114"}}, DsExcludeDomains: "baidu.com,163.com"}
|
||||
err := SetPolicy(&p1)
|
||||
ast.Nil(err)
|
||||
|
||||
p2 := Policy{Username: "a2", ClientDns: []ValData{{Val: "114.114.114.114"}}, DsExcludeDomains: "com.cn,qq.com"}
|
||||
err = SetPolicy(&p2)
|
||||
ast.Nil(err)
|
||||
|
||||
route := []ValData{{Val: "192.168.1.1/24"}}
|
||||
p3 := Policy{Username: "a3", ClientDns: []ValData{{Val: "114.114.114.114"}}, RouteInclude: route, DsExcludeDomains: "com.cn,qq.com"}
|
||||
err = SetPolicy(&p3)
|
||||
ast.Nil(err)
|
||||
// 判断 IpMask
|
||||
ast.Equal(p3.RouteInclude[0].IpMask, "192.168.1.1/255.255.255.0")
|
||||
|
||||
route2 := []ValData{{Val: "192.168.2.1/24"}}
|
||||
p4 := Policy{Username: "a4", ClientDns: []ValData{{Val: "114.114.114.114"}}, RouteExclude: route2, DsIncludeDomains: "com.cn,qq.com"}
|
||||
err = SetPolicy(&p4)
|
||||
ast.Nil(err)
|
||||
// 判断 IpMask
|
||||
ast.Equal(p4.RouteExclude[0].IpMask, "192.168.2.1/255.255.255.0")
|
||||
|
||||
// 判断所有数据
|
||||
var userPolicy *Policy
|
||||
pAll := []string{"a1", "a2", "a3", "a4"}
|
||||
for _, v := range pAll {
|
||||
userPolicy = GetPolicy(v)
|
||||
ast.NotEqual(userPolicy.Id, 0, "user policy id is zero")
|
||||
}
|
||||
}
|
@@ -1,13 +1,29 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
const (
|
||||
SettingBucket = "SettingBucket"
|
||||
Installed = "Installed"
|
||||
)
|
||||
type SettingInstall struct {
|
||||
Installed bool `json:"installed"`
|
||||
}
|
||||
|
||||
type SettingSmtp struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
From string `json:"from"`
|
||||
Encryption string `json:"encryption"`
|
||||
}
|
||||
|
||||
type SettingOther struct {
|
||||
LinkAddr string `json:"link_addr"`
|
||||
Banner string `json:"banner"`
|
||||
AccountMail string `json:"account_mail"`
|
||||
}
|
||||
|
||||
func StructName(data interface{}) string {
|
||||
ref := reflect.ValueOf(data)
|
||||
@@ -20,29 +36,30 @@ func StructName(data interface{}) string {
|
||||
return name
|
||||
}
|
||||
|
||||
func SettingSessAdd(sess *xorm.Session, data interface{}) error {
|
||||
name := StructName(data)
|
||||
v, _ := json.Marshal(data)
|
||||
s := &Setting{Name: name, Data: v}
|
||||
_, err := sess.InsertOne(s)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func SettingSet(data interface{}) error {
|
||||
key := StructName(data)
|
||||
err := Set(SettingBucket, key, data)
|
||||
name := StructName(data)
|
||||
v, _ := json.Marshal(data)
|
||||
s := &Setting{Data: v}
|
||||
err := Update("name", name, s)
|
||||
return err
|
||||
}
|
||||
|
||||
func SettingGet(data interface{}) error {
|
||||
key := StructName(data)
|
||||
err := Get(SettingBucket, key, data)
|
||||
name := StructName(data)
|
||||
s := &Setting{Name: name}
|
||||
err := One("name", name, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(s.Data, data)
|
||||
return err
|
||||
}
|
||||
|
||||
type SettingSmtp struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
From string `json:"from"`
|
||||
UseSSl bool `json:"use_ssl"`
|
||||
}
|
||||
|
||||
type SettingOther struct {
|
||||
LinkAddr string `json:"link_addr"`
|
||||
Banner string `json:"banner"`
|
||||
AccountMail string `json:"account_mail"`
|
||||
}
|
||||
|
@@ -6,5 +6,5 @@ func Start() {
|
||||
}
|
||||
|
||||
func Stop() error {
|
||||
return sdb.Close()
|
||||
return xdb.Close()
|
||||
}
|
||||
|
84
server/dbdata/tables.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Group struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
Name string `json:"name" xorm:"varchar(60) not null unique"`
|
||||
Note string `json:"note" xorm:"varchar(255)"`
|
||||
AllowLan bool `json:"allow_lan" xorm:"Bool"`
|
||||
ClientDns []ValData `json:"client_dns" xorm:"Text"`
|
||||
RouteInclude []ValData `json:"route_include" xorm:"Text"`
|
||||
RouteExclude []ValData `json:"route_exclude" xorm:"Text"`
|
||||
DsExcludeDomains string `json:"ds_exclude_domains" xorm:"Text"`
|
||||
DsIncludeDomains string `json:"ds_include_domains" xorm:"Text"`
|
||||
LinkAcl []GroupLinkAcl `json:"link_acl" xorm:"Text"`
|
||||
Bandwidth int `json:"bandwidth" xorm:"Int"` // 带宽限制
|
||||
Auth map[string]interface{} `json:"auth" xorm:"not null default '{}' varchar(255)"` // 认证方式
|
||||
Status int8 `json:"status" xorm:"Int"` // 1正常
|
||||
CreatedAt time.Time `json:"created_at" xorm:"DateTime created"`
|
||||
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
Username string `json:"username" xorm:"varchar(60) not null unique"`
|
||||
Nickname string `json:"nickname" xorm:"varchar(255)"`
|
||||
Email string `json:"email" xorm:"varchar(255)"`
|
||||
// Password string `json:"password"`
|
||||
PinCode string `json:"pin_code" xorm:"varchar(32)"`
|
||||
OtpSecret string `json:"otp_secret" xorm:"varchar(255)"`
|
||||
DisableOtp bool `json:"disable_otp" xorm:"Bool"` // 禁用otp
|
||||
Groups []string `json:"groups" xorm:"Text"`
|
||||
Status int8 `json:"status" xorm:"Int"` // 1正常
|
||||
SendEmail bool `json:"send_email" xorm:"Bool"`
|
||||
CreatedAt time.Time `json:"created_at" xorm:"DateTime created"`
|
||||
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
}
|
||||
|
||||
type IpMap struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
IpAddr string `json:"ip_addr" xorm:"varchar(32) not null unique"`
|
||||
MacAddr string `json:"mac_addr" xorm:"varchar(32) not null unique"`
|
||||
Username string `json:"username" xorm:"varchar(60)"`
|
||||
Keep bool `json:"keep" xorm:"Bool"` // 保留 ip-mac 绑定
|
||||
KeepTime time.Time `json:"keep_time" xorm:"DateTime"`
|
||||
Note string `json:"note" xorm:"varchar(255)"` // 备注
|
||||
LastLogin time.Time `json:"last_login" xorm:"DateTime updated"`
|
||||
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
}
|
||||
|
||||
type Setting struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
Name string `json:"name" xorm:"varchar(60) not null unique"`
|
||||
Data json.RawMessage `json:"data" xorm:"Text"`
|
||||
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
}
|
||||
|
||||
type AccessAudit struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
Username string `json:"username" xorm:"varchar(60) not null"`
|
||||
Protocol uint8 `json:"protocol" xorm:"not null"`
|
||||
Src string `json:"src" xorm:"varchar(60) not null"`
|
||||
SrcPort uint16 `json:"src_port" xorm:"not null"`
|
||||
Dst string `json:"dst" xorm:"varchar(60) not null"`
|
||||
DstPort uint16 `json:"dst_port" xorm:"not null"`
|
||||
CreatedAt time.Time `json:"created_at" xorm:"DateTime"`
|
||||
}
|
||||
|
||||
type Policy struct {
|
||||
Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
Username string `json:"username" xorm:"varchar(60) not null unique"`
|
||||
AllowLan bool `json:"allow_lan" xorm:"Bool"`
|
||||
ClientDns []ValData `json:"client_dns" xorm:"Text"`
|
||||
RouteInclude []ValData `json:"route_include" xorm:"Text"`
|
||||
RouteExclude []ValData `json:"route_exclude" xorm:"Text"`
|
||||
DsExcludeDomains string `json:"ds_exclude_domains" xorm:"Text"`
|
||||
DsIncludeDomains string `json:"ds_include_domains" xorm:"Text"`
|
||||
Status int8 `json:"status" xorm:"Int"` // 1正常 0 禁用
|
||||
CreatedAt time.Time `json:"created_at" xorm:"DateTime created"`
|
||||
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
|
||||
}
|
@@ -10,21 +10,21 @@ import (
|
||||
"github.com/xlzd/gotp"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id int `json:"id" storm:"id,increment"`
|
||||
Username string `json:"username" storm:"unique"`
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
// Password string `json:"password"`
|
||||
PinCode string `json:"pin_code"`
|
||||
OtpSecret string `json:"otp_secret"`
|
||||
DisableOtp bool `json:"disable_otp"` // 禁用otp
|
||||
Groups []string `json:"groups"`
|
||||
Status int8 `json:"status"` // 1正常
|
||||
SendEmail bool `json:"send_email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
// type User struct {
|
||||
// Id int `json:"id" xorm:"pk autoincr not null"`
|
||||
// Username string `json:"username" storm:"not null unique"`
|
||||
// Nickname string `json:"nickname"`
|
||||
// Email string `json:"email"`
|
||||
// // Password string `json:"password"`
|
||||
// PinCode string `json:"pin_code"`
|
||||
// OtpSecret string `json:"otp_secret"`
|
||||
// DisableOtp bool `json:"disable_otp"` // 禁用otp
|
||||
// Groups []string `json:"groups"`
|
||||
// Status int8 `json:"status"` // 1正常
|
||||
// SendEmail bool `json:"send_email"`
|
||||
// CreatedAt time.Time `json:"created_at"`
|
||||
// UpdatedAt time.Time `json:"updated_at"`
|
||||
// }
|
||||
|
||||
func SetUser(v *User) error {
|
||||
var err error
|
||||
@@ -57,14 +57,45 @@ func SetUser(v *User) error {
|
||||
v.Groups = ng
|
||||
|
||||
v.UpdatedAt = time.Now()
|
||||
err = Save(v)
|
||||
if v.Id > 0 {
|
||||
err = Set(v)
|
||||
} else {
|
||||
err = Add(v)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// 验证用户登陆信息
|
||||
// 验证用户登录信息
|
||||
func CheckUser(name, pwd, group string) error {
|
||||
return nil
|
||||
// 获取登入的group数据
|
||||
groupData := &Group{}
|
||||
err := One("Name", group, groupData)
|
||||
if err != nil || groupData.Status != 1 {
|
||||
return fmt.Errorf("%s - %s", name, "用户组错误")
|
||||
}
|
||||
// 初始化Auth
|
||||
if len(groupData.Auth) == 0 {
|
||||
groupData.Auth["type"] = "local"
|
||||
}
|
||||
authType := groupData.Auth["type"].(string)
|
||||
// 本地认证方式
|
||||
if authType == "local" {
|
||||
return checkLocalUser(name, pwd, group)
|
||||
}
|
||||
// 其它认证方式, 支持自定义
|
||||
_, ok := authRegistry[authType]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s %s", "未知的认证方式: ", authType)
|
||||
}
|
||||
auth := makeInstance(authType).(IUserAuth)
|
||||
return auth.checkUser(name, pwd, groupData)
|
||||
}
|
||||
|
||||
// 验证本地用户登录信息
|
||||
func checkLocalUser(name, pwd, group string) error {
|
||||
// TODO 严重问题
|
||||
// return nil
|
||||
|
||||
pl := len(pwd)
|
||||
if name == "" || pl < 6 {
|
||||
@@ -79,12 +110,6 @@ func CheckUser(name, pwd, group string) error {
|
||||
if !utils.InArrStr(v.Groups, group) {
|
||||
return fmt.Errorf("%s %s", name, "用户组错误")
|
||||
}
|
||||
groupData := &Group{}
|
||||
err = One("Name", group, groupData)
|
||||
if err != nil || groupData.Status != 1 {
|
||||
return fmt.Errorf("%s - %s", name, "用户组错误")
|
||||
}
|
||||
|
||||
// 判断otp信息
|
||||
pinCode := pwd
|
||||
if !v.DisableOtp {
|
||||
|
@@ -40,4 +40,30 @@ func TestCheckUser(t *testing.T) {
|
||||
_ = SetUser(&u)
|
||||
err = CheckUser("aaa", u.PinCode, group)
|
||||
ast.Nil(err)
|
||||
|
||||
// 添加一个radius组
|
||||
group2 := "group2"
|
||||
authData := map[string]interface{}{
|
||||
"type": "radius",
|
||||
"radius": map[string]string{
|
||||
"addr": "192.168.1.12:1044",
|
||||
"secret": "43214132",
|
||||
},
|
||||
}
|
||||
g2 := Group{Name: group2, Status: 1, ClientDns: dns, RouteInclude: route, Auth: authData}
|
||||
err = SetGroup(&g2)
|
||||
ast.Nil(err)
|
||||
err = CheckUser("aaa", "bbbbbbb", group2)
|
||||
if ast.NotNil(err) {
|
||||
ast.Equal("aaa Radius服务器连接异常, 请检测服务器和端口", err.Error())
|
||||
|
||||
}
|
||||
// 添加用户策略
|
||||
dns2 := []ValData{{Val: "8.8.8.8"}}
|
||||
route2 := []ValData{{Val: "192.168.2.1/24"}}
|
||||
p1 := Policy{Username: "aaa", Status: 1, ClientDns: dns2, RouteInclude: route2}
|
||||
err = SetPolicy(&p1)
|
||||
ast.Nil(err)
|
||||
err = CheckUser("aaa", u.PinCode, group)
|
||||
ast.Nil(err)
|
||||
}
|
||||
|
23
server/dbdata/userauth.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var authRegistry = make(map[string]reflect.Type)
|
||||
|
||||
type IUserAuth interface {
|
||||
checkData(authData map[string]interface{}) error
|
||||
checkUser(name, pwd string, g *Group) error
|
||||
}
|
||||
|
||||
func makeInstance(name string) interface{} {
|
||||
v := reflect.New(authRegistry[name]).Elem()
|
||||
return v.Interface()
|
||||
}
|
||||
|
||||
func ValidateIpPort(addr string) bool {
|
||||
RegExp := regexp.MustCompile(`^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$$`)
|
||||
return RegExp.MatchString(addr)
|
||||
}
|
72
server/dbdata/userauth_radius.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package dbdata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"layeh.com/radius"
|
||||
"layeh.com/radius/rfc2865"
|
||||
)
|
||||
|
||||
type AuthRadius struct {
|
||||
Addr string `json:"addr"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
authRegistry["radius"] = reflect.TypeOf(AuthRadius{})
|
||||
}
|
||||
|
||||
func (auth AuthRadius) checkData(authData map[string]interface{}) error {
|
||||
authType := authData["type"].(string)
|
||||
bodyBytes, err := json.Marshal(authData[authType])
|
||||
if err != nil {
|
||||
return errors.New("Radius的密钥/服务器地址填写有误")
|
||||
}
|
||||
json.Unmarshal(bodyBytes, &auth)
|
||||
if !ValidateIpPort(auth.Addr) {
|
||||
return errors.New("Radius的服务器地址填写有误")
|
||||
}
|
||||
// freeradius官网最大8000字符, 这里限制200
|
||||
if len(auth.Secret) < 8 || len(auth.Secret) > 200 {
|
||||
return errors.New("Radius的密钥长度需在8~200个字符之间")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (auth AuthRadius) checkUser(name, pwd string, g *Group) error {
|
||||
pl := len(pwd)
|
||||
if name == "" || pl < 1 {
|
||||
return fmt.Errorf("%s %s", name, "密码错误")
|
||||
}
|
||||
authType := g.Auth["type"].(string)
|
||||
if _, ok := g.Auth[authType]; !ok {
|
||||
return fmt.Errorf("%s %s", name, "Radius的radius值不存在")
|
||||
}
|
||||
bodyBytes, err := json.Marshal(g.Auth[authType])
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s", name, "Radius Marshal出现错误")
|
||||
}
|
||||
err = json.Unmarshal(bodyBytes, &auth)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s", name, "Radius Unmarshal出现错误")
|
||||
}
|
||||
// radius认证时,设置超时3秒
|
||||
packet := radius.New(radius.CodeAccessRequest, []byte(auth.Secret))
|
||||
rfc2865.UserName_SetString(packet, name)
|
||||
rfc2865.UserPassword_SetString(packet, pwd)
|
||||
ctx, done := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer done()
|
||||
response, err := radius.Exchange(ctx, packet, auth.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s", name, "Radius服务器连接异常, 请检测服务器和端口")
|
||||
}
|
||||
if response.Code != radius.CodeAccessAccept {
|
||||
return fmt.Errorf("%s %s", name, "Radius:用户名或密码错误")
|
||||
}
|
||||
return nil
|
||||
}
|
@@ -3,28 +3,30 @@ module github.com/bjdgyc/anylink
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
|
||||
github.com/asdine/storm/v3 v3.2.1
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/go-ole/go-ole v1.2.5 // indirect
|
||||
github.com/StackExchange/wmi v1.2.1 // indirect
|
||||
github.com/go-sql-driver/mysql v1.6.0
|
||||
github.com/golang-jwt/jwt/v4 v4.0.0
|
||||
github.com/google/gopacket v1.1.19
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/pion/dtls/v2 v2.0.0-00010101000000-000000000000
|
||||
github.com/lib/pq v1.10.2
|
||||
github.com/mattn/go-sqlite3 v1.14.8
|
||||
github.com/pion/dtls/v2 v2.0.9
|
||||
github.com/pion/logging v0.2.2
|
||||
github.com/shirou/gopsutil v3.21.4+incompatible
|
||||
github.com/shirou/gopsutil v3.21.7+incompatible
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/songgao/packets v0.0.0-20160404182456-549a10cd4091
|
||||
github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8
|
||||
github.com/spf13/cobra v1.1.3
|
||||
github.com/spf13/viper v1.7.1
|
||||
github.com/spf13/cobra v1.2.1
|
||||
github.com/spf13/viper v1.8.1
|
||||
github.com/stretchr/testify v1.7.0
|
||||
github.com/tklauser/go-sysconf v0.3.6 // indirect
|
||||
github.com/xhit/go-simple-mail/v2 v2.9.0
|
||||
github.com/tklauser/go-sysconf v0.3.7 // indirect
|
||||
github.com/xhit/go-simple-mail/v2 v2.10.0
|
||||
github.com/xlzd/gotp v0.0.0-20181030022105-c8557ba2c119
|
||||
go.etcd.io/bbolt v1.3.5
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a
|
||||
golang.org/x/net v0.0.0-20210520170846-37e1c6afe023
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97
|
||||
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d
|
||||
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
|
||||
layeh.com/radius v0.0.0-20210819152912-ad72663a72ab
|
||||
xorm.io/xorm v1.2.2
|
||||
)
|
||||
|
||||
replace github.com/pion/dtls/v2 => ../dtls-2.0.9
|
||||
|
772
server/go.sum
@@ -14,12 +14,14 @@ import (
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
var profileHash = ""
|
||||
|
||||
func LinkAuth(w http.ResponseWriter, r *http.Request) {
|
||||
// 判断anyconnect客户端
|
||||
userAgent := strings.ToLower(r.UserAgent())
|
||||
xAggregateAuth := r.Header.Get("X-Aggregate-Auth")
|
||||
xTranscendVersion := r.Header.Get("X-Transcend-Version")
|
||||
if !(strings.Contains(userAgent, "anyconnect") &&
|
||||
if !((strings.Contains(userAgent, "anyconnect") || strings.Contains(userAgent, "openconnect")) &&
|
||||
xAggregateAuth == "1" && xTranscendVersion == "1") {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprintf(w, "error request")
|
||||
@@ -89,7 +91,7 @@ func LinkAuth(w http.ResponseWriter, r *http.Request) {
|
||||
other := &dbdata.SettingOther{}
|
||||
_ = dbdata.SettingGet(other)
|
||||
rd := RequestData{SessionId: sess.Sid, SessionToken: sess.Sid + "@" + sess.Token,
|
||||
Banner: other.Banner}
|
||||
Banner: other.Banner, ProfileHash: profileHash}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
tplRequest(tpl_complete, w, rd)
|
||||
base.Debug("login", cr.Auth.Username)
|
||||
@@ -125,6 +127,7 @@ type RequestData struct {
|
||||
SessionId string
|
||||
SessionToken string
|
||||
Banner string
|
||||
ProfileHash string
|
||||
}
|
||||
|
||||
var auth_request = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -173,6 +176,64 @@ var auth_complete = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<server-cert-hash>240B97A685B2BFA66AD699B90AAC49EA66495D69</server-cert-hash>
|
||||
</vpn-base-config>
|
||||
<opaque is-for="vpn-client"></opaque>
|
||||
<vpn-profile-manifest>
|
||||
<vpn rev="1.0">
|
||||
<file type="profile" service-type="user">
|
||||
<uri>/profile.xml</uri>
|
||||
<hash type="sha1">{{.ProfileHash}}</hash>
|
||||
</file>
|
||||
</vpn>
|
||||
</vpn-profile-manifest>
|
||||
</config>
|
||||
</config-auth>
|
||||
`
|
||||
|
||||
var auth_profile = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<AnyConnectProfile xmlns="http://schemas.xmlsoap.org/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.xmlsoap.org/encoding/ AnyConnectProfile.xsd">
|
||||
|
||||
<ClientInitialization>
|
||||
<UseStartBeforeLogon UserControllable="false">false</UseStartBeforeLogon>
|
||||
<StrictCertificateTrust>false</StrictCertificateTrust>
|
||||
<RestrictPreferenceCaching>false</RestrictPreferenceCaching>
|
||||
<RestrictTunnelProtocols>IPSec</RestrictTunnelProtocols>
|
||||
<BypassDownloader>true</BypassDownloader>
|
||||
<WindowsVPNEstablishment>AllowRemoteUsers</WindowsVPNEstablishment>
|
||||
<CertEnrollmentPin>pinAllowed</CertEnrollmentPin>
|
||||
<CertificateMatch>
|
||||
<KeyUsage>
|
||||
<MatchKey>Digital_Signature</MatchKey>
|
||||
</KeyUsage>
|
||||
<ExtendedKeyUsage>
|
||||
<ExtendedMatchKey>ClientAuth</ExtendedMatchKey>
|
||||
</ExtendedKeyUsage>
|
||||
</CertificateMatch>
|
||||
|
||||
<BackupServerList>
|
||||
<HostAddress>localhost</HostAddress>
|
||||
</BackupServerList>
|
||||
</ClientInitialization>
|
||||
|
||||
<ServerList>
|
||||
<HostEntry>
|
||||
<HostName>VPN Server</HostName>
|
||||
<HostAddress>localhost</HostAddress>
|
||||
</HostEntry>
|
||||
</ServerList>
|
||||
</AnyConnectProfile>
|
||||
`
|
||||
var ds_domains_xml = `
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<config-auth client="vpn" type="complete" aggregate-auth-version="2">
|
||||
<config client="vpn" type="private">
|
||||
<opaque is-for="vpn-client">
|
||||
<custom-attr>
|
||||
{{if .DsExcludeDomains}}
|
||||
<dynamic-split-exclude-domains><![CDATA[{{.DsExcludeDomains}},]]></dynamic-split-exclude-domains>
|
||||
{{else if .DsIncludeDomains}}
|
||||
<dynamic-split-include-domains><![CDATA[{{.DsIncludeDomains}}]]></dynamic-split-include-domains>
|
||||
{{end}}
|
||||
</custom-attr>
|
||||
</opaque>
|
||||
</config>
|
||||
</config-auth>
|
||||
`
|
||||
|
@@ -58,7 +58,7 @@ func execCmd(cmdStrs []string) error {
|
||||
cmd := exec.Command("sh", "-c", cmdStr)
|
||||
b, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
log.Println(string(b), err)
|
||||
log.Println(string(b))
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
@@ -1,15 +1,17 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
func LinkCstp(conn net.Conn, bufRW *bufio.ReadWriter, cSess *sessdata.ConnSession) {
|
||||
defer func() {
|
||||
base.Debug("LinkCstp return", cSess.IpAddr)
|
||||
_ = conn.Close()
|
||||
@@ -23,19 +25,19 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
dead = time.Duration(cSess.CstpDpd+5) * time.Second
|
||||
)
|
||||
|
||||
go cstpWrite(conn, cSess)
|
||||
go cstpWrite(conn, bufRW, cSess)
|
||||
|
||||
for {
|
||||
|
||||
// 设置超时限制
|
||||
err = conn.SetReadDeadline(time.Now().Add(dead))
|
||||
err = conn.SetReadDeadline(utils.NowSec().Add(dead))
|
||||
if err != nil {
|
||||
base.Error("SetDeadline: ", err)
|
||||
return
|
||||
}
|
||||
// hdata := make([]byte, BufferSize)
|
||||
hdata := getByteFull()
|
||||
n, err = conn.Read(hdata)
|
||||
pl := getPayload()
|
||||
n, err = bufRW.Read(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("read hdata: ", err)
|
||||
return
|
||||
@@ -47,7 +49,7 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
base.Error(err)
|
||||
}
|
||||
|
||||
switch hdata[6] {
|
||||
switch pl.Data[6] {
|
||||
case 0x07: // KEEPALIVE
|
||||
// do nothing
|
||||
// base.Debug("recv keepalive", cSess.IpAddr)
|
||||
@@ -56,23 +58,28 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
return
|
||||
case 0x03: // DPD-REQ
|
||||
// base.Debug("recv DPD-REQ", cSess.IpAddr)
|
||||
if payloadOutCstp(cSess, sessdata.LTypeIPData, 0x04, nil) {
|
||||
pl.PType = 0x04
|
||||
if payloadOutCstp(cSess, pl) {
|
||||
return
|
||||
}
|
||||
case 0x04:
|
||||
// log.Println("recv DPD-RESP")
|
||||
case 0x00: // DATA
|
||||
dataLen = binary.BigEndian.Uint16(hdata[4:6]) // 4,5
|
||||
if payloadIn(cSess, sessdata.LTypeIPData, 0x00, hdata[8:8+dataLen]) {
|
||||
// 获取数据长度
|
||||
dataLen = binary.BigEndian.Uint16(pl.Data[4:6]) // 4,5
|
||||
// 去除数据头
|
||||
copy(pl.Data, pl.Data[8:8+dataLen])
|
||||
// 更新切片长度
|
||||
pl.Data = pl.Data[:dataLen]
|
||||
// pl.Data = append(pl.Data[:0], pl.Data[8:8+dataLen]...)
|
||||
if payloadIn(cSess, pl) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
putByte(hdata)
|
||||
}
|
||||
}
|
||||
|
||||
func cstpWrite(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
func cstpWrite(conn net.Conn, bufRW *bufio.ReadWriter, cSess *sessdata.ConnSession) {
|
||||
defer func() {
|
||||
base.Debug("cstpWrite return", cSess.IpAddr)
|
||||
_ = conn.Close()
|
||||
@@ -82,36 +89,44 @@ func cstpWrite(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
var (
|
||||
err error
|
||||
n int
|
||||
// header []byte
|
||||
payload *sessdata.Payload
|
||||
pl *sessdata.Payload
|
||||
)
|
||||
|
||||
for {
|
||||
select {
|
||||
case payload = <-cSess.PayloadOutCstp:
|
||||
case pl = <-cSess.PayloadOutCstp:
|
||||
case <-cSess.CloseChan:
|
||||
return
|
||||
}
|
||||
|
||||
if payload.LType != sessdata.LTypeIPData {
|
||||
if pl.LType != sessdata.LTypeIPData {
|
||||
continue
|
||||
}
|
||||
|
||||
h := []byte{'S', 'T', 'F', 0x01, 0x00, 0x00, payload.PType, 0x00}
|
||||
header := getByteZero()
|
||||
header = append(header, h...)
|
||||
if payload.PType == 0x00 { // data
|
||||
binary.BigEndian.PutUint16(header[4:6], uint16(len(payload.Data)))
|
||||
header = append(header, payload.Data...)
|
||||
if pl.PType == 0x00 {
|
||||
// 获取数据长度
|
||||
l := len(pl.Data)
|
||||
// 先扩容 +8
|
||||
pl.Data = pl.Data[:l+8]
|
||||
// 数据后移
|
||||
copy(pl.Data[8:], pl.Data)
|
||||
// 添加头信息
|
||||
copy(pl.Data[:8], plHeader)
|
||||
// 更新头长度
|
||||
binary.BigEndian.PutUint16(pl.Data[4:6], uint16(l))
|
||||
} else {
|
||||
pl.Data = append(pl.Data[:0], plHeader...)
|
||||
// 设置头类型
|
||||
pl.Data[6] = pl.PType
|
||||
}
|
||||
n, err = conn.Write(header)
|
||||
|
||||
n, err = conn.Write(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("write err", err)
|
||||
return
|
||||
}
|
||||
|
||||
putByte(header)
|
||||
putPayload(payload)
|
||||
putPayload(pl)
|
||||
|
||||
// 限流设置
|
||||
err = cSess.RateLimit(n, false)
|
||||
|
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
@@ -24,21 +25,22 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
}()
|
||||
|
||||
var (
|
||||
err error
|
||||
n int
|
||||
dead = time.Duration(cSess.CstpDpd+5) * time.Second
|
||||
)
|
||||
|
||||
go dtlsWrite(conn, dSess, cSess)
|
||||
|
||||
for {
|
||||
err := conn.SetReadDeadline(time.Now().Add(dead))
|
||||
err = conn.SetReadDeadline(utils.NowSec().Add(dead))
|
||||
if err != nil {
|
||||
base.Error("SetDeadline: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
// hdata := make([]byte, BufferSize)
|
||||
hdata := getByteFull()
|
||||
n, err := conn.Read(hdata)
|
||||
pl := getPayload()
|
||||
n, err = conn.Read(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("read hdata: ", err)
|
||||
return
|
||||
@@ -50,7 +52,7 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
base.Error(err)
|
||||
}
|
||||
|
||||
switch hdata[0] {
|
||||
switch pl.Data[0] {
|
||||
case 0x07: // KEEPALIVE
|
||||
// do nothing
|
||||
// base.Debug("recv keepalive", cSess.IpAddr)
|
||||
@@ -59,18 +61,23 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
|
||||
return
|
||||
case 0x03: // DPD-REQ
|
||||
// base.Debug("recv DPD-REQ", cSess.IpAddr)
|
||||
if payloadOutDtls(cSess, dSess, sessdata.LTypeIPData, 0x04, nil) {
|
||||
pl.PType = 0x04
|
||||
if payloadOutDtls(cSess, dSess, pl) {
|
||||
return
|
||||
}
|
||||
case 0x04:
|
||||
// base.Debug("recv DPD-RESP", cSess.IpAddr)
|
||||
case 0x00: // DATA
|
||||
if payloadIn(cSess, sessdata.LTypeIPData, 0x00, hdata[1:n]) {
|
||||
// 去除数据头
|
||||
// copy(pl.Data, pl.Data[1:n])
|
||||
// 更新切片长度
|
||||
// pl.Data = pl.Data[:n-1]
|
||||
pl.Data = append(pl.Data[:0], pl.Data[1:n]...)
|
||||
if payloadIn(cSess, pl) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
putByte(hdata)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,36 +89,42 @@ func dtlsWrite(conn net.Conn, dSess *sessdata.DtlsSession, cSess *sessdata.ConnS
|
||||
}()
|
||||
|
||||
var (
|
||||
// header []byte
|
||||
payload *sessdata.Payload
|
||||
pl *sessdata.Payload
|
||||
)
|
||||
|
||||
for {
|
||||
// dtls优先推送数据
|
||||
select {
|
||||
case payload = <-cSess.PayloadOutDtls:
|
||||
case pl = <-cSess.PayloadOutDtls:
|
||||
case <-dSess.CloseChan:
|
||||
return
|
||||
}
|
||||
|
||||
if payload.LType != sessdata.LTypeIPData {
|
||||
if pl.LType != sessdata.LTypeIPData {
|
||||
continue
|
||||
}
|
||||
|
||||
// header = []byte{payload.PType}
|
||||
header := getByteZero()
|
||||
header = append(header, payload.PType)
|
||||
if payload.PType == 0x00 { // data
|
||||
header = append(header, payload.Data...)
|
||||
if pl.PType == 0x00 { // data
|
||||
// 获取数据长度
|
||||
l := len(pl.Data)
|
||||
// 先扩容 +1
|
||||
pl.Data = pl.Data[:l+1]
|
||||
// 数据后移
|
||||
copy(pl.Data[1:], pl.Data)
|
||||
// 添加头信息
|
||||
pl.Data[0] = pl.PType
|
||||
} else {
|
||||
// 设置头类型
|
||||
pl.Data = append(pl.Data[:0], pl.PType)
|
||||
}
|
||||
n, err := conn.Write(header)
|
||||
n, err := conn.Write(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("write err", err)
|
||||
return
|
||||
}
|
||||
|
||||
putByte(header)
|
||||
putPayload(payload)
|
||||
putPayload(pl)
|
||||
|
||||
// 限流设置
|
||||
err = cSess.RateLimit(n, false)
|
||||
|
@@ -15,7 +15,7 @@ func LinkHome(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
connection := strings.ToLower(r.Header.Get("Connection"))
|
||||
userAgent := strings.ToLower(r.UserAgent())
|
||||
if connection == "close" && strings.Contains(userAgent, "anyconnect") {
|
||||
if connection == "close" && (strings.Contains(userAgent, "anyconnect") || strings.Contains(userAgent, "openconnect")) {
|
||||
w.Header().Set("Connection", "close")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
|
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
@@ -17,18 +18,32 @@ import (
|
||||
const bridgeName = "anylink0"
|
||||
|
||||
var (
|
||||
bridgeIp net.IP
|
||||
bridgeHw net.HardwareAddr
|
||||
// 网关mac地址
|
||||
gatewayHw net.HardwareAddr
|
||||
)
|
||||
|
||||
func checkTap() {
|
||||
brFace, err := net.InterfaceByName(bridgeName)
|
||||
type LinkDriver interface {
|
||||
io.ReadWriteCloser
|
||||
Name() string
|
||||
}
|
||||
|
||||
func _setGateway() {
|
||||
dstAddr := arpdis.Lookup(sessdata.IpPool.Ipv4Gateway, false)
|
||||
gatewayHw = dstAddr.HardwareAddr
|
||||
// 设置为静态地址映射
|
||||
dstAddr.Type = arpdis.TypeStatic
|
||||
arpdis.Add(dstAddr)
|
||||
}
|
||||
|
||||
func _checkTapIp(ifName string) {
|
||||
iFace, err := net.InterfaceByName(ifName)
|
||||
if err != nil {
|
||||
base.Fatal("testTap err: ", err)
|
||||
}
|
||||
bridgeHw = brFace.HardwareAddr
|
||||
|
||||
addrs, err := brFace.Addrs()
|
||||
var ifIp net.IP
|
||||
|
||||
addrs, err := iFace.Addrs()
|
||||
if err != nil {
|
||||
base.Fatal("testTap err: ", err)
|
||||
}
|
||||
@@ -37,17 +52,19 @@ func checkTap() {
|
||||
if err != nil || ip.To4() == nil {
|
||||
continue
|
||||
}
|
||||
bridgeIp = ip
|
||||
}
|
||||
if bridgeIp == nil && bridgeHw == nil {
|
||||
base.Fatal("bridgeIp is err")
|
||||
ifIp = ip
|
||||
}
|
||||
|
||||
if !sessdata.IpPool.Ipv4IPNet.Contains(bridgeIp) {
|
||||
base.Fatal("bridgeIp or Ip network err")
|
||||
if !sessdata.IpPool.Ipv4IPNet.Contains(ifIp) {
|
||||
base.Fatal("tapIp or Ip network err")
|
||||
}
|
||||
}
|
||||
|
||||
func checkTap() {
|
||||
_setGateway()
|
||||
_checkTapIp(bridgeName)
|
||||
}
|
||||
|
||||
// 创建tap网卡
|
||||
func LinkTap(cSess *sessdata.ConnSession) error {
|
||||
cfg := water.Config{
|
||||
@@ -60,88 +77,94 @@ func LinkTap(cSess *sessdata.ConnSession) error {
|
||||
return err
|
||||
}
|
||||
|
||||
cSess.TunName = ifce.Name()
|
||||
cSess.SetIfName(ifce.Name())
|
||||
|
||||
// arp on
|
||||
cmdstr1 := fmt.Sprintf("ip link set dev %s up mtu %d multicast on", ifce.Name(), cSess.Mtu)
|
||||
cmdstr2 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifce.Name())
|
||||
cmdstr3 := fmt.Sprintf("ip link set dev %s master %s", ifce.Name(), bridgeName)
|
||||
cmdStrs := []string{cmdstr1, cmdstr2, cmdstr3}
|
||||
err = execCmd(cmdStrs)
|
||||
cmdstr2 := fmt.Sprintf("ip link set dev %s master %s", ifce.Name(), bridgeName)
|
||||
err = execCmd([]string{cmdstr1, cmdstr2})
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
_ = ifce.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
go tapRead(ifce, cSess)
|
||||
go tapWrite(ifce, cSess)
|
||||
cmdstr3 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifce.Name())
|
||||
execCmd([]string{cmdstr3})
|
||||
|
||||
go allTapRead(ifce, cSess)
|
||||
go allTapWrite(ifce, cSess)
|
||||
return nil
|
||||
}
|
||||
|
||||
func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
// ========================通用代码===========================
|
||||
|
||||
func allTapWrite(ifce LinkDriver, cSess *sessdata.ConnSession) {
|
||||
defer func() {
|
||||
base.Debug("LinkTap return", cSess.IpAddr)
|
||||
cSess.Close()
|
||||
_ = ifce.Close()
|
||||
ifce.Close()
|
||||
}()
|
||||
|
||||
var (
|
||||
err error
|
||||
payload *sessdata.Payload
|
||||
frame ethernet.Frame
|
||||
err error
|
||||
dstHw net.HardwareAddr
|
||||
pl *sessdata.Payload
|
||||
frame = make(ethernet.Frame, BufferSize)
|
||||
ipDst = net.IPv4(1, 2, 3, 4)
|
||||
)
|
||||
|
||||
for {
|
||||
frame.Resize(BufferSize)
|
||||
|
||||
select {
|
||||
case payload = <-cSess.PayloadIn:
|
||||
case pl = <-cSess.PayloadIn:
|
||||
case <-cSess.CloseChan:
|
||||
return
|
||||
}
|
||||
|
||||
// var frame ethernet.Frame
|
||||
frame = getByteFull()
|
||||
switch payload.LType {
|
||||
switch pl.LType {
|
||||
default:
|
||||
// log.Println(payload)
|
||||
case sessdata.LTypeEthernet:
|
||||
copy(frame, payload.Data)
|
||||
frame = frame[:len(payload.Data)]
|
||||
case sessdata.LTypeIPData: // 需要转换成 Ethernet 数据
|
||||
data := payload.Data
|
||||
copy(frame, pl.Data)
|
||||
frame = frame[:len(pl.Data)]
|
||||
|
||||
ip_src := waterutil.IPv4Source(data)
|
||||
if waterutil.IsIPv6(data) || !ip_src.Equal(cSess.IpAddr) {
|
||||
// 过滤掉IPv6的数据
|
||||
// packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
|
||||
// fmt.Println("wirteArp:", packet)
|
||||
case sessdata.LTypeIPData: // 需要转换成 Ethernet 数据
|
||||
ipSrc := waterutil.IPv4Source(pl.Data)
|
||||
if !ipSrc.Equal(cSess.IpAddr) {
|
||||
// 非分配给客户端ip,直接丢弃
|
||||
continue
|
||||
}
|
||||
|
||||
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
|
||||
if waterutil.IsIPv6(pl.Data) {
|
||||
// 过滤掉IPv6的数据
|
||||
continue
|
||||
}
|
||||
|
||||
// packet := gopacket.NewPacket(pl.Data, layers.LayerTypeIPv4, gopacket.Default)
|
||||
// fmt.Println("get:", packet)
|
||||
|
||||
ip_dst := waterutil.IPv4Destination(data)
|
||||
// fmt.Println("get:", ip_src, ip_dst)
|
||||
// 手动设置ipv4地址
|
||||
ipDst[12] = pl.Data[16]
|
||||
ipDst[13] = pl.Data[17]
|
||||
ipDst[14] = pl.Data[18]
|
||||
ipDst[15] = pl.Data[19]
|
||||
|
||||
var dstHw net.HardwareAddr
|
||||
if !sessdata.IpPool.Ipv4IPNet.Contains(ip_dst) || ip_dst.Equal(sessdata.IpPool.Ipv4Gateway) {
|
||||
// 不是同一网段,使用网关mac地址
|
||||
dstAddr := arpdis.Lookup(sessdata.IpPool.Ipv4Gateway, false)
|
||||
dstHw = dstAddr.HardwareAddr
|
||||
} else {
|
||||
dstAddr := arpdis.Lookup(ip_dst, true)
|
||||
dstHw = gatewayHw
|
||||
if sessdata.IpPool.Ipv4IPNet.Contains(ipDst) {
|
||||
dstAddr := arpdis.Lookup(ipDst, true)
|
||||
// fmt.Println("dstAddr", dstAddr)
|
||||
if dstAddr != nil {
|
||||
dstHw = dstAddr.HardwareAddr
|
||||
} else {
|
||||
dstHw = bridgeHw
|
||||
}
|
||||
|
||||
}
|
||||
// fmt.Println("Gateway", ip_dst, dstAddr.HardwareAddr)
|
||||
|
||||
frame.Prepare(dstHw, cSess.MacHw, ethernet.NotTagged, ethernet.IPv4, len(data))
|
||||
copy(frame[12+2:], data)
|
||||
// fmt.Println("Gateway", ipSrc, ipDst, dstHw)
|
||||
frame.Prepare(dstHw, cSess.MacHw, ethernet.NotTagged, ethernet.IPv4, len(pl.Data))
|
||||
copy(frame[12+2:], pl.Data)
|
||||
}
|
||||
|
||||
// packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
|
||||
@@ -152,28 +175,26 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
return
|
||||
}
|
||||
|
||||
putByte(frame)
|
||||
putPayload(payload)
|
||||
putPayload(pl)
|
||||
}
|
||||
}
|
||||
|
||||
func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
func allTapRead(ifce LinkDriver, cSess *sessdata.ConnSession) {
|
||||
defer func() {
|
||||
base.Debug("tapRead return", cSess.IpAddr)
|
||||
_ = ifce.Close()
|
||||
ifce.Close()
|
||||
}()
|
||||
|
||||
var (
|
||||
err error
|
||||
n int
|
||||
buf []byte
|
||||
frame ethernet.Frame
|
||||
data []byte
|
||||
frame = make(ethernet.Frame, BufferSize)
|
||||
)
|
||||
|
||||
for {
|
||||
// var frame ethernet.Frame
|
||||
// frame.Resize(BufferSize)
|
||||
frame = getByteFull()
|
||||
frame.Resize(BufferSize)
|
||||
|
||||
n, err = ifce.Read(frame)
|
||||
if err != nil {
|
||||
base.Error("tap Read err", n, err)
|
||||
@@ -183,14 +204,12 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
|
||||
switch frame.Ethertype() {
|
||||
default:
|
||||
// packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
|
||||
// fmt.Println(packet)
|
||||
continue
|
||||
case ethernet.IPv6:
|
||||
continue
|
||||
case ethernet.IPv4:
|
||||
// 发送IP数据
|
||||
data := frame.Payload()
|
||||
data = frame.Payload()
|
||||
|
||||
ip_dst := waterutil.IPv4Destination(data)
|
||||
if !ip_dst.Equal(cSess.IpAddr) {
|
||||
@@ -202,13 +221,18 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
|
||||
// fmt.Println("put:", packet)
|
||||
|
||||
if payloadOut(cSess, sessdata.LTypeIPData, 0x00, data) {
|
||||
pl := getPayload()
|
||||
// 拷贝数据到pl
|
||||
copy(pl.Data, data)
|
||||
// 更新切片长度
|
||||
pl.Data = pl.Data[:len(data)]
|
||||
if payloadOut(cSess, pl) {
|
||||
return
|
||||
}
|
||||
|
||||
case ethernet.ARP:
|
||||
// 暂时仅实现了ARP协议
|
||||
packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
|
||||
packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.NoCopy)
|
||||
layer := packet.Layer(layers.LayerTypeARP)
|
||||
arpReq := layer.(*layers.ARP)
|
||||
|
||||
@@ -217,13 +241,13 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
continue
|
||||
}
|
||||
|
||||
// fmt.Println("arp", net.IP(arpReq.SourceProtAddress), sess.Ip)
|
||||
// fmt.Println("arp", time.Now(), net.IP(arpReq.SourceProtAddress), cSess.IpAddr)
|
||||
// fmt.Println(packet)
|
||||
|
||||
// 返回ARP数据
|
||||
src := &arpdis.Addr{IP: cSess.IpAddr, HardwareAddr: cSess.MacHw}
|
||||
dst := &arpdis.Addr{IP: arpReq.SourceProtAddress, HardwareAddr: frame.Source()}
|
||||
buf, err = arpdis.NewARPReply(src, dst)
|
||||
dst := &arpdis.Addr{IP: arpReq.SourceProtAddress, HardwareAddr: arpReq.SourceHwAddress}
|
||||
data, err = arpdis.NewARPReply(src, dst)
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
return
|
||||
@@ -231,21 +255,23 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
|
||||
// 从接受的arp信息添加arp地址
|
||||
addr := &arpdis.Addr{
|
||||
IP: make([]byte, len(arpReq.SourceProtAddress)),
|
||||
HardwareAddr: make([]byte, len(frame.Source())),
|
||||
IP: append([]byte{}, dst.IP...),
|
||||
HardwareAddr: append([]byte{}, dst.HardwareAddr...),
|
||||
}
|
||||
// addr.IP = arpReq.SourceProtAddress
|
||||
// addr.HardwareAddr = frame.Source()
|
||||
copy(addr.IP, arpReq.SourceProtAddress)
|
||||
copy(addr.HardwareAddr, frame.Source())
|
||||
arpdis.Add(addr)
|
||||
|
||||
if payloadIn(cSess, sessdata.LTypeEthernet, 0x00, buf) {
|
||||
pl := getPayload()
|
||||
// 设置为二层数据类型
|
||||
pl.LType = sessdata.LTypeEthernet
|
||||
// 拷贝数据到pl
|
||||
copy(pl.Data, data)
|
||||
// 更新切片长度
|
||||
pl.Data = pl.Data[:len(data)]
|
||||
|
||||
if payloadIn(cSess, pl) {
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
putByte(frame)
|
||||
}
|
||||
}
|
||||
|
@@ -40,21 +40,21 @@ func LinkTun(cSess *sessdata.ConnSession) error {
|
||||
return err
|
||||
}
|
||||
// log.Printf("Interface Name: %s\n", ifce.Name())
|
||||
cSess.SetTunName(ifce.Name())
|
||||
// cSess.TunName = ifce.Name()
|
||||
cSess.SetIfName(ifce.Name())
|
||||
|
||||
cmdstr1 := fmt.Sprintf("ip link set dev %s up mtu %d multicast off", ifce.Name(), cSess.Mtu)
|
||||
cmdstr2 := fmt.Sprintf("ip addr add dev %s local %s peer %s/32",
|
||||
ifce.Name(), base.Cfg.Ipv4Gateway, cSess.IpAddr)
|
||||
cmdstr3 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifce.Name())
|
||||
cmdStrs := []string{cmdstr1, cmdstr2, cmdstr3}
|
||||
err = execCmd(cmdStrs)
|
||||
err = execCmd([]string{cmdstr1, cmdstr2})
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
_ = ifce.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
cmdstr3 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifce.Name())
|
||||
execCmd([]string{cmdstr3})
|
||||
|
||||
go tunRead(ifce, cSess)
|
||||
go tunWrite(ifce, cSess)
|
||||
return nil
|
||||
@@ -68,24 +68,24 @@ func tunWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
}()
|
||||
|
||||
var (
|
||||
err error
|
||||
payload *sessdata.Payload
|
||||
err error
|
||||
pl *sessdata.Payload
|
||||
)
|
||||
|
||||
for {
|
||||
select {
|
||||
case payload = <-cSess.PayloadIn:
|
||||
case pl = <-cSess.PayloadIn:
|
||||
case <-cSess.CloseChan:
|
||||
return
|
||||
}
|
||||
|
||||
_, err = ifce.Write(payload.Data)
|
||||
_, err = ifce.Write(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("tun Write err", err)
|
||||
return
|
||||
}
|
||||
|
||||
putPayload(payload)
|
||||
putPayload(pl)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,13 +101,16 @@ func tunRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
|
||||
for {
|
||||
// data := make([]byte, BufferSize)
|
||||
data := getByteFull()
|
||||
n, err = ifce.Read(data)
|
||||
pl := getPayload()
|
||||
n, err = ifce.Read(pl.Data)
|
||||
if err != nil {
|
||||
base.Error("tun Read err", n, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 更新数据长度
|
||||
pl.Data = (pl.Data)[:n]
|
||||
|
||||
// data = data[:n]
|
||||
// ip_src := waterutil.IPv4Source(data)
|
||||
// ip_dst := waterutil.IPv4Destination(data)
|
||||
@@ -116,10 +119,8 @@ func tunRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
|
||||
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
|
||||
// fmt.Println("read:", packet)
|
||||
|
||||
if payloadOut(cSess, sessdata.LTypeIPData, 0x00, data[:n]) {
|
||||
if payloadOut(cSess, pl) {
|
||||
return
|
||||
}
|
||||
|
||||
putByte(data)
|
||||
}
|
||||
}
|
||||
|
@@ -8,8 +8,10 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
@@ -22,6 +24,14 @@ func init() {
|
||||
hn, _ = os.Hostname()
|
||||
}
|
||||
|
||||
func HttpSetHeader(w http.ResponseWriter, key string, value string) {
|
||||
w.Header()[key] = []string{value}
|
||||
}
|
||||
|
||||
func HttpAddHeader(w http.ResponseWriter, key string, value string) {
|
||||
w.Header()[key] = append(w.Header()[key], value)
|
||||
}
|
||||
|
||||
func LinkTunnel(w http.ResponseWriter, r *http.Request) {
|
||||
// TODO 调试信息输出
|
||||
// hd, _ := httputil.DumpRequest(r, true)
|
||||
@@ -51,6 +61,7 @@ func LinkTunnel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 客户端信息
|
||||
cstpMtu := r.Header.Get("X-CSTP-MTU")
|
||||
cstpBaseMtu := r.Header.Get("X-CSTP-Base-MTU")
|
||||
masterSecret := r.Header.Get("X-DTLS-Master-Secret")
|
||||
localIp := r.Header.Get("X-Cstp-Local-Address-Ip4")
|
||||
mobile := r.Header.Get("X-Cstp-License")
|
||||
@@ -79,65 +90,77 @@ func LinkTunnel(w http.ResponseWriter, r *http.Request) {
|
||||
base.Debug(cSess.IpAddr, cSess.MacHw, sess.Username, mobile)
|
||||
|
||||
// 返回客户端数据
|
||||
w.Header().Set("Server", fmt.Sprintf("%s %s", base.APP_NAME, base.APP_VER))
|
||||
w.Header().Set("X-CSTP-Version", "1")
|
||||
w.Header().Set("X-CSTP-Protocol", "Copyright (c) 2004 Cisco Systems, Inc.")
|
||||
w.Header().Set("X-CSTP-Address", cSess.IpAddr.String()) // 分配的ip地址
|
||||
w.Header().Set("X-CSTP-Netmask", sessdata.IpPool.Ipv4Mask.String()) // 子网掩码
|
||||
w.Header().Set("X-CSTP-Hostname", hn) // 机器名称
|
||||
HttpSetHeader(w, "Server", fmt.Sprintf("%s %s", base.APP_NAME, base.APP_VER))
|
||||
HttpSetHeader(w, "X-CSTP-Version", "1")
|
||||
HttpSetHeader(w, "X-CSTP-Server-Name", fmt.Sprintf("%s %s", base.APP_NAME, base.APP_VER))
|
||||
HttpSetHeader(w, "X-CSTP-Protocol", "Copyright (c) 2004 Cisco Systems, Inc.")
|
||||
HttpSetHeader(w, "X-CSTP-Address", cSess.IpAddr.String()) // 分配的ip地址
|
||||
HttpSetHeader(w, "X-CSTP-Netmask", sessdata.IpPool.Ipv4Mask.String()) // 子网掩码
|
||||
HttpSetHeader(w, "X-CSTP-Hostname", hn) // 机器名称
|
||||
//HttpSetHeader(w, "X-CSTP-Default-Domain", cSess.LocalIp)
|
||||
HttpSetHeader(w, "X-CSTP-Base-MTU", cstpBaseMtu)
|
||||
|
||||
// 设置用户策略
|
||||
SetUserPolicy(sess.Username, cSess.Group)
|
||||
|
||||
// 允许本地LAN访问vpn网络,必须放在路由的第一个
|
||||
if cSess.Group.AllowLan {
|
||||
w.Header().Set("X-CSTP-Split-Exclude", "0.0.0.0/255.255.255.255")
|
||||
HttpSetHeader(w, "X-CSTP-Split-Exclude", "0.0.0.0/255.255.255.255")
|
||||
}
|
||||
// dns地址
|
||||
for _, v := range cSess.Group.ClientDns {
|
||||
w.Header().Add("X-CSTP-DNS", v.Val)
|
||||
HttpAddHeader(w, "X-CSTP-DNS", v.Val)
|
||||
}
|
||||
// 允许的路由
|
||||
for _, v := range cSess.Group.RouteInclude {
|
||||
w.Header().Add("X-CSTP-Split-Include", v.IpMask)
|
||||
if v.Val == dbdata.All {
|
||||
continue
|
||||
}
|
||||
HttpAddHeader(w, "X-CSTP-Split-Include", v.IpMask)
|
||||
}
|
||||
// 不允许的路由
|
||||
for _, v := range cSess.Group.RouteExclude {
|
||||
w.Header().Add("X-CSTP-Split-Exclude", v.IpMask)
|
||||
HttpAddHeader(w, "X-CSTP-Split-Exclude", v.IpMask)
|
||||
}
|
||||
HttpSetHeader(w, "X-CSTP-Lease-Duration", fmt.Sprintf("%d", base.Cfg.IpLease)) // ip地址租期
|
||||
HttpSetHeader(w, "X-CSTP-Session-Timeout", "none")
|
||||
HttpSetHeader(w, "X-CSTP-Session-Timeout-Alert-Interval", "60")
|
||||
HttpSetHeader(w, "X-CSTP-Session-Timeout-Remaining", "none")
|
||||
HttpSetHeader(w, "X-CSTP-Idle-Timeout", "18000")
|
||||
HttpSetHeader(w, "X-CSTP-Disconnected-Timeout", "18000")
|
||||
HttpSetHeader(w, "X-CSTP-Keep", "true")
|
||||
HttpSetHeader(w, "X-CSTP-Tunnel-All-DNS", "false")
|
||||
|
||||
HttpSetHeader(w, "X-CSTP-Rekey-Time", "172800")
|
||||
HttpSetHeader(w, "X-CSTP-Rekey-Method", "new-tunnel")
|
||||
|
||||
HttpSetHeader(w, "X-CSTP-DPD", fmt.Sprintf("%d", cstpDpd))
|
||||
HttpSetHeader(w, "X-CSTP-Keepalive", fmt.Sprintf("%d", cstpKeepalive))
|
||||
// HttpSetHeader(w, "X-CSTP-Banner", banner.Banner)
|
||||
HttpSetHeader(w, "X-CSTP-MSIE-Proxy-Lockdown", "true")
|
||||
HttpSetHeader(w, "X-CSTP-Smartcard-Removal-Disconnect", "true")
|
||||
|
||||
HttpSetHeader(w, "X-CSTP-MTU", fmt.Sprintf("%d", cSess.Mtu)) // 1399
|
||||
HttpSetHeader(w, "X-DTLS-MTU", fmt.Sprintf("%d", cSess.Mtu))
|
||||
|
||||
HttpSetHeader(w, "X-DTLS-Session-ID", sess.DtlsSid)
|
||||
HttpSetHeader(w, "X-DTLS-Port", dtlsPort)
|
||||
HttpSetHeader(w, "X-DTLS-DPD", fmt.Sprintf("%d", cstpDpd))
|
||||
HttpSetHeader(w, "X-DTLS-Keepalive", fmt.Sprintf("%d", cstpKeepalive))
|
||||
HttpSetHeader(w, "X-DTLS-Rekey-Time", "5400")
|
||||
HttpSetHeader(w, "X-DTLS12-CipherSuite", "ECDHE-ECDSA-AES128-GCM-SHA256")
|
||||
|
||||
HttpSetHeader(w, "X-CSTP-License", "accept")
|
||||
HttpSetHeader(w, "X-CSTP-Routing-Filtering-Ignore", "false")
|
||||
HttpSetHeader(w, "X-CSTP-Quarantine", "false")
|
||||
HttpSetHeader(w, "X-CSTP-Disable-Always-On-VPN", "false")
|
||||
HttpSetHeader(w, "X-CSTP-Client-Bypass-Protocol", "false")
|
||||
HttpSetHeader(w, "X-CSTP-TCP-Keepalive", "false")
|
||||
// 设置域名拆分隧道(移动端不支持)
|
||||
if mobile != "mobile" {
|
||||
SetPostAuthXml(cSess.Group, w)
|
||||
}
|
||||
|
||||
w.Header().Set("X-CSTP-Lease-Duration", fmt.Sprintf("%d", base.Cfg.IpLease)) // ip地址租期
|
||||
w.Header().Set("X-CSTP-Session-Timeout", "none")
|
||||
w.Header().Set("X-CSTP-Session-Timeout-Alert-Interval", "60")
|
||||
w.Header().Set("X-CSTP-Session-Timeout-Remaining", "none")
|
||||
w.Header().Set("X-CSTP-Idle-Timeout", "18000")
|
||||
w.Header().Set("X-CSTP-Disconnected-Timeout", "18000")
|
||||
w.Header().Set("X-CSTP-Keep", "true")
|
||||
w.Header().Set("X-CSTP-Tunnel-All-DNS", "false")
|
||||
|
||||
w.Header().Set("X-CSTP-Rekey-Time", "172800")
|
||||
w.Header().Set("X-CSTP-Rekey-Method", "new-tunnel")
|
||||
|
||||
w.Header().Set("X-CSTP-DPD", fmt.Sprintf("%d", cstpDpd))
|
||||
w.Header().Set("X-CSTP-Keepalive", fmt.Sprintf("%d", cstpKeepalive))
|
||||
// w.Header().Set("X-CSTP-Banner", banner.Banner)
|
||||
w.Header().Set("X-CSTP-MSIE-Proxy-Lockdown", "true")
|
||||
w.Header().Set("X-CSTP-Smartcard-Removal-Disconnect", "true")
|
||||
|
||||
w.Header().Set("X-CSTP-MTU", fmt.Sprintf("%d", cSess.Mtu)) // 1399
|
||||
w.Header().Set("X-DTLS-MTU", fmt.Sprintf("%d", cSess.Mtu))
|
||||
|
||||
w.Header().Set("X-DTLS-Session-ID", sess.DtlsSid)
|
||||
w.Header().Set("X-DTLS-Port", dtlsPort)
|
||||
w.Header().Set("X-DTLS-DPD", fmt.Sprintf("%d", cstpDpd))
|
||||
w.Header().Set("X-DTLS-Keepalive", fmt.Sprintf("%d", cstpKeepalive))
|
||||
w.Header().Set("X-DTLS-Rekey-Time", "5400")
|
||||
w.Header().Set("X-DTLS12-CipherSuite", "ECDHE-ECDSA-AES128-GCM-SHA256")
|
||||
|
||||
w.Header().Set("X-CSTP-License", "accept")
|
||||
w.Header().Set("X-CSTP-Routing-Filtering-Ignore", "false")
|
||||
w.Header().Set("X-CSTP-Quarantine", "false")
|
||||
w.Header().Set("X-CSTP-Disable-Always-On-VPN", "false")
|
||||
w.Header().Set("X-CSTP-Client-Bypass-Protocol", "false")
|
||||
w.Header().Set("X-CSTP-TCP-Keepalive", "false")
|
||||
// w.Header().Set("X-CSTP-Post-Auth-XML", ``)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
hClone := w.Header().Clone()
|
||||
@@ -147,7 +170,7 @@ func LinkTunnel(w http.ResponseWriter, r *http.Request) {
|
||||
base.Debug(buf.String())
|
||||
|
||||
hj := w.(http.Hijacker)
|
||||
conn, _, err := hj.Hijack()
|
||||
conn, bufRW, err := hj.Hijack()
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
@@ -160,11 +183,46 @@ func LinkTunnel(w http.ResponseWriter, r *http.Request) {
|
||||
err = LinkTun(cSess)
|
||||
case base.LinkModeTAP:
|
||||
err = LinkTap(cSess)
|
||||
case base.LinkModeMacvtap:
|
||||
err = LinkMacvtap(cSess)
|
||||
}
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
conn.Close()
|
||||
base.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
go LinkCstp(conn, cSess)
|
||||
go LinkCstp(conn, bufRW, cSess)
|
||||
}
|
||||
|
||||
// 设置域名拆分隧道
|
||||
func SetPostAuthXml(g *dbdata.Group, w http.ResponseWriter) error {
|
||||
if g.DsExcludeDomains == "" && g.DsIncludeDomains == "" {
|
||||
return nil
|
||||
}
|
||||
tmpl, err := template.New("post_auth_xml").Parse(ds_domains_xml)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var result bytes.Buffer
|
||||
err = tmpl.Execute(&result, g)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
HttpSetHeader(w, "X-CSTP-Post-Auth-XML", result.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// 设置用户策略, 覆盖Group的属性值
|
||||
func SetUserPolicy(username string, g *dbdata.Group) {
|
||||
userPolicy := dbdata.GetPolicy(username)
|
||||
if userPolicy.Id != 0 && userPolicy.Status == 1 {
|
||||
base.Debug(username + " use UserPolicy")
|
||||
g.AllowLan = userPolicy.AllowLan
|
||||
g.ClientDns = userPolicy.ClientDns
|
||||
g.RouteInclude = userPolicy.RouteInclude
|
||||
g.RouteExclude = userPolicy.RouteExclude
|
||||
g.DsExcludeDomains = userPolicy.DsExcludeDomains
|
||||
g.DsIncludeDomains = userPolicy.DsIncludeDomains
|
||||
}
|
||||
}
|
||||
|
137
server/handler/link_vtap.go
Normal file
@@ -0,0 +1,137 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
// link vtap
|
||||
const vTapPrefix = "lvtap"
|
||||
|
||||
type Vtap struct {
|
||||
*os.File
|
||||
ifName string
|
||||
}
|
||||
|
||||
func (v *Vtap) Close() error {
|
||||
v.File.Close()
|
||||
cmdstr := fmt.Sprintf("ip link del %s", v.ifName)
|
||||
return execCmd([]string{cmdstr})
|
||||
}
|
||||
|
||||
func checkMacvtap() {
|
||||
_setGateway()
|
||||
_checkTapIp(base.Cfg.Ipv4Master)
|
||||
|
||||
ifName := "anylinkMacvtap"
|
||||
// 加载 macvtap
|
||||
cmdstr0 := fmt.Sprintf("modprobe -i macvtap")
|
||||
// 开启主网卡混杂模式
|
||||
cmdstr1 := fmt.Sprintf("ip link set dev %s promisc on", base.Cfg.Ipv4Master)
|
||||
// 测试 macvtap 功能
|
||||
cmdstr2 := fmt.Sprintf("ip link add link %s name %s type macvtap mode bridge", base.Cfg.Ipv4Master, ifName)
|
||||
cmdstr3 := fmt.Sprintf("ip link del %s", ifName)
|
||||
err := execCmd([]string{cmdstr0, cmdstr1, cmdstr2, cmdstr3})
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// 创建 Macvtap 网卡
|
||||
func LinkMacvtap(cSess *sessdata.ConnSession) error {
|
||||
capL := sessdata.IpPool.IpLongMax - sessdata.IpPool.IpLongMin
|
||||
ipN := utils.Ip2long(cSess.IpAddr) % capL
|
||||
ifName := fmt.Sprintf("%s%d", vTapPrefix, ipN)
|
||||
|
||||
cSess.SetIfName(ifName)
|
||||
|
||||
cmdstr1 := fmt.Sprintf("ip link add link %s name %s type macvtap mode bridge", base.Cfg.Ipv4Master, ifName)
|
||||
cmdstr2 := fmt.Sprintf("ip link set dev %s up mtu %d address %s", ifName, cSess.Mtu, cSess.MacHw)
|
||||
err := execCmd([]string{cmdstr1, cmdstr2})
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
return err
|
||||
}
|
||||
cmdstr3 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifName)
|
||||
execCmd([]string{cmdstr3})
|
||||
|
||||
return createVtap(cSess, ifName)
|
||||
}
|
||||
|
||||
func checkIpvtap() {
|
||||
|
||||
}
|
||||
|
||||
// 创建 Ipvtap 网卡
|
||||
func LinkIpvtap(cSess *sessdata.ConnSession) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ifReq struct {
|
||||
Name [0x10]byte
|
||||
Flags uint16
|
||||
pad [0x28 - 0x10 - 2]byte
|
||||
}
|
||||
|
||||
func createVtap(cSess *sessdata.ConnSession, ifName string) error {
|
||||
// 初始化 ifName
|
||||
inf, err := net.InterfaceByName(ifName)
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
tName := fmt.Sprintf("/dev/tap%d", inf.Index)
|
||||
|
||||
var fdInt int
|
||||
|
||||
fdInt, err = syscall.Open(tName, syscall.O_RDWR|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var flags uint16 = syscall.IFF_TAP | syscall.IFF_NO_PI
|
||||
var req ifReq
|
||||
req.Flags = flags
|
||||
|
||||
_, _, errno := syscall.Syscall(
|
||||
syscall.SYS_IOCTL,
|
||||
uintptr(fdInt),
|
||||
uintptr(syscall.TUNSETIFF),
|
||||
uintptr(unsafe.Pointer(&req)),
|
||||
)
|
||||
if errno != 0 {
|
||||
return os.NewSyscallError("ioctl", errno)
|
||||
}
|
||||
|
||||
file := os.NewFile(uintptr(fdInt), tName)
|
||||
ifce := &Vtap{file, ifName}
|
||||
|
||||
go allTapRead(ifce, cSess)
|
||||
go allTapWrite(ifce, cSess)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 销毁未关闭的vtap
|
||||
func destroyVtap() {
|
||||
its, err := net.Interfaces()
|
||||
if err != nil {
|
||||
base.Error(err)
|
||||
return
|
||||
}
|
||||
for _, v := range its {
|
||||
if strings.HasPrefix(v.Name, vTapPrefix) {
|
||||
// 删除原来的网卡
|
||||
cmdstr := fmt.Sprintf("ip link del %s", v.Name)
|
||||
execCmd([]string{cmdstr})
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,31 +1,30 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
"github.com/songgao/water/waterutil"
|
||||
)
|
||||
|
||||
func payloadIn(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
|
||||
pl := getPayload()
|
||||
pl.LType = lType
|
||||
pl.PType = pType
|
||||
pl.Data = append(pl.Data, data...)
|
||||
func payloadIn(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
|
||||
if pl.LType == sessdata.LTypeIPData && pl.PType == 0x00 {
|
||||
// 进行Acl规则判断
|
||||
check := checkLinkAcl(cSess.Group, pl)
|
||||
if !check {
|
||||
// 校验不通过直接丢弃
|
||||
return false
|
||||
}
|
||||
|
||||
return payloadInData(cSess, pl)
|
||||
}
|
||||
|
||||
func payloadInData(cSess *sessdata.ConnSession, payload *sessdata.Payload) bool {
|
||||
// 进行Acl规则判断
|
||||
check := checkLinkAcl(cSess.Group, payload)
|
||||
if !check {
|
||||
// 校验不通过直接丢弃
|
||||
return false
|
||||
logAudit(cSess, pl)
|
||||
}
|
||||
|
||||
closed := false
|
||||
select {
|
||||
case cSess.PayloadIn <- payload:
|
||||
case cSess.PayloadIn <- pl:
|
||||
case <-cSess.CloseChan:
|
||||
closed = true
|
||||
}
|
||||
@@ -33,21 +32,16 @@ func payloadInData(cSess *sessdata.ConnSession, payload *sessdata.Payload) bool
|
||||
return closed
|
||||
}
|
||||
|
||||
func payloadOut(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
|
||||
func payloadOut(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
|
||||
dSess := cSess.GetDtlsSession()
|
||||
if dSess == nil {
|
||||
return payloadOutCstp(cSess, lType, pType, data)
|
||||
return payloadOutCstp(cSess, pl)
|
||||
} else {
|
||||
return payloadOutDtls(cSess, dSess, lType, pType, data)
|
||||
return payloadOutDtls(cSess, dSess, pl)
|
||||
}
|
||||
}
|
||||
|
||||
func payloadOutCstp(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
|
||||
pl := getPayload()
|
||||
pl.LType = lType
|
||||
pl.PType = pType
|
||||
pl.Data = append(pl.Data, data...)
|
||||
|
||||
func payloadOutCstp(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
|
||||
closed := false
|
||||
|
||||
select {
|
||||
@@ -59,12 +53,7 @@ func payloadOutCstp(cSess *sessdata.ConnSession, lType sessdata.LType, pType byt
|
||||
return closed
|
||||
}
|
||||
|
||||
func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, lType sessdata.LType, pType byte, data []byte) bool {
|
||||
pl := getPayload()
|
||||
pl.LType = lType
|
||||
pl.PType = pType
|
||||
pl.Data = append(pl.Data, data...)
|
||||
|
||||
func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, pl *sessdata.Payload) bool {
|
||||
select {
|
||||
case cSess.PayloadOutDtls <- pl:
|
||||
case <-dSess.CloseChan:
|
||||
@@ -74,27 +63,29 @@ func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, lT
|
||||
}
|
||||
|
||||
// Acl规则校验
|
||||
func checkLinkAcl(group *dbdata.Group, payload *sessdata.Payload) bool {
|
||||
if payload.LType == sessdata.LTypeIPData && payload.PType == 0x00 && len(group.LinkAcl) > 0 {
|
||||
func checkLinkAcl(group *dbdata.Group, pl *sessdata.Payload) bool {
|
||||
if pl.LType == sessdata.LTypeIPData && pl.PType == 0x00 && len(group.LinkAcl) > 0 {
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
|
||||
ip_dst := waterutil.IPv4Destination(payload.Data)
|
||||
ip_port := waterutil.IPv4DestinationPort(payload.Data)
|
||||
ipDst := waterutil.IPv4Destination(pl.Data)
|
||||
ipPort := waterutil.IPv4DestinationPort(pl.Data)
|
||||
ipProto := waterutil.IPv4Protocol(pl.Data)
|
||||
// fmt.Println("sent:", ip_dst, ip_port)
|
||||
|
||||
// 优先放行dns端口
|
||||
for _, v := range group.ClientDns {
|
||||
if v.Val == ip_dst.String() && ip_port == 53 {
|
||||
if v.Val == ipDst.String() && ipPort == 53 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
for _, v := range group.LinkAcl {
|
||||
// 循环判断ip和端口
|
||||
if v.IpNet.Contains(ip_dst) {
|
||||
if v.Port == ip_port || v.Port == 0 {
|
||||
if v.IpNet.Contains(ipDst) {
|
||||
// 放行允许ip的ping
|
||||
if v.Port == ipPort || v.Port == 0 || ipProto == waterutil.ICMP {
|
||||
if v.Action == dbdata.Allow {
|
||||
return true
|
||||
} else {
|
||||
@@ -106,3 +97,53 @@ func checkLinkAcl(group *dbdata.Group, payload *sessdata.Payload) bool {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// 访问日志审计
|
||||
func logAudit(cSess *sessdata.ConnSession, pl *sessdata.Payload) {
|
||||
if base.Cfg.AuditInterval < 0 {
|
||||
return
|
||||
}
|
||||
|
||||
ipProto := waterutil.IPv4Protocol(pl.Data)
|
||||
// 只统计 tcp和udp 的访问
|
||||
switch ipProto {
|
||||
case waterutil.TCP:
|
||||
case waterutil.UDP:
|
||||
default:
|
||||
return
|
||||
}
|
||||
|
||||
ipSrc := waterutil.IPv4Source(pl.Data)
|
||||
ipDst := waterutil.IPv4Destination(pl.Data)
|
||||
ipPort := waterutil.IPv4DestinationPort(pl.Data)
|
||||
|
||||
b := getByte34()
|
||||
key := *b
|
||||
copy(key[:16], ipSrc)
|
||||
copy(key[16:32], ipDst)
|
||||
binary.BigEndian.PutUint16(key[32:34], ipPort)
|
||||
|
||||
s := utils.BytesToString(key)
|
||||
nu := utils.NowSec().Unix()
|
||||
|
||||
// 判断已经存在,并且没有过期
|
||||
v, ok := cSess.IpAuditMap[s]
|
||||
if ok && nu-v < int64(base.Cfg.AuditInterval) {
|
||||
// 回收byte对象
|
||||
putByte34(b)
|
||||
return
|
||||
}
|
||||
|
||||
cSess.IpAuditMap[s] = nu
|
||||
|
||||
audit := dbdata.AccessAudit{
|
||||
Username: cSess.Sess.Username,
|
||||
Protocol: uint8(ipProto),
|
||||
Src: ipSrc.String(),
|
||||
Dst: ipDst.String(),
|
||||
DstPort: ipPort,
|
||||
CreatedAt: utils.NowSec(),
|
||||
}
|
||||
|
||||
_ = dbdata.Add(audit)
|
||||
}
|
||||
|
@@ -3,13 +3,26 @@ package handler
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/sessdata"
|
||||
)
|
||||
|
||||
// 不允许直接修改
|
||||
// [6] => PType
|
||||
var plHeader = []byte{
|
||||
'S', 'T', 'F', 1,
|
||||
0x00, 0x00, /* Length */
|
||||
0x00, /* Type */
|
||||
0x00, /* Unknown */
|
||||
}
|
||||
|
||||
var plPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
b := make([]byte, BufferSize)
|
||||
pl := sessdata.Payload{
|
||||
Data: make([]byte, 0, BufferSize),
|
||||
LType: sessdata.LTypeIPData,
|
||||
PType: 0x00,
|
||||
Data: b,
|
||||
}
|
||||
// fmt.Println("plPool-init", len(pl.Data), cap(pl.Data))
|
||||
return &pl
|
||||
@@ -22,31 +35,55 @@ func getPayload() *sessdata.Payload {
|
||||
}
|
||||
|
||||
func putPayload(pl *sessdata.Payload) {
|
||||
pl.LType = 0
|
||||
pl.PType = 0
|
||||
pl.Data = pl.Data[:0]
|
||||
// 错误数据丢弃
|
||||
if cap(pl.Data) != BufferSize {
|
||||
base.Warn("payload cap is err", cap(pl.Data))
|
||||
return
|
||||
}
|
||||
|
||||
pl.LType = sessdata.LTypeIPData
|
||||
pl.PType = 0x00
|
||||
pl.Data = pl.Data[:BufferSize]
|
||||
plPool.Put(pl)
|
||||
}
|
||||
|
||||
var bytePool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
b := make([]byte, 0, BufferSize)
|
||||
b := make([]byte, BufferSize)
|
||||
// fmt.Println("bytePool-init")
|
||||
return b
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
func getByteZero() []byte {
|
||||
b := bytePool.Get().([]byte)
|
||||
func getByteZero() *[]byte {
|
||||
b := bytePool.Get().(*[]byte)
|
||||
*b = (*b)[:0]
|
||||
return b
|
||||
}
|
||||
|
||||
func getByteFull() []byte {
|
||||
b := bytePool.Get().([]byte)
|
||||
b = b[:BufferSize]
|
||||
func getByteFull() *[]byte {
|
||||
b := bytePool.Get().(*[]byte)
|
||||
return b
|
||||
}
|
||||
func putByte(b []byte) {
|
||||
b = b[:0]
|
||||
func putByte(b *[]byte) {
|
||||
*b = (*b)[:BufferSize]
|
||||
bytePool.Put(b)
|
||||
}
|
||||
|
||||
// 长度 34 小对象
|
||||
var byte34Pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
b := make([]byte, 34)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
func getByte34() *[]byte {
|
||||
b := byte34Pool.Get().(*[]byte)
|
||||
return b
|
||||
}
|
||||
|
||||
func putByte34(b *[]byte) {
|
||||
*b = (*b)[:34]
|
||||
byte34Pool.Put(b)
|
||||
}
|
||||
|
44
server/handler/pool_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// go test -bench=. -benchmem
|
||||
|
||||
// 去除数据头
|
||||
func BenchmarkHeaderCopy(b *testing.B) {
|
||||
l := 1500
|
||||
for i := 0; i < b.N; i++ {
|
||||
b.StopTimer()
|
||||
pl := getPayload()
|
||||
// 初始化数据
|
||||
pl.Data = pl.Data[:l]
|
||||
|
||||
b.StartTimer()
|
||||
dataLen := l - 8
|
||||
copy(pl.Data, pl.Data[8:8+dataLen])
|
||||
// 更新切片长度
|
||||
pl.Data = pl.Data[:dataLen]
|
||||
b.StopTimer()
|
||||
|
||||
putPayload(pl)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkHeaderAppend(b *testing.B) {
|
||||
l := 1500
|
||||
for i := 0; i < b.N; i++ {
|
||||
b.StopTimer()
|
||||
pl := getPayload()
|
||||
// 初始化数据
|
||||
pl.Data = pl.Data[:l]
|
||||
|
||||
b.StartTimer()
|
||||
dataLen := l - 8
|
||||
pl.Data = append(pl.Data[:0], pl.Data[:8+dataLen]...)
|
||||
b.StopTimer()
|
||||
|
||||
putPayload(pl)
|
||||
}
|
||||
}
|
@@ -6,6 +6,7 @@ import (
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
@@ -14,15 +15,39 @@ import (
|
||||
)
|
||||
|
||||
func startTls() {
|
||||
addr := base.Cfg.ServerAddr
|
||||
certFile := base.Cfg.CertFile
|
||||
keyFile := base.Cfg.CertKey
|
||||
|
||||
var (
|
||||
err error
|
||||
|
||||
addr = base.Cfg.ServerAddr
|
||||
ln net.Listener
|
||||
)
|
||||
|
||||
// 判断证书文件
|
||||
// _, err = os.Stat(certFile)
|
||||
// if errors.Is(err, os.ErrNotExist) {
|
||||
// // 自动生成证书
|
||||
// certs[0], err = selfsign.GenerateSelfSignedWithDNS("vpn.anylink")
|
||||
// } else {
|
||||
// // 使用自定义证书
|
||||
// certs[0], err = tls.LoadX509KeyPair(certFile, keyFile)
|
||||
// }
|
||||
|
||||
// 修复 CVE-2016-2183
|
||||
// https://segmentfault.com/a/1190000038486901
|
||||
// nmap -sV --script ssl-enum-ciphers -p 443 www.example.com
|
||||
cipherSuites := tls.CipherSuites()
|
||||
selectedCipherSuites := make([]uint16, 0, len(cipherSuites))
|
||||
for _, s := range cipherSuites {
|
||||
selectedCipherSuites = append(selectedCipherSuites, s.ID)
|
||||
}
|
||||
|
||||
// 设置tls信息
|
||||
tlsConfig := &tls.Config{
|
||||
NextProtos: []string{"http/1.1"},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: true,
|
||||
NextProtos: []string{"http/1.1"},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CipherSuites: selectedCipherSuites,
|
||||
// InsecureSkipVerify: true,
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
@@ -31,9 +56,7 @@ func startTls() {
|
||||
ErrorLog: base.GetBaseLog(),
|
||||
}
|
||||
|
||||
var ln net.Listener
|
||||
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
ln, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -44,7 +67,7 @@ func startTls() {
|
||||
}
|
||||
|
||||
base.Info("listen server", addr)
|
||||
err = srv.ServeTLS(ln, certFile, keyFile)
|
||||
err = srv.ServeTLS(ln, base.Cfg.CertFile, base.Cfg.CertKey)
|
||||
if err != nil {
|
||||
base.Fatal(err)
|
||||
}
|
||||
@@ -56,6 +79,10 @@ func initRoute() http.Handler {
|
||||
r.HandleFunc("/", LinkAuth).Methods(http.MethodPost)
|
||||
r.HandleFunc("/CSCOSSLC/tunnel", LinkTunnel).Methods(http.MethodConnect)
|
||||
r.HandleFunc("/otp_qr", LinkOtpQr).Methods(http.MethodGet)
|
||||
r.HandleFunc("/profile.xml", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := os.ReadFile(base.Cfg.Profile)
|
||||
w.Write(b)
|
||||
}).Methods(http.MethodGet)
|
||||
r.PathPrefix("/files/").Handler(
|
||||
http.StripPrefix("/files/",
|
||||
http.FileServer(http.Dir(base.Cfg.FilesPath)),
|
||||
|
@@ -1,6 +1,10 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
|
||||
"github.com/bjdgyc/anylink/admin"
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
@@ -11,10 +15,25 @@ func Start() {
|
||||
dbdata.Start()
|
||||
sessdata.Start()
|
||||
|
||||
checkTun()
|
||||
if base.Cfg.LinkMode == base.LinkModeTAP {
|
||||
switch base.Cfg.LinkMode {
|
||||
case base.LinkModeTUN:
|
||||
checkTun()
|
||||
case base.LinkModeTAP:
|
||||
checkTap()
|
||||
case base.LinkModeMacvtap:
|
||||
checkMacvtap()
|
||||
default:
|
||||
base.Fatal("LinkMode is err")
|
||||
}
|
||||
|
||||
// 计算profile.xml的hash
|
||||
b, err := os.ReadFile(base.Cfg.Profile)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ha := sha1.Sum(b)
|
||||
profileHash = hex.EncodeToString(ha[:])
|
||||
|
||||
go admin.StartAdmin()
|
||||
go startTls()
|
||||
go startDtls()
|
||||
@@ -22,4 +41,5 @@ func Start() {
|
||||
|
||||
func Stop() {
|
||||
_ = dbdata.Stop()
|
||||
destroyVtap()
|
||||
}
|
||||
|
@@ -1,21 +1,29 @@
|
||||
// AnyLink 是一个企业级远程办公vpn软件,可以支持多人同时在线使用。
|
||||
|
||||
// +build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/bjdgyc/anylink/admin"
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/handler"
|
||||
)
|
||||
|
||||
//go:embed ui
|
||||
var uiData embed.FS
|
||||
|
||||
// 程序版本
|
||||
var COMMIT_ID string
|
||||
var CommitId string
|
||||
|
||||
func main() {
|
||||
base.CommitId = COMMIT_ID
|
||||
base.CommitId = CommitId
|
||||
admin.UiData = uiData
|
||||
|
||||
base.Start()
|
||||
handler.Start()
|
||||
|
@@ -4,6 +4,8 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -16,7 +18,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
table = make(map[string]*Addr)
|
||||
table = make(map[string]*Addr, 128)
|
||||
tableMu sync.RWMutex
|
||||
)
|
||||
|
||||
@@ -40,25 +42,25 @@ func Lookup(ip net.IP, onlyTable bool) *Addr {
|
||||
|
||||
// Add adds a IP-MAC map to a runtime ARP table.
|
||||
func tableLookup(ip net.IP) *Addr {
|
||||
tableMu.Lock()
|
||||
tableMu.RLock()
|
||||
addr := table[ip.To4().String()]
|
||||
tableMu.Unlock()
|
||||
tableMu.RUnlock()
|
||||
if addr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 判断老化过期时间
|
||||
tsub := time.Since(addr.disTime)
|
||||
tSub := utils.NowSec().Sub(addr.disTime)
|
||||
switch addr.Type {
|
||||
case TypeStatic:
|
||||
case TypeNormal:
|
||||
if tsub > StaleTimeNormal {
|
||||
if tSub > StaleTimeNormal {
|
||||
return nil
|
||||
}
|
||||
case TypeUnreachable:
|
||||
if tsub > StaleTimeUnreachable {
|
||||
if tSub > StaleTimeUnreachable {
|
||||
return nil
|
||||
}
|
||||
case TypeStatic:
|
||||
}
|
||||
|
||||
return addr
|
||||
@@ -70,7 +72,7 @@ func Add(addr *Addr) {
|
||||
return
|
||||
}
|
||||
if addr.disTime.IsZero() {
|
||||
addr.disTime = time.Now()
|
||||
addr.disTime = utils.NowSec()
|
||||
}
|
||||
ip := addr.IP.To4().String()
|
||||
tableMu.Lock()
|
||||
|
@@ -19,7 +19,8 @@ func doLookup(ip net.IP) *Addr {
|
||||
err := doPing(ip.String())
|
||||
if err != nil {
|
||||
// log.Println(err)
|
||||
addr := &Addr{IP: ip, Type: TypeUnreachable}
|
||||
addr := &Addr{IP: net.IPv4(1, 2, 3, 4), Type: TypeUnreachable}
|
||||
copy(addr.IP, ip)
|
||||
return addr
|
||||
}
|
||||
|
||||
@@ -50,7 +51,9 @@ func doArpShow(ip net.IP) *Addr {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &Addr{IP: ip, HardwareAddr: mac}
|
||||
addr := &Addr{IP: net.IPv4(1, 2, 3, 4), HardwareAddr: mac}
|
||||
copy(addr.IP, ip)
|
||||
return addr
|
||||
}
|
||||
|
||||
// IP address HW type Flags HW address Mask Device
|
||||
|
17
server/pkg/utils/ip.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
)
|
||||
|
||||
func Long2ip(i uint32) net.IP {
|
||||
ip := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(ip, i)
|
||||
return ip
|
||||
}
|
||||
|
||||
func Ip2long(ip net.IP) uint32 {
|
||||
ip = ip.To4()
|
||||
return binary.BigEndian.Uint32(ip)
|
||||
}
|
20
server/pkg/utils/unsafe.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// BytesToString converts byte slice to string.
|
||||
func BytesToString(b []byte) string {
|
||||
return *(*string)(unsafe.Pointer(&b))
|
||||
}
|
||||
|
||||
// StringToBytes converts string to byte slice.
|
||||
func StringToBytes(s string) []byte {
|
||||
return *(*[]byte)(unsafe.Pointer(
|
||||
&struct {
|
||||
string
|
||||
Cap int
|
||||
}{s, len(s)},
|
||||
))
|
||||
}
|
@@ -3,11 +3,30 @@ package utils
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// 每秒时间缓存
|
||||
timeNowSec = &atomic.Value{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
timeNowSec.Store(time.Now())
|
||||
go func() {
|
||||
tick := time.NewTicker(time.Second * 1)
|
||||
for c := range tick.C {
|
||||
timeNowSec.Store(c)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func NowSec() time.Time {
|
||||
t := timeNowSec.Load()
|
||||
return t.(time.Time)
|
||||
}
|
||||
|
||||
func InArrStr(arr []string, str string) bool {
|
||||
|
@@ -1,13 +1,13 @@
|
||||
package sessdata
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/bjdgyc/anylink/base"
|
||||
"github.com/bjdgyc/anylink/dbdata"
|
||||
"github.com/bjdgyc/anylink/pkg/utils"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -43,22 +43,11 @@ func initIpPool() {
|
||||
// max := min | uint32(math.Pow(2, float64(32-one))-1)
|
||||
|
||||
// ip地址池
|
||||
IpPool.IpLongMin = ip2long(net.ParseIP(base.Cfg.Ipv4Start))
|
||||
IpPool.IpLongMax = ip2long(net.ParseIP(base.Cfg.Ipv4End))
|
||||
IpPool.IpLongMin = utils.Ip2long(net.ParseIP(base.Cfg.Ipv4Start))
|
||||
IpPool.IpLongMax = utils.Ip2long(net.ParseIP(base.Cfg.Ipv4End))
|
||||
}
|
||||
|
||||
func long2ip(i uint32) net.IP {
|
||||
ip := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(ip, i)
|
||||
return ip
|
||||
}
|
||||
|
||||
func ip2long(ip net.IP) uint32 {
|
||||
ip = ip.To4()
|
||||
return binary.BigEndian.Uint32(ip)
|
||||
}
|
||||
|
||||
// 获取动态ip
|
||||
// AcquireIp 获取动态ip
|
||||
func AcquireIp(username, macAddr string) net.IP {
|
||||
IpPool.mux.Lock()
|
||||
defer IpPool.mux.Unlock()
|
||||
@@ -67,43 +56,30 @@ func AcquireIp(username, macAddr string) net.IP {
|
||||
|
||||
// 判断已经分配过
|
||||
mi := &dbdata.IpMap{}
|
||||
err := dbdata.One("MacAddr", macAddr, mi)
|
||||
err := dbdata.One("mac_addr", macAddr, mi)
|
||||
if err == nil {
|
||||
ip := mi.IpAddr
|
||||
ipStr := ip.String()
|
||||
ipStr := mi.IpAddr
|
||||
ip := net.ParseIP(ipStr)
|
||||
// 跳过活跃连接
|
||||
_, ok := ipActive[ipStr]
|
||||
// 检测原有ip是否在新的ip池内
|
||||
if IpPool.Ipv4IPNet.Contains(ip) {
|
||||
if IpPool.Ipv4IPNet.Contains(ip) && !ok {
|
||||
mi.Username = username
|
||||
mi.LastLogin = tNow
|
||||
// 回写db数据
|
||||
_ = dbdata.Save(mi)
|
||||
_ = dbdata.Add(mi)
|
||||
ipActive[ipStr] = true
|
||||
return ip
|
||||
} else {
|
||||
_ = dbdata.Del(mi)
|
||||
}
|
||||
}
|
||||
|
||||
// 全局遍历未分配ip
|
||||
// 优先获取没有使用的ip
|
||||
for i := IpPool.IpLongMin; i <= IpPool.IpLongMax; i++ {
|
||||
ip := long2ip(i)
|
||||
ipStr := ip.String()
|
||||
mi := &dbdata.IpMap{}
|
||||
err := dbdata.One("IpAddr", ip, mi)
|
||||
if err != nil && dbdata.CheckErrNotFound(err) {
|
||||
// 该ip没有被使用
|
||||
mi := &dbdata.IpMap{IpAddr: ip, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
_ = dbdata.Save(mi)
|
||||
ipActive[ipStr] = true
|
||||
return ip
|
||||
}
|
||||
_ = dbdata.Del(mi)
|
||||
|
||||
}
|
||||
|
||||
farIp := &dbdata.IpMap{LastLogin: tNow}
|
||||
// 遍历超过租期ip
|
||||
// 全局遍历超过租期ip
|
||||
for i := IpPool.IpLongMin; i <= IpPool.IpLongMax; i++ {
|
||||
ip := long2ip(i)
|
||||
ip := utils.Long2ip(i)
|
||||
ipStr := ip.String()
|
||||
|
||||
// 跳过活跃连接
|
||||
@@ -112,11 +88,20 @@ func AcquireIp(username, macAddr string) net.IP {
|
||||
}
|
||||
|
||||
v := &dbdata.IpMap{}
|
||||
err := dbdata.One("IpAddr", ip, v)
|
||||
err = dbdata.One("ip_addr", ipStr, v)
|
||||
if err != nil {
|
||||
if dbdata.CheckErrNotFound(err) {
|
||||
// 该ip没有被使用
|
||||
mi = &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
_ = dbdata.Add(mi)
|
||||
ipActive[ipStr] = true
|
||||
return ip
|
||||
}
|
||||
base.Error(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 跳过ip保留
|
||||
if v.Keep {
|
||||
continue
|
||||
}
|
||||
@@ -124,9 +109,9 @@ func AcquireIp(username, macAddr string) net.IP {
|
||||
// 已经超过租期
|
||||
if tNow.Sub(v.LastLogin) > time.Duration(base.Cfg.IpLease)*time.Second {
|
||||
_ = dbdata.Del(v)
|
||||
mi := &dbdata.IpMap{IpAddr: ip, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
mi = &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
// 重写db数据
|
||||
_ = dbdata.Save(mi)
|
||||
_ = dbdata.Add(mi)
|
||||
ipActive[ipStr] = true
|
||||
return ip
|
||||
}
|
||||
@@ -143,11 +128,11 @@ func AcquireIp(username, macAddr string) net.IP {
|
||||
}
|
||||
|
||||
// 使用最早登陆的mac ip
|
||||
ip := farIp.IpAddr
|
||||
ipStr := ip.String()
|
||||
mi = &dbdata.IpMap{IpAddr: ip, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
ipStr := farIp.IpAddr
|
||||
ip := net.ParseIP(ipStr)
|
||||
mi = &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, Username: username, LastLogin: tNow}
|
||||
// 回写db数据
|
||||
_ = dbdata.Save(mi)
|
||||
_ = dbdata.Add(mi)
|
||||
ipActive[ipStr] = true
|
||||
return ip
|
||||
}
|
||||
@@ -159,9 +144,9 @@ func ReleaseIp(ip net.IP, macAddr string) {
|
||||
|
||||
delete(ipActive, ip.String())
|
||||
mi := &dbdata.IpMap{}
|
||||
err := dbdata.One("IpAddr", ip, mi)
|
||||
err := dbdata.One("ip_addr", ip.String(), mi)
|
||||
if err == nil {
|
||||
mi.LastLogin = time.Now()
|
||||
_ = dbdata.Save(mi)
|
||||
_ = dbdata.Add(mi)
|
||||
}
|
||||
}
|
||||
|
@@ -15,7 +15,8 @@ import (
|
||||
func preData(tmpDir string) {
|
||||
base.Test()
|
||||
tmpDb := path.Join(tmpDir, "test.db")
|
||||
base.Cfg.DbFile = tmpDb
|
||||
base.Cfg.DbType = "sqlite3"
|
||||
base.Cfg.DbSource = tmpDb
|
||||
base.Cfg.Ipv4CIDR = "192.168.3.0/24"
|
||||
base.Cfg.Ipv4Start = "192.168.3.1"
|
||||
base.Cfg.Ipv4End = "192.168.3.199"
|
||||
@@ -27,7 +28,7 @@ func preData(tmpDir string) {
|
||||
Name: "group1",
|
||||
Bandwidth: 1000,
|
||||
}
|
||||
_ = dbdata.Save(&group)
|
||||
_ = dbdata.Add(&group)
|
||||
initIpPool()
|
||||
}
|
||||
|
||||
|
@@ -54,13 +54,13 @@ func OnlineSess() []Online {
|
||||
Group: v.Group,
|
||||
MacAddr: v.MacAddr,
|
||||
RemoteAddr: v.CSess.RemoteAddr,
|
||||
TunName: v.CSess.TunName,
|
||||
TunName: v.CSess.IfName,
|
||||
Mtu: v.CSess.Mtu,
|
||||
Client: v.CSess.Client,
|
||||
BandwidthUp: utils.HumanByte(atomic.LoadUint32(&v.CSess.BandwidthUpPeriod)) + "/s",
|
||||
BandwidthDown: utils.HumanByte(atomic.LoadUint32(&v.CSess.BandwidthDownPeriod)) + "/s",
|
||||
BandwidthUpAll: utils.HumanByte(atomic.LoadUint32(&v.CSess.BandwidthUpAll)),
|
||||
BandwidthDownAll: utils.HumanByte(atomic.LoadUint32(&v.CSess.BandwidthDownAll)),
|
||||
BandwidthUpAll: utils.HumanByte(atomic.LoadUint64(&v.CSess.BandwidthUpAll)),
|
||||
BandwidthDownAll: utils.HumanByte(atomic.LoadUint64(&v.CSess.BandwidthDownAll)),
|
||||
LastLogin: v.LastLogin,
|
||||
}
|
||||
datas = append(datas, val)
|
||||
|
@@ -8,13 +8,13 @@ const (
|
||||
)
|
||||
|
||||
type Payload struct {
|
||||
PType byte // payload types
|
||||
LType LType // LinkType
|
||||
PType byte // payload types
|
||||
Data []byte
|
||||
}
|
||||
|
||||
/*
|
||||
var header = []byte{'S', 'T', 'F', 0x01, 0, 0, 0x00, 0}
|
||||
var header = []byte{'S', 'T', 'F', 0x01, 0, 0, 0x07, 0}
|
||||
https://tools.ietf.org/html/draft-mavrogiannopoulos-openconnect-02#section-2.2
|
||||
|
||||
+---------------------+---------------------------------------------+
|
||||
|
@@ -32,7 +32,7 @@ type ConnSession struct {
|
||||
MacHw net.HardwareAddr // 客户端mac地址,从Session取出
|
||||
RemoteAddr string
|
||||
Mtu int
|
||||
TunName string
|
||||
IfName string
|
||||
Client string // 客户端 mobile pc
|
||||
CstpDpd int
|
||||
Group *dbdata.Group
|
||||
@@ -41,21 +41,21 @@ type ConnSession struct {
|
||||
BandwidthDown uint32 // 使用下行带宽 Byte
|
||||
BandwidthUpPeriod uint32 // 前一周期的总量
|
||||
BandwidthDownPeriod uint32
|
||||
BandwidthUpAll uint32 // 使用上行带宽总量
|
||||
BandwidthDownAll uint32 // 使用下行带宽总量
|
||||
BandwidthUpAll uint64 // 使用上行带宽总量
|
||||
BandwidthDownAll uint64 // 使用下行带宽总量
|
||||
closeOnce sync.Once
|
||||
CloseChan chan struct{}
|
||||
PayloadIn chan *Payload
|
||||
// PayloadOut chan *Payload // 公共ip数据
|
||||
PayloadOutCstp chan *Payload // Cstp的数据
|
||||
PayloadOutDtls chan *Payload // Dtls的数据
|
||||
PayloadOutCstp chan *Payload // Cstp的数据
|
||||
PayloadOutDtls chan *Payload // Dtls的数据
|
||||
IpAuditMap map[string]int64 // 审计的ip数据
|
||||
|
||||
// dSess *DtlsSession
|
||||
dSess *atomic.Value
|
||||
}
|
||||
|
||||
type DtlsSession struct {
|
||||
isActive int32
|
||||
isActive int32
|
||||
CloseChan chan struct{}
|
||||
closeOnce sync.Once
|
||||
IpAddr net.IP
|
||||
@@ -111,9 +111,9 @@ func checkSession() {
|
||||
|
||||
func GenToken() string {
|
||||
// 生成32位的 token
|
||||
btoken := make([]byte, 32)
|
||||
rand.Read(btoken)
|
||||
return fmt.Sprintf("%x", btoken)
|
||||
bToken := make([]byte, 32)
|
||||
rand.Read(bToken)
|
||||
return fmt.Sprintf("%x", bToken)
|
||||
}
|
||||
|
||||
func NewSession(token string) *Session {
|
||||
@@ -183,12 +183,17 @@ func (s *Session) NewConn() *ConnSession {
|
||||
IpAddr: ip,
|
||||
closeOnce: sync.Once{},
|
||||
CloseChan: make(chan struct{}),
|
||||
PayloadIn: make(chan *Payload),
|
||||
PayloadOutCstp: make(chan *Payload),
|
||||
PayloadOutDtls: make(chan *Payload),
|
||||
PayloadIn: make(chan *Payload, 64),
|
||||
PayloadOutCstp: make(chan *Payload, 64),
|
||||
PayloadOutDtls: make(chan *Payload, 64),
|
||||
dSess: &atomic.Value{},
|
||||
}
|
||||
|
||||
// ip 审计
|
||||
if base.Cfg.AuditInterval >= 0 {
|
||||
cSess.IpAuditMap = make(map[string]int64, 512)
|
||||
}
|
||||
|
||||
dSess := &DtlsSession{
|
||||
isActive: -1,
|
||||
}
|
||||
@@ -236,7 +241,7 @@ func (cs *ConnSession) NewDtlsConn() *DtlsSession {
|
||||
}
|
||||
|
||||
dSess := &DtlsSession{
|
||||
isActive: 1,
|
||||
isActive: 1,
|
||||
CloseChan: make(chan struct{}),
|
||||
closeOnce: sync.Once{},
|
||||
IpAddr: cs.IpAddr,
|
||||
@@ -284,14 +289,17 @@ func (cs *ConnSession) ratePeriod() {
|
||||
atomic.SwapUint32(&cs.BandwidthUpPeriod, rtUp/BandwidthPeriodSec)
|
||||
atomic.SwapUint32(&cs.BandwidthDownPeriod, rtDown/BandwidthPeriodSec)
|
||||
// 累加所有流量
|
||||
atomic.AddUint32(&cs.BandwidthUpAll, rtUp)
|
||||
atomic.AddUint32(&cs.BandwidthDownAll, rtDown)
|
||||
atomic.AddUint64(&cs.BandwidthUpAll, uint64(rtUp))
|
||||
atomic.AddUint64(&cs.BandwidthDownAll, uint64(rtDown))
|
||||
}
|
||||
}
|
||||
|
||||
const MaxMtu = 1460
|
||||
var MaxMtu = 1460
|
||||
|
||||
func (cs *ConnSession) SetMtu(mtu string) {
|
||||
if base.Cfg.Mtu > 0 {
|
||||
MaxMtu = base.Cfg.Mtu
|
||||
}
|
||||
cs.Mtu = MaxMtu
|
||||
|
||||
mi, err := strconv.Atoi(mtu)
|
||||
@@ -304,10 +312,10 @@ func (cs *ConnSession) SetMtu(mtu string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (cs *ConnSession) SetTunName(name string) {
|
||||
func (cs *ConnSession) SetIfName(name string) {
|
||||
cs.Sess.mux.Lock()
|
||||
defer cs.Sess.mux.Unlock()
|
||||
cs.TunName = name
|
||||
cs.IfName = name
|
||||
}
|
||||
|
||||
func (cs *ConnSession) RateLimit(byt int, isUp bool) error {
|
||||
|
@@ -1,13 +1,15 @@
|
||||
[Unit]
|
||||
Description=VPN Server Service
|
||||
After=network.target
|
||||
Description=AnyLink Server Service
|
||||
Documentation=https://github.com/bjdgyc/anylink
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory= /usr/local/anylink-deploy
|
||||
WorkingDirectory=/usr/local/anylink-deploy
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
ExecStart=/usr/local/anylink-deploy/anylink --conf=conf/server.toml
|
||||
ExecStart=/usr/local/anylink-deploy/anylink --conf=/usr/local/anylink-deploy/conf/server.toml
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
@@ -1,3 +0,0 @@
|
||||
> 1%
|
||||
last 2 versions
|
||||
not dead
|
26204
web/package-lock.json
generated
@@ -8,13 +8,13 @@
|
||||
"lint": "vue-cli-service lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.20.0",
|
||||
"axios": "^0.21.1",
|
||||
"core-js": "^3.6.5",
|
||||
"echarts": "^4.9.0",
|
||||
"element-ui": "^2.4.5",
|
||||
"vue": "^2.6.11",
|
||||
"vue-count-to": "^1.0.13",
|
||||
"vue-router": "^3.4.6"
|
||||
"vue-router": "^3.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vue/cli-plugin-babel": "~4.5.0",
|
||||
@@ -25,5 +25,24 @@
|
||||
"eslint-plugin-vue": "^6.2.2",
|
||||
"vue-cli-plugin-element": "~1.0.1",
|
||||
"vue-template-compiler": "^2.6.11"
|
||||
}
|
||||
},
|
||||
"eslintConfig": {
|
||||
"root": true,
|
||||
"env": {
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"plugin:vue/essential",
|
||||
"eslint:recommended"
|
||||
],
|
||||
"parserOptions": {
|
||||
"parser": "babel-eslint"
|
||||
},
|
||||
"rules": {}
|
||||
},
|
||||
"browserslist": [
|
||||
"> 1%",
|
||||
"last 2 versions",
|
||||
"not dead"
|
||||
]
|
||||
}
|
||||
|
@@ -32,6 +32,7 @@
|
||||
<el-menu-item index="/admin/set/system">系统信息</el-menu-item>
|
||||
<el-menu-item index="/admin/set/soft">软件配置</el-menu-item>
|
||||
<el-menu-item index="/admin/set/other">其他设置</el-menu-item>
|
||||
<el-menu-item index="/admin/set/audit">审计日志</el-menu-item>
|
||||
</el-submenu>
|
||||
|
||||
<el-submenu index="2">
|
||||
@@ -41,6 +42,7 @@
|
||||
</template>
|
||||
|
||||
<el-menu-item index="/admin/user/list">用户列表</el-menu-item>
|
||||
<el-menu-item index="/admin/user/policy">用户策略</el-menu-item>
|
||||
<el-menu-item index="/admin/user/online">在线用户</el-menu-item>
|
||||
<el-menu-item index="/admin/user/ip_map">IP映射</el-menu-item>
|
||||
</el-submenu>
|
||||
|
@@ -1,7 +1,6 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-card>
|
||||
|
||||
<el-form :inline="true">
|
||||
<el-form-item>
|
||||
<el-button
|
||||
@@ -65,7 +64,13 @@
|
||||
label="路由包含"
|
||||
width="200">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.route_include" :key="inx">{{ item.val }}</el-row>
|
||||
<el-row v-for="(item,inx) in scope.row.route_include.slice(0, readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
<div v-if="scope.row.route_include.length > readMinRows">
|
||||
<div v-if="readMore[`ri_${ scope.row.id }`]">
|
||||
<el-row v-for="(item,inx) in scope.row.route_include.slice(readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
</div>
|
||||
<el-button size="mini" type="text" @click="toggleMore(`ri_${ scope.row.id }`)">{{ readMore[`ri_${ scope.row.id }`] ? "▲ 收起" : "▼ 更多" }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
@@ -74,7 +79,13 @@
|
||||
label="路由排除"
|
||||
width="200">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.route_exclude" :key="inx">{{ item.val }}</el-row>
|
||||
<el-row v-for="(item,inx) in scope.row.route_exclude.slice(0, readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
<div v-if="scope.row.route_exclude.length > readMinRows">
|
||||
<div v-if="readMore[`re_${ scope.row.id }`]">
|
||||
<el-row v-for="(item,inx) in scope.row.route_exclude.slice(readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
</div>
|
||||
<el-button size="mini" type="text" @click="toggleMore(`re_${ scope.row.id }`)">{{ readMore[`re_${ scope.row.id }`] ? "▲ 收起" : "▼ 更多" }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
@@ -83,9 +94,17 @@
|
||||
label="LINK-ACL"
|
||||
min-width="200">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.link_acl" :key="inx">
|
||||
<el-row v-for="(item,inx) in scope.row.link_acl.slice(0, readMinRows)" :key="inx">
|
||||
{{ item.action }} => {{ item.val }} : {{ item.port }}
|
||||
</el-row>
|
||||
<div v-if="scope.row.link_acl.length > readMinRows">
|
||||
<div v-if="readMore[`la_${ scope.row.id }`]">
|
||||
<el-row v-for="(item,inx) in scope.row.link_acl.slice(readMinRows)" :key="inx">
|
||||
{{ item.action }} => {{ item.val }} : {{ item.port }}
|
||||
</el-row>
|
||||
</div>
|
||||
<el-button size="mini" type="text" @click="toggleMore(`la_${ scope.row.id }`)">{{ readMore[`la_${ scope.row.id }`] ? "▲ 收起" : "▼ 更多" }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
@@ -118,8 +137,8 @@
|
||||
|
||||
<el-popconfirm
|
||||
style="margin-left: 10px"
|
||||
@onConfirm="handleDel(scope.row)"
|
||||
title="确定要删除用户吗?">
|
||||
@confirm="handleDel(scope.row)"
|
||||
title="确定要删除用户组吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
size="mini"
|
||||
@@ -152,135 +171,175 @@
|
||||
center>
|
||||
|
||||
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="ruleForm">
|
||||
<el-form-item label="用户组ID" prop="id">
|
||||
<el-input v-model="ruleForm.id" disabled></el-input>
|
||||
</el-form-item>
|
||||
<el-tabs v-model="activeTab">
|
||||
<el-tab-pane label="通用" name="general">
|
||||
<el-form-item label="用户组ID" prop="id">
|
||||
<el-input v-model="ruleForm.id" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="组名" prop="name">
|
||||
<el-input v-model="ruleForm.name" :disabled="ruleForm.id > 0"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="组名" prop="name">
|
||||
<el-input v-model="ruleForm.name" :disabled="ruleForm.id > 0"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="备注" prop="note">
|
||||
<el-input v-model="ruleForm.note"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注" prop="note">
|
||||
<el-input v-model="ruleForm.note"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="带宽限制" prop="bandwidth">
|
||||
<el-input v-model.number="ruleForm.bandwidth">
|
||||
<template slot="append">BYTE</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="本地网络" prop="allow_lan">
|
||||
<el-switch
|
||||
v-model="ruleForm.allow_lan">
|
||||
</el-switch>
|
||||
</el-form-item>
|
||||
<el-form-item label="带宽限制" prop="bandwidth">
|
||||
<el-input v-model.number="ruleForm.bandwidth">
|
||||
<template slot="append">BYTE/S</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="本地网络" prop="allow_lan">
|
||||
<el-switch
|
||||
v-model="ruleForm.allow_lan">
|
||||
</el-switch>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="客户端DNS" prop="client_dns">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入IP格式如: 192.168.0.10</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.client_dns)"></el-button>
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.client_dns)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.client_dns"
|
||||
:key="index" style="margin-bottom: 5px" gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="14">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-form-item label="客户端DNS" prop="client_dns">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入IP格式如: 192.168.0.10</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.client_dns)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.client_dns"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.client_dns,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-radio-group v-model="ruleForm.status">
|
||||
<el-radio :label="1" border>启用</el-radio>
|
||||
<el-radio :label="0" border>停用</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-form-item label="包含路由" prop="route_include">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.1.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_include)"></el-button>
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_include)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_include"
|
||||
:key="index" style="margin-bottom: 5px" gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="14">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-tab-pane label="认证方式" name="authtype">
|
||||
<el-form-item label="认证" prop="authtype">
|
||||
<el-radio-group v-model="ruleForm.auth.type">
|
||||
<el-radio label="local" border>本地</el-radio>
|
||||
<el-radio label="radius" border>Radius</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="Radius密钥" v-if="ruleForm.auth.type == 'radius'">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="ruleForm.auth.radius.secret"></el-input>
|
||||
</el-col>
|
||||
</el-form-item>
|
||||
<el-form-item label="Radius服务器" v-if="ruleForm.auth.type == 'radius'">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="ruleForm.auth.radius.addr" placeholder="输入IP和端口 192.168.2.1:1812"></el-input>
|
||||
</el-col>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-form-item label="排除路由" prop="route_exclude">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.2.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_exclude)"></el-button>
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_exclude)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_exclude"
|
||||
:key="index" style="margin-bottom: 5px" gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="14">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-tab-pane label="路由设置" name="route">
|
||||
<el-form-item label="包含路由" prop="route_include">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.1.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_include)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_include"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_include,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="权限控制" prop="link_acl">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.3.0/24 端口0表示所有端口</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.link_acl)"></el-button>
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.link_acl)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-form-item label="排除路由" prop="route_exclude">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.2.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_exclude)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_exclude"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_exclude,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="权限控制" name="link_acl">
|
||||
<el-form-item label="权限控制" prop="link_acl">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.3.0/24 端口0表示所有端口</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.link_acl)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<el-row v-for="(item,index) in ruleForm.link_acl"
|
||||
:key="index" style="margin-bottom: 5px" gutter="5">
|
||||
<el-col :span="11">
|
||||
<el-input placeholder="请输入CIDR地址" v-model="item.val">
|
||||
<el-select v-model="item.action" slot="prepend">
|
||||
<el-option label="允许" value="allow"></el-option>
|
||||
<el-option label="禁止" value="deny"></el-option>
|
||||
</el-select>
|
||||
</el-input>
|
||||
</el-col>
|
||||
<el-col :span="3">
|
||||
<el-input v-model.number="item.port" placeholder="端口"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-row v-for="(item,index) in ruleForm.link_acl"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="5">
|
||||
<el-col :span="11">
|
||||
<el-input placeholder="请输入CIDR地址" v-model="item.val">
|
||||
<el-select v-model="item.action" slot="prepend">
|
||||
<el-option label="允许" value="allow"></el-option>
|
||||
<el-option label="禁止" value="deny"></el-option>
|
||||
</el-select>
|
||||
</el-input>
|
||||
</el-col>
|
||||
<el-col :span="3">
|
||||
<el-input v-model.number="item.port" placeholder="端口"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="8">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.link_acl,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-radio-group v-model="ruleForm.status">
|
||||
<el-radio :label="1" border>启用</el-radio>
|
||||
<el-radio :label="0" border>停用</el-radio>
|
||||
</el-radio-group>
|
||||
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
|
||||
<el-button @click="disVisible">取消</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-tab-pane label="域名拆分隧道" name="ds_domains">
|
||||
<el-form-item label="包含域名" prop="ds_include_domains">
|
||||
<el-input type="textarea" :rows="5" v-model="ruleForm.ds_include_domains" placeholder="输入域名用,号分隔,默认匹配所有子域名, 如baidu.com,163.com"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="排除域名" prop="ds_exclude_domains">
|
||||
<el-input type="textarea" :rows="5" v-model="ruleForm.ds_exclude_domains" placeholder="输入域名用,号分隔,默认匹配所有子域名, 如baidu.com,163.com"></el-input>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
|
||||
<el-button @click="disVisible">取消</el-button>
|
||||
</el-form-item>
|
||||
</el-tabs>
|
||||
</el-form>
|
||||
</el-dialog>
|
||||
|
||||
</div>
|
||||
@@ -298,37 +357,36 @@ export default {
|
||||
this.$emit('update:route_name', ['用户组信息', '用户组列表'])
|
||||
},
|
||||
mounted() {
|
||||
this.getData(1)
|
||||
this.getData(1);
|
||||
this.setAuthData();
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
page: 1,
|
||||
tableData: [],
|
||||
count: 10,
|
||||
|
||||
activeTab : "general",
|
||||
readMore: {},
|
||||
readMinRows : 5,
|
||||
ruleForm: {
|
||||
bandwidth: 0,
|
||||
status: 1,
|
||||
allow_lan: true,
|
||||
client_dns: [{val: '114.114.114.114'}],
|
||||
route_include: [],
|
||||
route_include: [{val: 'all', note: '默认全局代理'}],
|
||||
route_exclude: [],
|
||||
link_acl: [],
|
||||
auth : {"type":'local'}
|
||||
},
|
||||
rules: {
|
||||
name: [
|
||||
{required: true, message: '请输入用户名', trigger: 'blur'},
|
||||
{required: true, message: '请输入组名', trigger: 'blur'},
|
||||
{max: 30, message: '长度小于 30 个字符', trigger: 'blur'}
|
||||
],
|
||||
bandwidth: [
|
||||
{required: true, message: '请输入用户姓名', trigger: 'blur'},
|
||||
{type: 'number', message: '年龄必须为数字值'}
|
||||
{required: true, message: '请输入带宽限制', trigger: 'blur'},
|
||||
{type: 'number', message: '带宽限制必须为数字值'}
|
||||
],
|
||||
email: [
|
||||
{required: true, message: '请输入用户邮箱', trigger: 'blur'},
|
||||
{type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
|
||||
],
|
||||
|
||||
status: [
|
||||
{required: true}
|
||||
],
|
||||
@@ -336,6 +394,14 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
setAuthData(row) {
|
||||
var defAuthData = {"type":'local',
|
||||
"radius":{"addr":"", "secret":""},
|
||||
}
|
||||
if (this.ruleForm.auth.type == "local" || !row) {
|
||||
this.ruleForm.auth = defAuthData;
|
||||
}
|
||||
},
|
||||
handleDel(row) {
|
||||
axios.post('/group/del?id=' + row.id).then(resp => {
|
||||
const rdata = resp.data;
|
||||
@@ -354,17 +420,19 @@ export default {
|
||||
handleEdit(row) {
|
||||
!this.$refs['ruleForm'] || this.$refs['ruleForm'].resetFields();
|
||||
console.log(row)
|
||||
this.activeTab = "general"
|
||||
this.user_edit_dialog = true
|
||||
if (!row) {
|
||||
this.setAuthData(row)
|
||||
return;
|
||||
}
|
||||
|
||||
axios.get('/group/detail', {
|
||||
params: {
|
||||
id: row.id,
|
||||
}
|
||||
}).then(resp => {
|
||||
this.ruleForm = resp.data.data
|
||||
this.ruleForm = resp.data.data;
|
||||
this.setAuthData(resp.data.data);
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
@@ -389,13 +457,16 @@ export default {
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
removeDomain(arr, item) {
|
||||
console.log(item)
|
||||
removeDomain(arr, index) {
|
||||
console.log(index)
|
||||
if (index >= 0 && index < arr.length) {
|
||||
arr.splice(index, 1)
|
||||
}
|
||||
// let index = arr.indexOf(item);
|
||||
// if (index !== -1 && arr.length > 1) {
|
||||
// arr.splice(index, 1)
|
||||
// }
|
||||
arr.pop()
|
||||
// arr.pop()
|
||||
},
|
||||
addDomain(arr) {
|
||||
arr.push({val: "", action: "allow", port: 0});
|
||||
@@ -406,12 +477,12 @@ export default {
|
||||
console.log('error submit!!');
|
||||
return false;
|
||||
}
|
||||
|
||||
axios.post('/group/set', this.ruleForm).then(resp => {
|
||||
const rdata = resp.data;
|
||||
if (rdata.code === 0) {
|
||||
this.$message.success(rdata.msg);
|
||||
this.getData(1);
|
||||
this.user_edit_dialog = false
|
||||
} else {
|
||||
this.$message.error(rdata.msg);
|
||||
}
|
||||
@@ -424,9 +495,15 @@ export default {
|
||||
},
|
||||
resetForm(formName) {
|
||||
this.$refs[formName].resetFields();
|
||||
}
|
||||
},
|
||||
toggleMore(id) {
|
||||
if (this.readMore[id]) {
|
||||
this.$set(this.readMore, id, false);
|
||||
} else {
|
||||
this.$set(this.readMore, id, true);
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
|
145
web/src/pages/set/Audit.vue
Normal file
@@ -0,0 +1,145 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-card>
|
||||
|
||||
<el-table
|
||||
ref="multipleTable"
|
||||
:data="tableData"
|
||||
border>
|
||||
|
||||
<el-table-column
|
||||
sortable="true"
|
||||
prop="id"
|
||||
label="ID"
|
||||
width="60">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="username"
|
||||
label="用户名">
|
||||
</el-table-column>
|
||||
|
||||
|
||||
<el-table-column
|
||||
prop="protocol"
|
||||
label="协议">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="src"
|
||||
label="源IP地址">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="dst"
|
||||
label="目的IP地址">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="dst_port"
|
||||
label="目的端口">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="created_at"
|
||||
label="创建时间"
|
||||
:formatter="tableDateFormat">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
label="操作"
|
||||
width="150">
|
||||
<template slot-scope="scope">
|
||||
<el-popconfirm
|
||||
class="m-left-10"
|
||||
@confirm="handleDel(scope.row)"
|
||||
title="确定要删除审计日志吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
size="mini"
|
||||
type="danger">删除
|
||||
</el-button>
|
||||
</el-popconfirm>
|
||||
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="sh-20"></div>
|
||||
|
||||
<el-pagination
|
||||
background
|
||||
layout="prev, pager, next"
|
||||
:pager-count="11"
|
||||
@current-change="pageChange"
|
||||
:total="count">
|
||||
</el-pagination>
|
||||
|
||||
</el-card>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import axios from "axios";
|
||||
|
||||
export default {
|
||||
name: "Audit",
|
||||
components: {},
|
||||
mixins: [],
|
||||
created() {
|
||||
this.$emit('update:route_path', this.$route.path)
|
||||
this.$emit('update:route_name', ['基础信息', 'IP审计'])
|
||||
},
|
||||
mounted() {
|
||||
this.getData(1)
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
tableData: [],
|
||||
count: 10,
|
||||
nowIndex: 0,
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
getData(p) {
|
||||
axios.get('/set/audit/list', {
|
||||
params: {
|
||||
page: p,
|
||||
}
|
||||
}).then(resp => {
|
||||
var data = resp.data.data
|
||||
console.log(data);
|
||||
this.tableData = data.datas;
|
||||
this.count = data.count
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
pageChange(p) {
|
||||
this.getData(p)
|
||||
},
|
||||
|
||||
handleDel(row) {
|
||||
axios.post('/set/audit/del?id=' + row.id).then(resp => {
|
||||
var rdata = resp.data
|
||||
if (rdata.code === 0) {
|
||||
this.$message.success(rdata.msg);
|
||||
this.getData(1);
|
||||
} else {
|
||||
this.$message.error(rdata.msg);
|
||||
}
|
||||
console.log(rdata);
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
@@ -15,8 +15,12 @@
|
||||
<el-form-item label="密码" prop="password">
|
||||
<el-input v-model="dataSmtp.password"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="启用SSL" prop="use_ssl">
|
||||
<el-switch v-model="dataSmtp.use_ssl"></el-switch>
|
||||
<el-form-item label="加密类型" prop="encryption">
|
||||
<el-radio-group v-model="dataSmtp.encryption">
|
||||
<el-radio label="None">None</el-radio>
|
||||
<el-radio label="SSLTLS">SSLTLS</el-radio>
|
||||
<el-radio label="STARTTLS">STARTTLS</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="邮件from" prop="from">
|
||||
<el-input v-model="dataSmtp.from"></el-input>
|
||||
|
@@ -46,8 +46,9 @@
|
||||
|
||||
<el-card v-if="system.sys" style="margin-top: 10px">
|
||||
<div slot="header">
|
||||
<span>go运行环境</span>
|
||||
<span>运行环境</span>
|
||||
</div>
|
||||
<Cell left="软件版本" :right="system.sys.appVersion" divider/>
|
||||
<Cell left="GO版本" :right="system.sys.goOs" divider/>
|
||||
<Cell left="GoArch" :right="system.sys.goArch" divider/>
|
||||
<Cell left="GoVersion" :right="system.sys.goVersion" divider/>
|
||||
|
@@ -76,13 +76,12 @@
|
||||
|
||||
<el-popconfirm
|
||||
class="m-left-10"
|
||||
@onConfirm="handleDel(scope.row)"
|
||||
@confirm="handleDel(scope.row)"
|
||||
title="确定要删除IP映射吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
size="mini"
|
||||
type="danger"
|
||||
@click="handleDelete(scope.row)">删除
|
||||
type="danger">删除
|
||||
</el-button>
|
||||
</el-popconfirm>
|
||||
|
||||
|
@@ -120,7 +120,7 @@
|
||||
|
||||
<el-popconfirm
|
||||
class="m-left-10"
|
||||
@onConfirm="handleDel(scope.row)"
|
||||
@confirm="handleDel(scope.row)"
|
||||
title="确定要删除用户吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
@@ -388,6 +388,7 @@ export default {
|
||||
if (data.code === 0) {
|
||||
this.$message.success(data.msg);
|
||||
this.getData(1);
|
||||
this.user_edit_dialog = false
|
||||
} else {
|
||||
this.$message.error(data.msg);
|
||||
}
|
||||
|
@@ -95,7 +95,7 @@
|
||||
|
||||
<el-popconfirm
|
||||
class="m-left-10"
|
||||
@onConfirm="handleOffline(scope.row)"
|
||||
@confirm="handleOffline(scope.row)"
|
||||
title="确定要下线用户吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
|
421
web/src/pages/user/Policy.vue
Normal file
@@ -0,0 +1,421 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-card>
|
||||
<el-form :inline="true">
|
||||
<el-form-item>
|
||||
<el-button
|
||||
size="small"
|
||||
type="primary"
|
||||
icon="el-icon-plus"
|
||||
@click="handleEdit('')">添加
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-table
|
||||
ref="multipleTable"
|
||||
:data="tableData"
|
||||
border>
|
||||
|
||||
<el-table-column
|
||||
sortable="true"
|
||||
prop="id"
|
||||
label="ID"
|
||||
width="60">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="username"
|
||||
label="用户名">
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="allow_lan"
|
||||
label="本地网络">
|
||||
<template slot-scope="scope">
|
||||
<el-switch
|
||||
v-model="scope.row.allow_lan"
|
||||
disabled>
|
||||
</el-switch>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="client_dns"
|
||||
label="客户端DNS"
|
||||
width="160">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.client_dns" :key="inx">{{ item.val }}</el-row>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="route_include"
|
||||
label="路由包含"
|
||||
width="200">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.route_include.slice(0, readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
<div v-if="scope.row.route_include.length > readMinRows">
|
||||
<div v-if="readMore[`ri_${ scope.row.id }`]">
|
||||
<el-row v-for="(item,inx) in scope.row.route_include.slice(readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
</div>
|
||||
<el-button size="mini" type="text" @click="toggleMore(`ri_${ scope.row.id }`)">{{ readMore[`ri_${ scope.row.id }`] ? "▲ 收起" : "▼ 更多" }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="route_exclude"
|
||||
label="路由排除"
|
||||
width="200">
|
||||
<template slot-scope="scope">
|
||||
<el-row v-for="(item,inx) in scope.row.route_exclude.slice(0, readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
<div v-if="scope.row.route_exclude.length > readMinRows">
|
||||
<div v-if="readMore[`re_${ scope.row.id }`]">
|
||||
<el-row v-for="(item,inx) in scope.row.route_exclude.slice(readMinRows)" :key="inx">{{ item.val }}</el-row>
|
||||
</div>
|
||||
<el-button size="mini" type="text" @click="toggleMore(`re_${ scope.row.id }`)">{{ readMore[`re_${ scope.row.id }`] ? "▲ 收起" : "▼ 更多" }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="status"
|
||||
label="状态"
|
||||
width="70">
|
||||
<template slot-scope="scope">
|
||||
<el-tag v-if="scope.row.status === 1" type="success">可用</el-tag>
|
||||
<el-tag v-else type="danger">停用</el-tag>
|
||||
</template>
|
||||
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
prop="updated_at"
|
||||
label="更新时间"
|
||||
:formatter="tableDateFormat">
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column
|
||||
label="操作"
|
||||
width="150">
|
||||
<template slot-scope="scope">
|
||||
<el-button
|
||||
size="mini"
|
||||
type="primary"
|
||||
@click="handleEdit(scope.row)">编辑
|
||||
</el-button>
|
||||
|
||||
<el-popconfirm
|
||||
style="margin-left: 10px"
|
||||
@confirm="handleDel(scope.row)"
|
||||
title="确定要删除用户策略项吗?">
|
||||
<el-button
|
||||
slot="reference"
|
||||
size="mini"
|
||||
type="danger">删除
|
||||
</el-button>
|
||||
</el-popconfirm>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-pagination
|
||||
background
|
||||
layout="prev, pager, next"
|
||||
:pager-count="11"
|
||||
@current-change="pageChange"
|
||||
:current-page="page"
|
||||
:total="count">
|
||||
</el-pagination>
|
||||
|
||||
</el-card>
|
||||
|
||||
<!--新增、修改弹出框-->
|
||||
<el-dialog
|
||||
:close-on-click-modal="false"
|
||||
title="用户策略"
|
||||
:visible.sync="user_edit_dialog"
|
||||
width="750px"
|
||||
top="50px"
|
||||
center>
|
||||
|
||||
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="ruleForm">
|
||||
<el-tabs v-model="activeTab">
|
||||
<el-tab-pane label="通用" name="general">
|
||||
<el-form-item label="ID" prop="id">
|
||||
<el-input v-model="ruleForm.id" disabled></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="用户名" prop="username">
|
||||
<el-input v-model="ruleForm.username" :disabled="ruleForm.id > 0"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="本地网络" prop="allow_lan">
|
||||
<el-switch
|
||||
v-model="ruleForm.allow_lan">
|
||||
</el-switch>
|
||||
</el-form-item>
|
||||
<el-form-item label="客户端DNS" prop="client_dns">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入IP格式如: 192.168.0.10</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.client_dns)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.client_dns"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.client_dns,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-radio-group v-model="ruleForm.status">
|
||||
<el-radio :label="1" border>启用</el-radio>
|
||||
<el-radio :label="0" border>停用</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="路由设置" name="route">
|
||||
<el-form-item label="包含路由" prop="route_include">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.1.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_include)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_include"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_include,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="排除路由" prop="route_exclude">
|
||||
<el-row class="msg-info">
|
||||
<el-col :span="20">输入CIDR格式如: 192.168.2.0/24</el-col>
|
||||
<el-col :span="4">
|
||||
<el-button size="mini" type="success" icon="el-icon-plus" circle
|
||||
@click.prevent="addDomain(ruleForm.route_exclude)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-row v-for="(item,index) in ruleForm.route_exclude"
|
||||
:key="index" style="margin-bottom: 5px" :gutter="10">
|
||||
<el-col :span="10">
|
||||
<el-input v-model="item.val"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="12">
|
||||
<el-input v-model="item.note" placeholder="备注"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="2">
|
||||
<el-button size="mini" type="danger" icon="el-icon-minus" circle
|
||||
@click.prevent="removeDomain(ruleForm.route_exclude,index)"></el-button>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="动态拆分隧道" name="ds_domains">
|
||||
<el-form-item label="包含域名" prop="ds_include_domains">
|
||||
<el-input type="textarea" :rows="5" v-model="ruleForm.ds_include_domains"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="排除域名" prop="ds_exclude_domains">
|
||||
<el-input type="textarea" :rows="5" v-model="ruleForm.ds_exclude_domains"></el-input>
|
||||
</el-form-item>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
|
||||
<el-button @click="disVisible">取消</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-dialog>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import axios from "axios";
|
||||
|
||||
export default {
|
||||
name: "Policy",
|
||||
components: {},
|
||||
mixins: [],
|
||||
created() {
|
||||
this.$emit('update:route_path', this.$route.path)
|
||||
this.$emit('update:route_name', ['用户信息', '用户策略'])
|
||||
},
|
||||
mounted() {
|
||||
this.getData(1)
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
page: 1,
|
||||
tableData: [],
|
||||
count: 10,
|
||||
activeTab : "general",
|
||||
readMore: {},
|
||||
readMinRows : 5,
|
||||
ruleForm: {
|
||||
bandwidth: 0,
|
||||
status: 1,
|
||||
allow_lan: true,
|
||||
client_dns: [{val: '114.114.114.114'}],
|
||||
route_include: [{val: 'all', note: '默认全局代理'}],
|
||||
route_exclude: [],
|
||||
re_upper_limit : 0,
|
||||
},
|
||||
rules: {
|
||||
name: [
|
||||
{required: true, message: '请输入用户名', trigger: 'blur'},
|
||||
{max: 30, message: '长度小于 30 个字符', trigger: 'blur'}
|
||||
],
|
||||
bandwidth: [
|
||||
{required: true, message: '请输入带宽限制', trigger: 'blur'},
|
||||
{type: 'number', message: '带宽必须为数字值'}
|
||||
],
|
||||
status: [
|
||||
{required: true}
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
handleDel(row) {
|
||||
axios.post('/user/policy/del?id=' + row.id).then(resp => {
|
||||
const rdata = resp.data;
|
||||
if (rdata.code === 0) {
|
||||
this.$message.success(rdata.msg);
|
||||
this.getData(1);
|
||||
} else {
|
||||
this.$message.error(rdata.msg);
|
||||
}
|
||||
console.log(rdata);
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
handleEdit(row) {
|
||||
!this.$refs['ruleForm'] || this.$refs['ruleForm'].resetFields();
|
||||
console.log(row)
|
||||
this.activeTab = "general"
|
||||
this.user_edit_dialog = true
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
axios.get('/user/policy/detail', {
|
||||
params: {
|
||||
id: row.id,
|
||||
}
|
||||
}).then(resp => {
|
||||
this.ruleForm = resp.data.data
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
pageChange(p) {
|
||||
this.getData(p)
|
||||
},
|
||||
getData(page) {
|
||||
this.page = page
|
||||
axios.get('/user/policy/list', {
|
||||
params: {
|
||||
page: page,
|
||||
}
|
||||
}).then(resp => {
|
||||
const rdata = resp.data.data;
|
||||
console.log(rdata);
|
||||
this.tableData = rdata.datas;
|
||||
this.count = rdata.count
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
removeDomain(arr, index) {
|
||||
console.log(index)
|
||||
if (index >= 0 && index < arr.length) {
|
||||
arr.splice(index, 1)
|
||||
}
|
||||
// let index = arr.indexOf(item);
|
||||
// if (index !== -1 && arr.length > 1) {
|
||||
// arr.splice(index, 1)
|
||||
// }
|
||||
// arr.pop()
|
||||
},
|
||||
addDomain(arr) {
|
||||
arr.push({val: "", action: "allow", port: 0});
|
||||
},
|
||||
submitForm(formName) {
|
||||
this.$refs[formName].validate((valid) => {
|
||||
if (!valid) {
|
||||
console.log('error submit!!');
|
||||
return false;
|
||||
}
|
||||
|
||||
axios.post('/user/policy/set', this.ruleForm).then(resp => {
|
||||
const rdata = resp.data;
|
||||
if (rdata.code === 0) {
|
||||
this.$message.success(rdata.msg);
|
||||
this.getData(1);
|
||||
this.user_edit_dialog = false
|
||||
} else {
|
||||
this.$message.error(rdata.msg);
|
||||
}
|
||||
console.log(rdata);
|
||||
}).catch(error => {
|
||||
this.$message.error('哦,请求出错');
|
||||
console.log(error);
|
||||
});
|
||||
});
|
||||
},
|
||||
resetForm(formName) {
|
||||
this.$refs[formName].resetFields();
|
||||
},
|
||||
toggleMore(id) {
|
||||
if (this.readMore[id]) {
|
||||
this.$set(this.readMore, id, false);
|
||||
} else {
|
||||
this.$set(this.readMore, id, true);
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.msg-info {
|
||||
background-color: #f4f4f5;
|
||||
color: #909399;
|
||||
padding: 0 5px;
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.el-select {
|
||||
width: 80px;
|
||||
}
|
||||
</style>
|