diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..02e9ba66 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3 +LABEL maintainer="r4v3zn " version="0.1.0" description="Vulfocus for Docker" +EXPOSE 80 +RUN mkdir /vulfocus-api/ +WORKDIR /vulfocus-api/ +ADD vulfocus-api/ /vulfocus-api/ +ENV VUL_IP="" +RUN mv /etc/apt/sources.list /etc/apt/sources.list.back && \ + cp /vulfocus-api/sources.list /etc/apt/sources.list && \ + apt update && \ + apt install nginx -y && \ + rm -rf /var/www/html/* && \ + cp /vulfocus-api/default /etc/nginx/sites-available/default && \ + cp /vulfocus-api/default /etc/nginx/sites-enabled/default && \ + pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package -r requirements.txt && \ + chmod u+x /vulfocus-api/run.sh +ADD dist/ /var/www/html/ +CMD ["sh", "/vulfocus-api/run.sh"] \ No newline at end of file diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..71bf4ce7 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,168 @@ +## 安装 + +系统为前后端分离项目,`vulfocus-api` 为后端项目、`vulfocus-frontend` 为前端项目。 + +### 快速安装 + +``` +docker pull vulfocus/vulfocus:latest +docker run -d -p 80:80 -v /var/run/docker.sock:/var/run/docker.sock -e VUL_IP=xxx.xxx.xxx.xxx vulfocus/vulfocus +``` + +其中 `-v /var/run/docker.sock:/var/run/docker.sock` 为 docker 交互文件, `-e VUL_IP=xxx.xxx.xxx.xxx` 为 Docker 服务器IP,不能为 127.0.0.1。 + +默认账户密码为 `admin/admin`。 + +![](./imgs/1.png) + +### Vulfocus API + +环境: + +- 语言:python3 +- 数据库:sqlite3 +- 框架:Django +- API:djangorestframework + +安装 Docker: + +[https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/) + +安装依赖: + +``` +pip install -r requirements.txt +``` + +创建数据库: + +``` +python manage.py migrate +``` + +创建管理员用户: + +``` +python manage.py createsuperuser +``` + +靶场配置: + +1. 配置 Docker URL(`vulfocus/settings.py`),默认为:`tcp://127.0.0.1:2375`,修改为 Docker 服务器的 IP。 + +2. 配置 VUL_IP(`vulfocus/settings.py`),修改为 Docker 服务器的 IP。 + +启动 API 后端: + +``` +python manage.py runserver 0.0.0.0:8000 +``` + +#### 部署 + +##### Docker 配置 + +配置 Docker 2375 端口(可根据实际情况进行修改),修改 docker 配置文件,加入以下信息: + +``` +ExecStart=/usr/bin/dockerd -H tcp://127.0.0.1:2375 -H unix://var/run/docker.sock \ +``` + +配置上传文件大小,修改 `nginx.conf` 文件,http 中加入: + +``` +client_max_body_size 2048M; +``` + +其中 2048M(2GB) 为上传文件最大限制,可根据实际进行修改,最小配置为 200M 。 + +##### Linux 部署 + +修改 nginx 配置目录 `sites-enabled` 中 `default` 文件 ,server 节点添加以下代码: + +``` +location /api/ { + proxy_pass http://127.0.0.1:8000/; +} +``` + +##### Windows 部署 + +修改 nginx 配置文件 `nginx.conf` ,server 添加以下代码: + +``` +location /api/ { + proxy_pass http://127.0.0.1:8000/; +} +``` + +##### nginx 参考配置文件 + +以下为 nginx 参考配置文件: + +``` +worker_processes 1; +events { + worker_connections 1024; +} +http { + include mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 65; + client_max_body_size 2048M; + server { + listen 80; + server_name localhost; + location / { + root html; + index index.html index.htm; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + location /api/ { + proxy_pass http://127.0.0.1:8000/; + } + } +} +``` + +### Vulfocus Frontend + +vulfocus 前端项目,通过 Element-ui + VUE 构建。 + +环境: +- UI:Element UI +- 框架:vue +- node:v12.16.2 +- npm:6.14.4 + +#### 部署 + +##### 项目构建 + +安装依赖: + +```shell script +npm install +``` + +构建项目: +``` +npm run build:prod +``` + +将 dist 目录部署至 nginx 中,默认 nginx 静态目录位于 `/var/www/html`。 + +##### 发行版本 + +通过 [https://github.com/fofapro/vulfocus/releases](https://github.com/fofapro/vulfocus/releases) 下载最新发布的版本。 + +#### 开发 + +```shell script +npm run dev +``` + diff --git a/LICENSE b/LICENSE index 261eeb9e..9466347c 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2020] [fofapro and r4v3zn] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 1c0f062c..581deaca 100644 --- a/README.md +++ b/README.md @@ -1 +1,127 @@ -# vulfocus \ No newline at end of file + +

Welcome to Vulfocus 🚀

+ +Vulfocus 是一个漏洞集成平台,将漏洞环境 docker 镜像,放入即可使用,开箱即用。 + +

+ + + + +

+ +在线演示:[http://vulfocus.fofa.so/](http://vulfocus.fofa.so/) + +## 背景 + +现在阶段网络靶场平台是遍地开花,让人看的眼花缭乱,但商业化产品居多,还有一些类似 dvwa、 sqli-labs这类的开源项目,但是漏洞环境比较固定,使用完一次后就失去其作用。当你需要某个环境的时候,你可能还需要去 https://hub.docker.com/ 官网上找,但每次启动的流程会比较繁琐,因为每个镜像的启动命令可能都不太一样,而且一但环境多了很不好管理,需要启动同一个框架两个不同版本的漏洞环境的时候,就需要修改一些端口、配置文件等等很麻烦,甚至很多场景是不满足的,之前关于漏洞环境镜像使用多的是vulhub,但是作为企业,高校等以及相关的培训,单纯的漏洞环境不一定能满足使用的需求,所以我们基于当下的一些靶场项目做出了小小的改进来符合我们一些需求,比如,增加flag的形式,积分的形式,来满足一些考核与验证的需求,于是 Vulfocus 就诞生了。 + +## 认识 Vulfocus + +因为 Vulfocus 一个漏洞集成平台,所以可以无限向里添加漏洞环境没有限制,前提是你的内存足够大。因为漏洞环境是docker镜像的原因每次重新启动漏洞环境都会还原,不用出现你会对环境造成破坏下次无法启动的现象。 + +Vulfocus 的 docker 仓库 [https://hub.docker.com/u/vulfocus](https://hub.docker.com/u/vulfocus) + +### Vulfocus的特性 + + +1. 启动:一键漏洞环境启动,方便简单。 +2. 自带 Flag 功能:每次启动 flag 都会自动更新,明确漏洞是否利用成功。 +3. 带有计分功能也可适用于相关安全人员能力的考核。 +4. 兼容 [Vulhub](https://vulhub.org/)、[Vulapps](http://vulapps.evalbug.com/) 中所有漏洞镜像。 + + +## ⬇️ 下载及安装 + +🏠 请参考 [INSTALL.md](./INSTALL.md) 进行安装。 + +⬇️ 发行版下载 [https://github.com/fofapro/vulfocus/releases](https://github.com/fofapro/vulfocus/releases)。 + +### ✨ 使用 + +![](./imgs/register&login.gif) + +1. 安装完成后,访问80端口 + +2. 用设置好的管理员账户登录 + +3. 首页为漏洞集成页面,刚开始是没有漏洞镜像的需要从 [https://hub.docker.com/](https://hub.docker.com/) 网站拉取镜像,或自己以tar包的形式上传。 + + 漏洞镜像的拉取和上传(**需管理员权限**): + + (1)、在进行管理中,添加功能 + + ![](./imgs/upload_image_pull.gif) + + ![](./imgs/upload_image_file.gif) + + (2)、分别填入漏洞名称、镜像、rank、描述 + + - 镜像又分为文件和文本 + - 文本:是从 [https://hub.docker.com/u/vulfocus](https://hub.docker.com/u/vulfocus) 官网拉取镜像。内容为如: `vulfocus/webmin-cve_2019_15107` 。 + - 文件:本地漏洞镜像打成tar包的形式进行上传。 + +4. 下载完成后点击启动即可。 + +![](./imgs/tp5_rce.gif) + +5. 镜像启动后,会在环境里写入一个 flag (默认 flag 会写入 **/tmp/** 下),读取到 flag 后填入 flag 窗口,镜像会自动关闭,如需重新启动,需强刷一下,然后再次点击启动即可。 + + +## 🛠贡献漏洞镜像 + +初期 Vulfocus 的漏洞镜像会较少,可能无法满足你的需求,所以非常期望大家来一起维护 Vulfocus,当你发现你的一些漏洞环境在 Vulfocus 中找不到时,可以提交供大家使用。一个有问题的环境可能会影响到使用者的情绪。因此我们对社区提交的漏洞环境会进行审核。贡献者在提交漏洞环境的时候,可提供相应的复现工具或流程,加速环境的审核。 + +### 方式 + +- 提交 dockerfile +- 也可以上传到 [https://hub.docker.com](https://hub.docker.com) ,把镜像的名称提供给我们,镜像名称的命令规则如:框架(CMS、组件)-漏洞编号,例如:`vulfocus/spring-cve_2017_8046` + + +- 例: + vulfocus/webmin-cve_2019_15107 + vulfocus/spring-cve_2017_8046 + +### 流程 + +- fork [vulfocus](https://github.com/fofapro/vulfocus) 至个人项目,然后 clone 项目。 + +- 提交 dockerfile 至 [images](./images/) 文件夹中创建漏洞名称,然后将 dockerfile 放置该目录下,最后将环境信息提交至 [`images/README.md`](./images/README.md)。 +- 贡献者以 PR 的方式向 github Vulfocus 社区仓库内提交 漏洞环境, 提交位置: [https://github.com/fofapro/vulfocus/dockerfile/](https://github.com/fofapro/vulfocus/dockerfile/) +- 我们会根据提供的 dockerfile,确定镜像环境是否可用。 +- 审核完成后镜像会放进 https://hub.docker.com/u/vulfocus 仓库供大家使用。 + +## 📝 讨论区 + +如有问题可以在 GitHub 提 issue, 也可在下方的讨论组里 + +GitHub issue: [https://github.com/fofapro/vulfocus/issues](https://github.com/fofapro/vulfocus/issues) + +微信群: 扫描以下二维码加我的个人微信,会把大家拉到 Vulfocus 官方微信群。 + + + +## 致谢 + +- [Vue Element Admin](https://github.com/PanJiaChen/vue-element-admin) +- [Vulhub](https://vulhub.org/) + +## 声明 + +该项目会收集了当下比较流行的漏洞环境,若有侵权,请联系我们! + +## FAQ + +镜像启动后立即访问地址失败? + +1. 根据镜像的大小,启动时间会有不同的延迟,一般在几秒以内。 + +提交完 flag 后会有卡住? + +1. 在提交完正确flag后,会进行镜像关闭的动作,所以会有几秒的延迟。 + +拉取镜像时一直卡在哪里 + +1. 由于网络延迟或镜像太大的原因时间会长一点。 + +2. 镜像名称填错,也会卡在哪里,建议强刷一下。 \ No newline at end of file diff --git a/images/.DS_Store b/images/.DS_Store new file mode 100644 index 00000000..0add286c Binary files /dev/null and b/images/.DS_Store differ diff --git a/images/README.md b/images/README.md new file mode 100644 index 00000000..15e62e2f --- /dev/null +++ b/images/README.md @@ -0,0 +1,32 @@ +Vulfocus 镜像维护目录,该目录中存储 Vulfocus 所有的 Dockerfile 信息,提交者需在此文件夹中创建漏洞对应的环境目录,然后在此目录中编译 Dockerfile 文件,最后将漏洞镜像信息提交至该文件中。 + + + +| id | 漏洞名称 | 镜像名称 | 描述 | +| :--- | :--------------- | :--------------------------------------------------- | :--------------- | +| 1 | CVE-2020-12409 | `docker pull vulfocus/solr-cve_2020_12409` | CVE-2020-12409 | +| 2 | CVE-2020-7961 | `docker pull vulfocus/liferay-cve_2020_7961` | CVE-2020-7961 | +| 3 | CVE-2020-1938 | `docker pull vulfocus/tomcat-cve_2020_1938` | CVE-2020-1938 | +| 4 | CNVD-2019-22238 | `docker pull vulfocus/fastjson-cnvd_2019_22238` | CNVD-2019-22238 | +| 5 | CVE-2019-17564 | `docker pull vulfocus/dubbo-cve_2019_17564` | CVE-2019-17564 | +| 6 | CVE-2019-15107 | `docker pull vulfocus/webmin-cve_2019_15107` | CVE-2019-15107 | +| 7 | CVE-2019-8942 | `docker pull vulfocus/wordpress-cve_2019_8942` | CVE-2019-8942 | +| 8 | CNVD-2018-24942 | `docker pull vulfocus/thinkphp-cnvd_2018_24942` | CNVD-2018-24942 | +| 9 | CVE-2018_1000861 | `docker pull vulfocus/jenkins-cve2018_1000861` | CVE-2018_1000861 | +| 10 | CVE-2018-7600 | `docker pull vulfocus/drupal-cve_2018_7600` | CVE-2018-7600 | +| 11 | CVE-2017_1000353 | `docker pull vulfocus/jenkins-cve2017_1000353` | CVE-2017_1000353 | +| 12 | CVE-2017-12636 | `docker pull vulfocus/couchdb-cve_2017_12636` | CVE-2017-12636 | +| 13 | CVE-2017-12615 | `docker pull vulfocus/tomcat-cve_2017_12615` | CVE-2017-12615 | +| 14 | CVE-2017-12149 | `docker pull vulfocus/jboss-cve_2017_12149` | CVE-2017-12149 | +| 15 | CVE-2017-9791 | `docker pull vulfocus/struts2-cve_2017_9791` | CVE-2017-9791 | +| 16 | CVE-2017_8046 | `docker pull vulfocus/vulfocus/spring-cve_2017_8046` | CVE-2017_8046 | +| 17 | CVE-2017-7504 | `docker pull vulfocus/jboss-cve_2017_7504` | CVE-2017-7504 | +| 18 | CVE-2017-5941 | `docker pull vulfocus/nodejs-cve_2017_594` | CVE-2017-5941 | +| 19 | CVE-2017-5638 | `docker pull vulfocus/struts2-cve_2017_5638` | CVE-2017-5638 | +| 20 | CVE-2017-3066 | `docker pull vulfocus/coldfision-cve_2017_3066` | CVE-2017-3066 | +| 21 | CNVD-2017-02833 | `docker pull vulfocus/fastjson-cnvd_2017_02833` | CNVD-2017-02833 | +| 22 | CVE-2016-10033 | `docker pull vulfocus/wordpress-cve_2016_10033` | CVE-2016-10033 | +| 23 | CVE-2016-9565 | `docker pull vulfocus/nagios-cve_2016_9565` | CVE-2016-9565 | +| 24 | CVE-2016-4437 | `docker pull vulfocus/shiro-cve_2016_4437` | CVE-2016-4437 | +| 25 | CVE-2014-3120 | `docker pull vulfocus/elasticsearch-cve_2014_3120` | CVE-2014-3120 | + diff --git a/images/Struts-016/Dockerfile b/images/Struts-016/Dockerfile new file mode 100644 index 00000000..b13e5070 --- /dev/null +++ b/images/Struts-016/Dockerfile @@ -0,0 +1,14 @@ +FROM tomcat:8-jre8 +MAINTAINER vulfocus@bmh.com + +ENV WAR_URL https://github.com/sie504/Struts-S2-xxx/raw/master/s2-016.war + +WORKDIR /tmp + +RUN set -ex \ + && rm -rf /usr/local/tomcat/webapps/* \ + && chmod a+x /usr/local/tomcat/bin/*.sh \ + && wget -qO /usr/local/tomcat/webapps/ROOT.war $WAR_URL + +EXPOSE 8080 +CMD ["/usr/local/tomcat/bin/catalina.sh", "run"] \ No newline at end of file diff --git a/imgs/.DS_Store b/imgs/.DS_Store new file mode 100644 index 00000000..5008ddfc Binary files /dev/null and b/imgs/.DS_Store differ diff --git a/imgs/1.png b/imgs/1.png new file mode 100644 index 00000000..31c760df Binary files /dev/null and b/imgs/1.png differ diff --git a/imgs/2.png b/imgs/2.png new file mode 100644 index 00000000..d7c65814 Binary files /dev/null and b/imgs/2.png differ diff --git a/imgs/3.png b/imgs/3.png new file mode 100644 index 00000000..ec18a7fc Binary files /dev/null and b/imgs/3.png differ diff --git a/imgs/4.png b/imgs/4.png new file mode 100644 index 00000000..5ad04f21 Binary files /dev/null and b/imgs/4.png differ diff --git a/imgs/5.png b/imgs/5.png new file mode 100644 index 00000000..2af83f14 Binary files /dev/null and b/imgs/5.png differ diff --git a/imgs/register&login.gif b/imgs/register&login.gif new file mode 100755 index 00000000..b57efa8d Binary files /dev/null and b/imgs/register&login.gif differ diff --git a/imgs/tp5_rce.gif b/imgs/tp5_rce.gif new file mode 100755 index 00000000..d96ad8e6 Binary files /dev/null and b/imgs/tp5_rce.gif differ diff --git a/imgs/upload_image_file.gif b/imgs/upload_image_file.gif new file mode 100755 index 00000000..ebf199bd Binary files /dev/null and b/imgs/upload_image_file.gif differ diff --git a/imgs/upload_image_pull.gif b/imgs/upload_image_pull.gif new file mode 100755 index 00000000..66b15b28 Binary files /dev/null and b/imgs/upload_image_pull.gif differ diff --git a/imgs/wechat.jpeg b/imgs/wechat.jpeg new file mode 100644 index 00000000..fb74207d Binary files /dev/null and b/imgs/wechat.jpeg differ diff --git a/vulfocus-api/.DS_Store b/vulfocus-api/.DS_Store new file mode 100644 index 00000000..9614ae68 Binary files /dev/null and b/vulfocus-api/.DS_Store differ diff --git a/vulfocus-api/.idea/inspectionProfiles/Project_Default.xml b/vulfocus-api/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 00000000..13f873b4 --- /dev/null +++ b/vulfocus-api/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,15 @@ + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/inspectionProfiles/profiles_settings.xml b/vulfocus-api/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 00000000..105ce2da --- /dev/null +++ b/vulfocus-api/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/markdown-navigator-enh.xml b/vulfocus-api/.idea/markdown-navigator-enh.xml new file mode 100644 index 00000000..12fb99d1 --- /dev/null +++ b/vulfocus-api/.idea/markdown-navigator-enh.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/markdown-navigator.xml b/vulfocus-api/.idea/markdown-navigator.xml new file mode 100644 index 00000000..5968eb49 --- /dev/null +++ b/vulfocus-api/.idea/markdown-navigator.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/misc.xml b/vulfocus-api/.idea/misc.xml new file mode 100644 index 00000000..86561143 --- /dev/null +++ b/vulfocus-api/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/modules.xml b/vulfocus-api/.idea/modules.xml new file mode 100644 index 00000000..81184e8a --- /dev/null +++ b/vulfocus-api/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/vcs.xml b/vulfocus-api/.idea/vcs.xml new file mode 100644 index 00000000..6c0b8635 --- /dev/null +++ b/vulfocus-api/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/vulfocus-api.iml b/vulfocus-api/.idea/vulfocus-api.iml new file mode 100644 index 00000000..bac68309 --- /dev/null +++ b/vulfocus-api/.idea/vulfocus-api.iml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vulfocus-api/.idea/workspace.xml b/vulfocus-api/.idea/workspace.xml new file mode 100644 index 00000000..98d24193 --- /dev/null +++ b/vulfocus-api/.idea/workspace.xml @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1586853780665 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vulfocus-api/README.md b/vulfocus-api/README.md new file mode 100644 index 00000000..fea35e97 --- /dev/null +++ b/vulfocus-api/README.md @@ -0,0 +1,114 @@ +# vulfocus API + +环境: + +- 语言:python3 +- 数据库:sqlite3 +- 框架:Django +- API:djangorestframework + +安装 Docker: + +[https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/) + +安装依赖: + +``` +pip install -r requirements.txt +``` + +创建数据库: + +``` +python manage.py migrate +``` + +创建管理员用户: + +``` +python manage.py createsuperuser +``` + +靶场配置: + +1. 配置 Docker URL(`vulfocus/settings.py`),默认为:`tcp://127.0.0.1:2375`,修改为 Docker 服务器的 IP。 + +2. 配置 VUL_IP(`vulfocus/settings.py`),修改为 Docker 服务器的 IP。 + +启动 API 后端: + +``` +python manage.py runserver 0.0.0.0:8000 +``` + +### 部署 + +#### Docker 配置 + +配置 Docker 2375 端口(可根据实际情况进行修改),修改 docker 配置文件,加入以下信息: + +``` +ExecStart=/usr/bin/dockerd -H tcp://127.0.0.1:2375 -H unix://var/run/docker.sock \ +``` + +配置上传文件大小,修改 `nginx.conf` 文件,http 中加入: + +``` +client_max_body_size 4096M; +``` + +其中 2048M(2GB) 为上传文件最大限制,可根据实际进行修改,最小配置为 200M 。 + +#### Linux 部署 + +修改 nginx 配置目录 `sites-enabled` 中 `default` 文件 ,server 节点添加以下代码: + +``` +location /api/ { + proxy_pass http://127.0.0.1:8000/; +} +``` + +#### Windows 部署 + +修改 nginx 配置文件 `nginx.conf` ,server 添加以下代码: + +``` +location /api/ { + proxy_pass http://127.0.0.1:8000/; +} +``` + +#### nginx 参考配置文件 + +以下为 nginx 参考配置文件: + +``` +worker_processes 1; +events { + worker_connections 1024; +} +http { + include mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 65; + client_max_body_size 4096M; + server { + listen 80; + server_name localhost; + location / { + root html; + index index.html index.htm; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + location /api/ { + proxy_pass http://127.0.0.1:8000/; + } + } +} +``` + diff --git a/vulfocus-api/default b/vulfocus-api/default new file mode 100644 index 00000000..a21e34d9 --- /dev/null +++ b/vulfocus-api/default @@ -0,0 +1,95 @@ +## +# You should look at the following URL's in order to grasp a solid understanding +# of Nginx configuration files in order to fully unleash the power of Nginx. +# https://www.nginx.com/resources/wiki/start/ +# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ +# https://wiki.debian.org/Nginx/DirectoryStructure +# +# In most cases, administrators will remove this file from sites-enabled/ and +# leave it as reference inside of sites-available where it will continue to be +# updated by the nginx packaging team. +# +# This file will automatically load configuration files provided by other +# applications, such as Drupal or Wordpress. These applications will be made +# available underneath a path with that package name, such as /drupal8. +# +# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples. +## + +# Default server configuration +# +server { + listen 80 default_server; + listen [::]:80 default_server; + + # SSL configuration + # + # listen 443 ssl default_server; + # listen [::]:443 ssl default_server; + # + # Note: You should disable gzip for SSL traffic. + # See: https://bugs.debian.org/773332 + # + # Read up on ssl_ciphers to ensure a secure configuration. + # See: https://bugs.debian.org/765782 + # + # Self signed certs generated by the ssl-cert package + # Don't use them in a production server! + # + # include snippets/snakeoil.conf; + + root /var/www/html; + + # Add index.php to the list if you are using PHP + index index.html index.htm index.nginx-debian.html; + + server_name _; + + location / { + # First attempt to serve request as file, then + # as directory, then fall back to displaying a 404. + try_files $uri $uri/ =404; + } + + location /api/ { + proxy_pass http://127.0.0.1:8000/; + } + + # pass PHP scripts to FastCGI server + # + #location ~ \.php$ { + # include snippets/fastcgi-php.conf; + # + # # With php-fpm (or other unix sockets): + # fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; + # # With php-cgi (or other tcp sockets): + # fastcgi_pass 127.0.0.1:9000; + #} + + # deny access to .htaccess files, if Apache's document root + # concurs with nginx's one + # + #location ~ /\.ht { + # deny all; + #} +} + + +# Virtual Host configuration for example.com +# +# You can move that to a different file under sites-available/ and symlink that +# to sites-enabled/ to enable it. +# +#server { +# listen 80; +# listen [::]:80; +# +# server_name example.com; +# +# root /var/www/example.com; +# index index.html; +# +# location / { +# try_files $uri $uri/ =404; +# } +#} \ No newline at end of file diff --git a/vulfocus-api/dockerapi/.DS_Store b/vulfocus-api/dockerapi/.DS_Store new file mode 100644 index 00000000..a513abec Binary files /dev/null and b/vulfocus-api/dockerapi/.DS_Store differ diff --git a/vulfocus-api/dockerapi/__init__.py b/vulfocus-api/dockerapi/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/vulfocus-api/dockerapi/admin.py b/vulfocus-api/dockerapi/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/vulfocus-api/dockerapi/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/vulfocus-api/dockerapi/apps.py b/vulfocus-api/dockerapi/apps.py new file mode 100644 index 00000000..21e5e8b4 --- /dev/null +++ b/vulfocus-api/dockerapi/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class DockerapiConfig(AppConfig): + name = 'dockerapi' diff --git a/vulfocus-api/dockerapi/common.py b/vulfocus-api/dockerapi/common.py new file mode 100644 index 00000000..3d568a64 --- /dev/null +++ b/vulfocus-api/dockerapi/common.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Time : 2019/11/28 11:15 PM +# @Author : woo0nise +# @Site : +# @File : common.py +# @Software: PyCharm + +HTTP_OK = 200 +HTTP_ERR = 500 +HTTP_BULD = 201 + + +class R: + + @staticmethod + def ok(data=None, msg='OK'): + return { + "data": data, + "status": HTTP_OK, + "msg": msg + } + + @staticmethod + def err(data=None, msg='服务器内部错误'): + return { + "data": data, + "status": HTTP_ERR, + "msg": msg + } + + @staticmethod + def build(data=None, msg=''): + return { + "data": data, + "status": HTTP_BULD, + "msg": msg + } diff --git a/vulfocus-api/dockerapi/migrations/.DS_Store b/vulfocus-api/dockerapi/migrations/.DS_Store new file mode 100644 index 00000000..38734ca2 Binary files /dev/null and b/vulfocus-api/dockerapi/migrations/.DS_Store differ diff --git a/vulfocus-api/dockerapi/migrations/0001_initial.py b/vulfocus-api/dockerapi/migrations/0001_initial.py new file mode 100644 index 00000000..ab262fef --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0001_initial.py @@ -0,0 +1,64 @@ +# Generated by Django 2.2.5 on 2019-10-29 04:21 + +from django.db import migrations, models +import django.db.models.deletion +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='ImageInfo', + fields=[ + ('image_id', models.UUIDField(default='66b8a169-eb66-45e5-adc2-a50dc2d3b33a', primary_key=True, serialize=False)), + ('image_name', models.CharField(max_length=256, unique=True, verbose_name='Docker镜像名称')), + ('image_vul_name', models.CharField(max_length=256, verbose_name='漏洞名称')), + ('image_port', models.CharField(max_length=256, verbose_name='暴露端口')), + ('image_desc', models.TextField(null=True, verbose_name='镜像描述')), + ('rank', models.FloatField(verbose_name='Rank')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='Docker创建时间,默认为当前时间')), + ('update_date', models.DateTimeField(auto_now=True, verbose_name='Docker更新时间,默认为当前时间')), + ], + options={ + 'db_table': 'image_info', + }, + ), + migrations.CreateModel( + name='TimeMoudel', + fields=[ + ('time_id', models.CharField(default='ac7258ed-b864-4349-b875-9619069c1b00', max_length=255, primary_key=True, serialize=False, verbose_name='ID')), + ('user_id', models.IntegerField(verbose_name='用户ID')), + ('start_time', models.FloatField(verbose_name='开始时间戳')), + ('end_time', models.FloatField(verbose_name='结束时间')), + ], + options={ + 'db_table': 'time_moudel', + }, + ), + migrations.CreateModel( + name='ContainerVul', + fields=[ + ('container_id', models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False, verbose_name='漏洞容器创建ID')), + ('docker_container_id', models.CharField(max_length=255, verbose_name='Docker容器运行进ID')), + ('user_id', models.IntegerField(verbose_name='用户ID')), + ('vul_host', models.CharField(max_length=255, verbose_name='容器漏洞URL')), + ('container_status', models.CharField(max_length=255, verbose_name='容器当前状态')), + ('container_port', models.CharField(max_length=255, verbose_name='容器端口')), + ('container_flag', models.CharField(max_length=255, verbose_name='flag')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='容器创建时间,默认为当前时间')), + ('is_check', models.BooleanField(default=False, verbose_name='Flag是否通过')), + ('is_check_date', models.DateTimeField(null=True, verbose_name='Flag提交时间')), + ('time_model_id', models.CharField(default='', max_length=255, verbose_name='时间模式 ID')), + ('image_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dockerapi.ImageInfo', verbose_name='Docker ID')), + ], + options={ + 'db_table': 'container_vul', + }, + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0002_auto_20191029_1222.py b/vulfocus-api/dockerapi/migrations/0002_auto_20191029_1222.py new file mode 100644 index 00000000..628e149a --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0002_auto_20191029_1222.py @@ -0,0 +1,24 @@ +# Generated by Django 2.2.5 on 2019-10-29 04:22 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='imageinfo', + name='image_id', + field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0003_auto_20191029_1453.py b/vulfocus-api/dockerapi/migrations/0003_auto_20191029_1453.py new file mode 100644 index 00000000..0b41f436 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0003_auto_20191029_1453.py @@ -0,0 +1,34 @@ +# Generated by Django 2.2.5 on 2019-10-29 06:53 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0002_auto_20191029_1222'), + ] + + operations = [ + migrations.AlterField( + model_name='containervul', + name='container_id', + field=models.UUIDField(default=uuid.UUID('da7fb088-fa18-11e9-ba43-8c8590a149dc'), primary_key=True, serialize=False, verbose_name='漏洞容器创建ID'), + ), + migrations.AlterField( + model_name='containervul', + name='time_model_id', + field=models.UUIDField(default='', verbose_name='时间模式 ID'), + ), + migrations.AlterField( + model_name='imageinfo', + name='image_id', + field=models.UUIDField(default=uuid.UUID('da7f9954-fa18-11e9-ba43-8c8590a149dc'), primary_key=True, serialize=False), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.UUIDField(default=uuid.UUID('da7fc8de-fa18-11e9-ba43-8c8590a149dc'), primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0004_auto_20191029_1502.py b/vulfocus-api/dockerapi/migrations/0004_auto_20191029_1502.py new file mode 100644 index 00000000..20ff2255 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0004_auto_20191029_1502.py @@ -0,0 +1,29 @@ +# Generated by Django 2.2.5 on 2019-10-29 07:02 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0003_auto_20191029_1453'), + ] + + operations = [ + migrations.AlterField( + model_name='containervul', + name='container_id', + field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False, verbose_name='漏洞容器创建ID'), + ), + migrations.AlterField( + model_name='imageinfo', + name='image_id', + field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0005_auto_20191029_1518.py b/vulfocus-api/dockerapi/migrations/0005_auto_20191029_1518.py new file mode 100644 index 00000000..94ca1cab --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0005_auto_20191029_1518.py @@ -0,0 +1,34 @@ +# Generated by Django 2.2.5 on 2019-10-29 07:18 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0004_auto_20191029_1502'), + ] + + operations = [ + migrations.AlterField( + model_name='containervul', + name='container_id', + field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='漏洞容器创建ID'), + ), + migrations.AlterField( + model_name='containervul', + name='time_model_id', + field=models.CharField(default='', max_length=255, verbose_name='时间模式 ID'), + ), + migrations.AlterField( + model_name='imageinfo', + name='image_id', + field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='1e5a9d0a-9bc7-4493-9ffb-c91f12bdc9a7', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0006_auto_20191128_2251.py b/vulfocus-api/dockerapi/migrations/0006_auto_20191128_2251.py new file mode 100644 index 00000000..5cad8c5e --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0006_auto_20191128_2251.py @@ -0,0 +1,97 @@ +# Generated by Django 2.2.5 on 2019-11-28 14:51 + +from django.db import migrations, models +import django.db.models.deletion +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0005_auto_20191029_1518'), + ] + + operations = [ + migrations.CreateModel( + name='CombinationImage', + fields=[ + ('combination_image_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='组合镜像ID')), + ('combination_image_name', models.CharField(max_length=255, verbose_name='组合镜像名称')), + ('create_user', models.IntegerField(verbose_name='创建用户ID')), + ('net_work_id', models.CharField(max_length=255, verbose_name='网卡ID')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='开始时间')), + ('update_date', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'db_table': 'combination_image', + }, + ), + migrations.CreateModel( + name='CombinationImageInfo', + fields=[ + ('combination_image_info_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), + ('combination_image_id', models.UUIDField(editable=False, verbose_name='组合镜像ID')), + ('image_id', models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='镜像ID')), + ], + options={ + 'db_table': 'combination_image_info', + }, + ), + migrations.CreateModel( + name='CombinationInfo', + fields=[ + ('combination_info_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), + ('combination_image_id', models.UUIDField(editable=False, verbose_name='组合镜像ID')), + ('user_id', models.IntegerField(verbose_name='创建用户')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('update_date', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'db_table': 'combination_info', + }, + ), + migrations.CreateModel( + name='NetWorkInfo', + fields=[ + ('net_work_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='网卡UUID')), + ('net_work_name', models.CharField(max_length=255, verbose_name='网卡名称')), + ('net_work_subnet', models.CharField(max_length=255, verbose_name='子网')), + ('net_work_gateway', models.CharField(max_length=255, verbose_name='网关')), + ('net_work_scope', models.CharField(default='local', max_length=255, verbose_name='空间')), + ('net_work_driver', models.CharField(default='bridge', max_length=255, verbose_name='驱动')), + ('enable_ipv6', models.BooleanField(default=False, verbose_name='是否开启 IPv6')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ('update_date', models.DateTimeField(auto_now=True, verbose_name='更新时间')), + ], + options={ + 'db_table': 'net_work_info', + }, + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='8ca211fc-b7e3-4e21-a8d8-cb5a341e6b5d', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + migrations.CreateModel( + name='CombinationContainer', + fields=[ + ('container_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), + ('combination_info_id', models.UUIDField(editable=False, verbose_name='用户启动镜像组合ID')), + ('combination_image_id', models.UUIDField(editable=False, verbose_name='漏洞组合镜像信息ID')), + ('combination_image_info_id', models.UUIDField(editable=False, verbose_name='漏洞组合镜像信息ID')), + ('user_id', models.IntegerField(verbose_name='使用用户ID')), + ('docker_container_id', models.CharField(max_length=255, verbose_name='Docker容器运行进ID')), + ('vul_host', models.CharField(max_length=255, verbose_name='容器漏洞URL')), + ('container_status', models.CharField(max_length=255, verbose_name='容器状态')), + ('container_port', models.CharField(max_length=255, verbose_name='容器端口')), + ('container_flag', models.CharField(max_length=255, verbose_name='flag')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='容器创建时间,默认为当前时间')), + ('is_check', models.BooleanField(default=False, verbose_name='Flag是否通过')), + ('is_check_date', models.DateTimeField(null=True, verbose_name='Flag提交时间')), + ('image_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dockerapi.ImageInfo', verbose_name='镜像ID')), + ], + options={ + 'db_table': 'combination_container', + }, + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0007_auto_20191205_1747.py b/vulfocus-api/dockerapi/migrations/0007_auto_20191205_1747.py new file mode 100644 index 00000000..92311951 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0007_auto_20191205_1747.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-05 09:47 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0006_auto_20191128_2251'), + ] + + operations = [ + migrations.AddField( + model_name='combinationcontainer', + name='vul_ip', + field=models.CharField(default='', max_length=255, verbose_name='容器漏洞URL'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='bcedecaf-c63a-4898-a198-aaccd82fb977', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0008_auto_20191206_1205.py b/vulfocus-api/dockerapi/migrations/0008_auto_20191206_1205.py new file mode 100644 index 00000000..c706a290 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0008_auto_20191206_1205.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-06 04:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0007_auto_20191205_1747'), + ] + + operations = [ + migrations.AlterField( + model_name='combinationcontainer', + name='image_id', + field=models.UUIDField(editable=False, verbose_name='镜像ID'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='ce7cbda8-491e-4af2-a83a-ca02968a901c', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0009_auto_20191206_1305.py b/vulfocus-api/dockerapi/migrations/0009_auto_20191206_1305.py new file mode 100644 index 00000000..2dcefe53 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0009_auto_20191206_1305.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-06 05:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0008_auto_20191206_1205'), + ] + + operations = [ + migrations.AddField( + model_name='networkinfo', + name='net_work_client_id', + field=models.CharField(default='', max_length=255, verbose_name='Dcoker网卡链接ID'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='09e1d7e1-9492-4222-82ff-5ed1b2ed0132', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0010_auto_20191213_1142.py b/vulfocus-api/dockerapi/migrations/0010_auto_20191213_1142.py new file mode 100644 index 00000000..d21446dc --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0010_auto_20191213_1142.py @@ -0,0 +1,29 @@ +# Generated by Django 2.2.5 on 2019-12-13 03:42 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0009_auto_20191206_1305'), + ] + + operations = [ + migrations.AddField( + model_name='combinationinfo', + name='master_id', + field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='入口节点ID'), + ), + migrations.AddField( + model_name='combinationinfo', + name='master_status', + field=models.CharField(default='', max_length=255, verbose_name='入口节点状态'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='6cb6250c-d9f3-469e-a40c-56e667d2a508', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0011_auto_20191213_1144.py b/vulfocus-api/dockerapi/migrations/0011_auto_20191213_1144.py new file mode 100644 index 00000000..660f38c7 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0011_auto_20191213_1144.py @@ -0,0 +1,43 @@ +# Generated by Django 2.2.5 on 2019-12-13 03:44 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0010_auto_20191213_1142'), + ] + + operations = [ + migrations.AlterField( + model_name='combinationcontainer', + name='vul_ip', + field=models.CharField(max_length=255, verbose_name='容器漏洞URL'), + ), + migrations.AlterField( + model_name='combinationinfo', + name='master_id', + field=models.UUIDField(editable=False, verbose_name='入口节点ID'), + ), + migrations.AlterField( + model_name='combinationinfo', + name='master_status', + field=models.CharField(max_length=255, verbose_name='入口节点状态'), + ), + migrations.AlterField( + model_name='containervul', + name='time_model_id', + field=models.CharField(max_length=255, verbose_name='时间模式 ID'), + ), + migrations.AlterField( + model_name='networkinfo', + name='net_work_client_id', + field=models.CharField(max_length=255, verbose_name='Dcoker网卡链接ID'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='2b84a266-0d45-4c75-b184-5856eaf1ddd6', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0012_auto_20191213_1501.py b/vulfocus-api/dockerapi/migrations/0012_auto_20191213_1501.py new file mode 100644 index 00000000..268da140 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0012_auto_20191213_1501.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-13 07:01 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0011_auto_20191213_1144'), + ] + + operations = [ + migrations.AddField( + model_name='combinationinfo', + name='master_host', + field=models.CharField(default='', max_length=255, verbose_name='入口节点Host'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='13c80d8b-a58c-4425-9a96-7a5fe68f8bef', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0013_auto_20191213_1501.py b/vulfocus-api/dockerapi/migrations/0013_auto_20191213_1501.py new file mode 100644 index 00000000..a4ced55d --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0013_auto_20191213_1501.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-13 07:01 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0012_auto_20191213_1501'), + ] + + operations = [ + migrations.AlterField( + model_name='combinationinfo', + name='master_host', + field=models.CharField(max_length=255, verbose_name='入口节点Host'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='196bfd80-0b46-4d6d-bee4-4fbb62f554c8', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0014_auto_20191213_1513.py b/vulfocus-api/dockerapi/migrations/0014_auto_20191213_1513.py new file mode 100644 index 00000000..b256e350 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0014_auto_20191213_1513.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-13 07:13 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0013_auto_20191213_1501'), + ] + + operations = [ + migrations.AddField( + model_name='combinationimage', + name='combination_desc', + field=models.TextField(default='', null=True, verbose_name='环境描述'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='9a8928c8-b6fc-44a8-909b-f68522baa342', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0015_auto_20191220_1903.py b/vulfocus-api/dockerapi/migrations/0015_auto_20191220_1903.py new file mode 100644 index 00000000..c1acb70c --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0015_auto_20191220_1903.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-20 11:03 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0014_auto_20191213_1513'), + ] + + operations = [ + migrations.AddField( + model_name='networkinfo', + name='create_user', + field=models.IntegerField(default=1, verbose_name='创建用户ID'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='cf637d0a-1b3f-4528-90ed-099b2936dfc8', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0016_auto_20191220_1904.py b/vulfocus-api/dockerapi/migrations/0016_auto_20191220_1904.py new file mode 100644 index 00000000..c2ac3cb8 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0016_auto_20191220_1904.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.5 on 2019-12-20 11:04 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0015_auto_20191220_1903'), + ] + + operations = [ + migrations.AlterField( + model_name='networkinfo', + name='create_user', + field=models.IntegerField(verbose_name='创建用户ID'), + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='fb8a09b5-c9d7-4001-9574-baecc99d2a43', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0017_auto_20191220_1912.py b/vulfocus-api/dockerapi/migrations/0017_auto_20191220_1912.py new file mode 100644 index 00000000..97fcc516 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0017_auto_20191220_1912.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.5 on 2019-12-20 11:12 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0016_auto_20191220_1904'), + ] + + operations = [ + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='f2ae48f4-a4d7-4a0c-a1b0-94f035bef3d9', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/0018_auto_20200110_1553.py b/vulfocus-api/dockerapi/migrations/0018_auto_20200110_1553.py new file mode 100644 index 00000000..91acaa02 --- /dev/null +++ b/vulfocus-api/dockerapi/migrations/0018_auto_20200110_1553.py @@ -0,0 +1,35 @@ +# Generated by Django 2.2.5 on 2020-01-10 07:53 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ('dockerapi', '0017_auto_20191220_1912'), + ] + + operations = [ + migrations.CreateModel( + name='SysLog', + fields=[ + ('log_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), + ('user_id', models.IntegerField(verbose_name='使用用户ID')), + ('operation_type', models.CharField(max_length=255, verbose_name='操作类型')), + ('operation_name', models.CharField(max_length=255, verbose_name='操作名称')), + ('operation_value', models.CharField(max_length=255, verbose_name='操作内容')), + ('operation_args', models.TextField(default='', null=True, verbose_name='参数')), + ('ip', models.CharField(max_length=255, verbose_name='IP地址')), + ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), + ], + options={ + 'db_table': 'sys_log', + }, + ), + migrations.AlterField( + model_name='timemoudel', + name='time_id', + field=models.CharField(default='eb0fa616-f5f6-4f6d-8864-1fd37d126ec6', max_length=255, primary_key=True, serialize=False, verbose_name='ID'), + ), + ] diff --git a/vulfocus-api/dockerapi/migrations/__init__.py b/vulfocus-api/dockerapi/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/vulfocus-api/dockerapi/models.py b/vulfocus-api/dockerapi/models.py new file mode 100644 index 00000000..6ea8b22f --- /dev/null +++ b/vulfocus-api/dockerapi/models.py @@ -0,0 +1,64 @@ +from django.db import models +import uuid +from user.models import UserProfile +# Create your models here. + + +class ImageInfo(models.Model): + """ + 镜像实体Model + """ + image_id = models.UUIDField(default=uuid.uuid4,editable=False, primary_key=True) + image_name = models.CharField(max_length=256,unique=True, verbose_name='Docker镜像名称', null=False) + image_vul_name = models.CharField(max_length=256,verbose_name='漏洞名称', null=False) + image_port = models.CharField(null=False, verbose_name='暴露端口', max_length=256) + image_desc = models.TextField(verbose_name='镜像描述', null=True) + rank = models.FloatField(verbose_name='Rank', null=False) + create_date = models.DateTimeField(auto_now_add=True, verbose_name='Docker创建时间,默认为当前时间') + update_date = models.DateTimeField(auto_now=True, verbose_name='Docker更新时间,默认为当前时间') + + class Meta: + db_table = 'image_info' + + +class ContainerVul(models.Model): + """ + 容器实体Model + """ + container_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='漏洞容器创建ID') + docker_container_id = models.CharField(max_length=255, verbose_name='Docker容器运行进ID') + image_id = models.ForeignKey(ImageInfo, on_delete=models.CASCADE, verbose_name='Docker ID') + user_id = models.IntegerField(verbose_name='用户ID') + vul_host = models.CharField(max_length=255, verbose_name='容器漏洞URL') + container_status = models.CharField(max_length=255, verbose_name='容器当前状态') + container_port = models.CharField(max_length=255, verbose_name='容器端口') + container_flag = models.CharField(max_length=255, verbose_name='flag') + create_date = models.DateTimeField(auto_now_add=True, verbose_name='容器创建时间,默认为当前时间') + is_check = models.BooleanField(default=False, verbose_name='Flag是否通过') + is_check_date = models.DateTimeField(null=True, verbose_name='Flag提交时间') + time_model_id = models.CharField(max_length=255, verbose_name='时间模式 ID') + + class Meta: + db_table = 'container_vul' + + +class SysLog(models.Model): + # id + log_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name="ID") + # 操作人员ID + user_id = models.IntegerField(verbose_name="使用用户ID") + # 操作类型字段 + operation_type = models.CharField(max_length=255, verbose_name="操作类型") + # 操作名称 + operation_name = models.CharField(max_length=255, verbose_name="操作名称") + # 操作内容 + operation_value = models.CharField(max_length=255, verbose_name="操作内容") + # 操作参数 + operation_args = models.TextField(verbose_name='参数', null=True, default="") + # ip + ip = models.CharField(max_length=255, verbose_name="IP地址") + # 创建时间 + create_date = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') + + class Meta: + db_table = "sys_log" diff --git a/vulfocus-api/dockerapi/serializers.py b/vulfocus-api/dockerapi/serializers.py new file mode 100644 index 00000000..aea3fcb0 --- /dev/null +++ b/vulfocus-api/dockerapi/serializers.py @@ -0,0 +1,85 @@ +# coding:utf-8 +from rest_framework import serializers +from dockerapi.models import ImageInfo, ContainerVul, SysLog +from user.models import UserProfile + + +class ImageInfoSerializer(serializers.ModelSerializer): + + status = serializers.SerializerMethodField('statusck') + + def statusck(self, obj): + status = {} + id = None + request = self.context.get("request") + if request and hasattr(request, "user"): + id = request.user.id + ''' + 检测是否在时间模式中 + ''' + time_model_id = '' + data = ContainerVul.objects.all().filter(user_id=id, image_id=obj.image_id,time_model_id=time_model_id).first() + if data: + status["status"] = data.container_status + status["is_check"] = data.is_check + status["container_id"] = data.container_id + else: + status["status"] = "" + status["is_check"] = False + status["container_id"] = "" + return status + + class Meta: + model = ImageInfo + fields = "__all__" + + +class ContainerVulSerializer(serializers.ModelSerializer): + rank = serializers.SerializerMethodField('ranktocon') + name = serializers.SerializerMethodField('conname') + user_name = serializers.SerializerMethodField('get_user_name') + vul_name = serializers.SerializerMethodField('get_vul_name') + vul_desc = serializers.SerializerMethodField('get_vul_desc') + + + class Meta: + model = ContainerVul + fields = ['name', 'container_id', 'container_status', 'vul_host', 'create_date', 'is_check', 'is_check_date', + 'rank', 'user_name', 'vul_name', 'vul_desc'] + + def get_vul_name(self,obj): + return obj.image_id.image_vul_name + + def get_vul_desc(self,obj): + return obj.image_id.image_desc + + def ranktocon(self, obj): + if obj: + return obj.image_id.rank + else: + return "" + + def conname(self, obj): + if obj: + return obj.image_id.image_name + else: + return "" + + def get_user_name(self, obj): + user_id = obj.user_id + user_info = UserProfile.objects.get(id=user_id) + return user_info.username + + +class SysLogSerializer(serializers.ModelSerializer): + + user_name = serializers.SerializerMethodField('get_user_name') + + class Meta: + model = SysLog + fields = ['user_name', 'operation_type', 'operation_name', 'operation_value', 'operation_args', 'ip', 'create_date'] + + def get_user_name(self, obj): + user_id = obj.user_id + user_info = UserProfile.objects.get(id=user_id) + return user_info.username diff --git a/vulfocus-api/dockerapi/tests.py b/vulfocus-api/dockerapi/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/vulfocus-api/dockerapi/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/vulfocus-api/dockerapi/views.py b/vulfocus-api/dockerapi/views.py new file mode 100644 index 00000000..a1ca1e36 --- /dev/null +++ b/vulfocus-api/dockerapi/views.py @@ -0,0 +1,485 @@ +import uuid, time, random, socket, traceback +from django.http import JsonResponse +from rest_framework import viewsets +from rest_framework.decorators import action +from dockerapi.models import ImageInfo +from dockerapi.serializers import ImageInfoSerializer, ContainerVulSerializer, SysLogSerializer +from dockerapi.models import ContainerVul +from vulfocus.settings import client, VUL_IP +import django.utils +import django.utils.timezone as timezone +from docker.errors import NotFound, ImageNotFound +from .common import R +from django.db.models import Q +from docker.models.images import Image +from .models import SysLog + + +def get_request_ip(request): + """ + 获取请求IP + :param request: + :return: + """ + request_ip = "" + if request.META.get('HTTP_X_FORWARDED_FOR'): + request_ip = request.META.get("HTTP_X_FORWARDED_FOR") + else: + request_ip = request.META.get("REMOTE_ADDR") + return request_ip + + +class ImageInfoViewSet(viewsets.ModelViewSet): + serializer_class = ImageInfoSerializer + + def get_queryset(self): + query = self.request.GET.get("query", "") + if query: + query = query.strip() + image_info_list = ImageInfo.objects.filter(Q(image_name__contains=query) | Q(image_vul_name__contains=query) + | Q(image_desc__contains=query)) + else: + image_info_list = ImageInfo.objects.all() + return image_info_list + + def destroy(self, request, *args, **kwargs): + """ + 删除镜像 + :param request: + :param args: + :param kwargs: + :return: + """ + user = request.user + if not user.is_superuser: + return JsonResponse(R.build(msg="权限不足")) + img = self.get_object() + + operation_args = ImageInfoSerializer(img).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user.id, operation_type="镜像", operation_name="删除", + operation_value=operation_args["image_vul_name"], operation_args=operation_args, ip=request_ip) + sys_log.save() + + image_id = img.image_id + container_vul = ContainerVul.objects.filter(image_id=image_id) + if container_vul.count() == 0: + img.delete() + return JsonResponse(R.ok()) + else: + return JsonResponse(R.build(msg="镜像正在使用,无法删除!")) + + def create(self, request, *args, **kwargs): + """ + 创建镜像 + :param request: + :param args: + :param kwargs: + :return: + """ + user = request.user + if not user.is_superuser: + return JsonResponse(R.build(msg="权限不足!")) + file = request.FILES.get("file") + rank = request.POST.get("rank", default=2.5) + image_name = request.POST.get("name") + try: + rank = float(rank) + except Exception as e: + return JsonResponse(R.build(msg="Rank 格式错误")) + image_vul_name = request.POST.get("vul_name", default="") + if not image_vul_name: + return JsonResponse(R.build(msg="漏洞名称不能为空")) + image_desc = request.POST.get("desc", default="") + if not file and not image_name: + return JsonResponse(R.build(msg="镜像文件或名称不能为空")) + if file and image_name: + return JsonResponse(R.build(msg="镜像文件或名称不能同时填写")) + image_port = "" + if not image_name and file: + try: + file_info = file.read() + images = client.images.load(file_info) + image = images[0] + repo_tags = image.attrs["RepoTags"] + if len(repo_tags) == 0: + # 移除本地镜像 + try: + client.images.remove(image.id) + except Exception as e: + pass + return JsonResponse(msg="镜像名称不能为空") + config = image.attrs["ContainerConfig"] + port_list = [] + if "ExposedPorts" in config: + port_list = config["ExposedPorts"] + ports = [] + for port in port_list: + port = port.replace("/", "").replace("tcp", "").replace("udp", "") + ports.append(port) + image_name = repo_tags[0] + image_port = ",".join(ports) + except Exception as e: + return JsonResponse(R.err()) + """ + 查重 + """ + count = ImageInfo.objects.filter(image_name=image_name).count() + if count > 0: + return JsonResponse(R.build(msg="漏洞镜像已存在!")) + if not file and image_name: + try: + image = client.images.get(image_name) + except Exception as e: + images = client.images.pull(image_name) + if Image == type(images): + image = images + else: + if len(images) > 0: + image = images[0] + else: + return JsonResponse(R.build("镜像不存在!")) + config = image.attrs["ContainerConfig"] + port_list = [] + if "ExposedPorts" in config: + port_list = config["ExposedPorts"] + ports = [] + for port in port_list: + port = port.replace("/", "").replace("tcp", "").replace("udp", "") + ports.append(port) + image_port = ",".join(ports) + image_info = ImageInfo(image_name=image_name, image_vul_name=image_vul_name, image_port=image_port, rank=rank, + image_desc=image_desc) + image_info.save() + rs_data = ImageInfoSerializer(image_info).data + + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user.id, operation_type="镜像", operation_name="创建", + operation_value=rs_data["image_vul_name"], operation_args=rs_data, ip=request_ip) + sys_log.save() + return JsonResponse(R.ok(data=rs_data)) + + @action(methods=["post", "get"], detail=True, url_path="start") + def start_container(self, request, pk=None): + """ + 启动靶场 + :param request: + :param pk: + :return: + """ + Img = self.get_object() + # 当前用户登录ID + user_id = request.user.id + image_id = Img.image_id + time_model_id = '' + try: + container_vul = ContainerVul.objects.filter(user_id=user_id, image_id=image_id, time_model_id=time_model_id).first() + # 连接Docker容器 + docker_container = client.containers.get(container_id=container_vul.docker_container_id) + # 当前状态 + if 'exited' == container_vul.container_status or 'exited' == docker_container.status: + # 启动 + docker_container.start() + time_sleep_count = 10 + container_status = str(docker_container.status) + for i in range(time_sleep_count): + docker_container.reload() + container_status = str(docker_container.status) + if 'running' == container_status: + break + elif 'exited' == container_status: + pass + time.sleep(1) + if 'running' != container_status: + return JsonResponse({"info": "", "msg": "漏洞容器启动失败"}, status=202) + container_vul.container_status = container_status + container_vul.save() + + operation_args = ImageInfoSerializer(Img).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="启动", + operation_value=operation_args["image_vul_name"], operation_args=operation_args, + ip=request_ip) + sys_log.save() + + return JsonResponse({"info": container_vul.vul_host, "container_id": container_vul.container_id, "msg": "容器已启动"},status=201) + except AttributeError as attribute_error: + pass + except NotFound as docker_not_found: + # 容器不存在,直接删除数据库记录 + container_vul.delete() + except Exception as e: + return JsonResponse({"info": "", "msg": "服务器内部错误,请联系管理员"}, status=500) + vul_flag = "flag-{bmh%s}" % (uuid.uuid4(),) + vul_ip = get_local_ip() + if not vul_ip: + return JsonResponse({"info": "", "msg": "服务器内部错误,请联系管理员"}, status=500) + command = 'touch /tmp/%s' % (vul_flag, ) + image_port = Img.image_port + image_port_list = image_port.split(',') + port_dict = {} + for tmp_port in image_port_list: + tmp_random_port = '' + for i in range(20): + try: + # 端口 + tmp_random_port = random.randint(8000, 65536) + ContainerVul.objects.get(container_port=tmp_random_port) + print('端口重复 --> %s' % (tmp_random_port,)) + except Exception as e: + break + if not tmp_random_port: + return JsonResponse({"info": "", "msg": "端口无效"}, status=202) + port_dict['%s/tcp' % (tmp_port, )] = tmp_random_port + try: + container = client.containers.run(image=Img.image_name, ports=port_dict, detach=True) + time_sleep_count = 10 + container_status = str(container.status) + for i in range(time_sleep_count): + container.reload() + container_status = str(container.status) + if 'running' == container_status: + print(container.exec_run(command)) + break + elif 'exited' == container_status: + break + time.sleep(1) + # docker 容器 id + docker_container_id = container.id + port_list = port_dict.values() + tmp_port_list = [] + for tmp_port in port_list: + tmp_port_list.append(str(tmp_port)) + port_str = ",".join(tmp_port_list) + vul_host = vul_ip + ':' + port_str + container_vul = ContainerVul(image_id=Img, user_id=request.user.id, vul_host=vul_host, + container_status=container_status, + docker_container_id=docker_container_id, + container_port=port_str, + time_model_id=time_model_id, + create_date=django.utils.timezone.now(), + container_flag=vul_flag) + container_vul.save() + + operation_args = ImageInfoSerializer(Img).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="启动", + operation_value=operation_args["image_vul_name"], operation_args=operation_args, ip=request_ip) + sys_log.save() + + return JsonResponse({"info": vul_host, "container_id": container_vul.container_id}, status=201) + except ImageNotFound as image_not_found: + return JsonResponse({"info": "", "msg": "镜像不存在"}) + except Exception as e: + traceback.print_exc() + return JsonResponse({"info": "", "msg": "服务器内部错误,请联系管理员"}, status=500) + + +class ContainerVulViewSet(viewsets.ReadOnlyModelViewSet): + + serializer_class = ContainerVulSerializer + + def get_queryset(self): + request = self.request + user = request.user + flag = request.GET.get("flag", "") + if flag == 'list' and user.is_superuser: + container_vul_list = ContainerVul.objects.all() + else: + container_vul_list = ContainerVul.objects.all().filter(user_id=self.request.user.id, time_model_id="") + return container_vul_list + + @action(methods=["get"], detail=True, url_path='start') + def start_container(self, request, pk=None): + """ + 启动容器 + :param request: + :param pk: + :return: + """ + user_info = request.user + container_vul = self.get_object() + user_id = user_info.id + + operation_args = ContainerVulSerializer(container_vul).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="启动", + operation_value=operation_args["vul_name"], operation_args=operation_args, + ip=request_ip) + sys_log.save() + + if user_info.is_superuser or user_id == container_vul.user_id: + try: + # docker 连接容器ID + docker_container_id = container_vul.docker_container_id + # 连接Docker容器 + docker_container = client.containers.get(docker_container_id) + docker_container.start() + container_vul.container_status = 'running' + container_vul.save() + return JsonResponse({"info": container_vul.vul_host, "container_id": container_vul.container_id}, status=201) + except Exception as e: + return JsonResponse({"msg": "服务器内部错误", "code": "500"}, status=500) + else: + return JsonResponse({"msg": "权限不足", "code": "202"}) + + @action(methods=["get"], detail=True, url_path='stop') + def stop_container(self, request, pk=None): + """ + 停止容器运行 + :param request: + :param pk: + :return: + """ + user_info = request.user + container_vul = self.get_object() + user_id = user_info.id + + operation_args = ContainerVulSerializer(container_vul).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="停止", + operation_value=operation_args["vul_name"], operation_args=operation_args, + ip=request_ip) + sys_log.save() + + if user_info.is_superuser or user_id == container_vul.user_id: + try: + # docker 连接容器ID + docker_container_id = container_vul.docker_container_id + # 连接 Docker 容器 + docker_container = client.containers.get(docker_container_id) + docker_container.stop() + container_vul.container_status = 'stop' + container_vul.save() + return JsonResponse({"msg": "停止成功", "code": "202"}, status=201) + except NotFound as not_found: + container_vul.delete() + return JsonResponse({"msg": "停止成功", "code": "202"}, status=201) + except Exception as e: + return JsonResponse({"msg": "停止失败,服务器内部错误", "code": "500"}, status=500) + else: + return JsonResponse({"msg": "权限不足", "code": "202"}) + + ''' + 删除容器 + ''' + @action(methods=["delete"], detail=True, url_path="delete") + def delete_container(self, request, pk=None): + user_info = request.user + container_vul = self.get_object() + user_id = user_info.id + + operation_args = ContainerVulSerializer(container_vul).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="删除", + operation_value=operation_args["vul_name"], operation_args=operation_args, + ip=request_ip) + sys_log.save() + if user_info.is_superuser or user_id == container_vul.user_id: + # docker 连接容器ID + docker_container_id = container_vul.docker_container_id + try: + # 连接Docker容器 + docker_container = client.containers.get(docker_container_id) + # 停止容器运行 + docker_container.stop() + # 删除容器 + docker_container.remove() + except Exception as e: + print(e) + # 删除对象 + container_vul.delete() + return JsonResponse({"msg": "删除成功", "code": "201"}, status=201) + else: + return JsonResponse({"msg": "权限不足", "code": "202"}) + + ''' + 验证Flag是否正确 + ''' + @action(methods=["post", "get"], detail=True, url_path="flag") + def check_flag(self, request, pk=None): + flag = request.GET.get('flag', None) + container_vul = self.get_object() + user_id = request.user.id + + operation_args = ContainerVulSerializer(container_vul).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="提交Flag", + operation_value=operation_args["vul_name"], operation_args={"flag": flag}, + ip=request_ip) + sys_log.save() + + if user_id != container_vul.user_id: + return JsonResponse({"code": "2003", "msg": "与用户不匹配"}) + if not flag: + return JsonResponse({"code": "2003", "msg": "Flag不能为空"}) + try: + if flag != container_vul.container_flag: + return JsonResponse({"code": "2001", "msg": "flag错误"}) + else: + if not container_vul.is_check: + # 更新为通过 + container_vul.is_check_date = django.utils.timezone.now() + container_vul.is_check = True + try: + docker_container_id = container_vul.docker_container_id + docker_container = client.containers.get(container_id=docker_container_id) + docker_container.stop() + container_vul.container_status = 'stop' + container_vul.save() + except Exception as e: + pass + return JsonResponse({"code": "2000", "msg": "OK"}, status=201) + except Exception as e: + return JsonResponse({"code": "2002", "msg": str(e)}) + + ''' + 获取靶场状态信息 + ''' + @action(methods=["get"], detail=True, url_path="status") + def status_container(self, request, pk=None): + container_vul = self.get_object() + user_id = request.user.id + + operation_args = ContainerVulSerializer(container_vul).data + request_ip = get_request_ip(request) + sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="状态", + operation_value=operation_args["vul_name"], operation_args=operation_args, + ip=request_ip) + sys_log.save() + + if container_vul.user_id != user_id: + return JsonResponse({"code": "2003", "msg": "与用户不匹配"}) + info = ContainerVulSerializer(container_vul) + rs_data = info.data + return JsonResponse(rs_data) + + +class SysLogSet(viewsets.ModelViewSet): + + serializer_class = SysLogSerializer + + def get_queryset(self): + request = self.request + user = request.user + if user.is_superuser: + return SysLog.objects.all().filter() + else: + return [] + + +def get_local_ip(): + """ + 获取本机IP + :return: + """ + local_ip = '' + if VUL_IP: + return VUL_IP + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(('8.8.8.8', 80)) + local_ip = s.getsockname()[0] + finally: + s.close() + return local_ip diff --git a/vulfocus-api/manage.py b/vulfocus-api/manage.py new file mode 100755 index 00000000..ea6d56aa --- /dev/null +++ b/vulfocus-api/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vulfocus.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/vulfocus-api/requirements.txt b/vulfocus-api/requirements.txt new file mode 100644 index 00000000..1d4bad5c --- /dev/null +++ b/vulfocus-api/requirements.txt @@ -0,0 +1,14 @@ +Django==2.2.5 +django-cors-headers==3.1.0 +django-filter==2.2.0 +djangorestframework==3.10.3 +djangorestframework-jwt==1.11.0 +Markdown==3.1.1 +PyJWT==1.7.1 +pytz==2019.2 +sqlparse==0.3.0 +IPy==1.0 +docker==3.7.3 +docker-compose==1.25.4 +docker-pycreds==0.4.0 +dockerpty==0.4.1 \ No newline at end of file diff --git a/vulfocus-api/run.sh b/vulfocus-api/run.sh new file mode 100644 index 00000000..8e5a951a --- /dev/null +++ b/vulfocus-api/run.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +service nginx start +wait +python3 manage.py runserver 0.0.0.0:8000 \ No newline at end of file diff --git a/vulfocus-api/sources.list b/vulfocus-api/sources.list new file mode 100644 index 00000000..2914959f --- /dev/null +++ b/vulfocus-api/sources.list @@ -0,0 +1,11 @@ +deb https://mirrors.ustc.edu.cn/debian/ stretch main contrib non-free +deb-src https://mirrors.ustc.edu.cn/debian/ stretch main contrib non-free + +deb https://mirrors.ustc.edu.cn/debian/ stretch-updates main contrib non-free +deb-src https://mirrors.ustc.edu.cn/debian/ stretch-updates main contrib non-free + +deb https://mirrors.ustc.edu.cn/debian/ stretch-backports main contrib non-free +deb-src https://mirrors.ustc.edu.cn/debian/ stretch-backports main contrib non-free + +deb https://mirrors.ustc.edu.cn/debian-security/ stretch/updates main contrib non-free +deb-src https://mirrors.ustc.edu.cn/debian-security/ stretch/updates main contrib non-free \ No newline at end of file diff --git a/vulfocus-api/user/__init__.py b/vulfocus-api/user/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/vulfocus-api/user/admin.py b/vulfocus-api/user/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/vulfocus-api/user/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/vulfocus-api/user/apps.py b/vulfocus-api/user/apps.py new file mode 100644 index 00000000..35048d48 --- /dev/null +++ b/vulfocus-api/user/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class UserConfig(AppConfig): + name = 'user' diff --git a/vulfocus-api/user/jwt.py b/vulfocus-api/user/jwt.py new file mode 100644 index 00000000..52663b07 --- /dev/null +++ b/vulfocus-api/user/jwt.py @@ -0,0 +1,10 @@ +# coding:utf-8 + + +def jwt_response_payload_handler(token, user=None, request=None): + return { + "code": 20000, + "data": { + "token": token + } + } diff --git a/vulfocus-api/user/migrations/0001_initial.py b/vulfocus-api/user/migrations/0001_initial.py new file mode 100644 index 00000000..33a990a7 --- /dev/null +++ b/vulfocus-api/user/migrations/0001_initial.py @@ -0,0 +1,46 @@ +# Generated by Django 2.2.5 on 2019-09-20 12:16 + +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0011_update_proxy_permissions'), + ] + + operations = [ + migrations.CreateModel( + name='UserProfile', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('avatar', models.CharField(blank=True, max_length=100, null=True, verbose_name='头像')), + ('role', models.CharField(default='注册用户', max_length=10, verbose_name='角色')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'user', + 'verbose_name_plural': 'users', + 'abstract': False, + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/vulfocus-api/user/migrations/0002_auto_20191029_1158.py b/vulfocus-api/user/migrations/0002_auto_20191029_1158.py new file mode 100644 index 00000000..a80711a0 --- /dev/null +++ b/vulfocus-api/user/migrations/0002_auto_20191029_1158.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.5 on 2019-10-29 03:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('user', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='userprofile', + name='avatar', + field=models.CharField(blank=True, default='http://www.baimaohui.net/home/image/icon-anquan-logo.png', max_length=100, null=True, verbose_name='头像'), + ), + ] diff --git a/vulfocus-api/user/migrations/__init__.py b/vulfocus-api/user/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/vulfocus-api/user/models.py b/vulfocus-api/user/models.py new file mode 100644 index 00000000..55ad9c73 --- /dev/null +++ b/vulfocus-api/user/models.py @@ -0,0 +1,10 @@ +from django.db import models +from django.contrib.auth.models import AbstractUser + + +class UserProfile(AbstractUser): + avatar = models.CharField(max_length=100, null=True, blank=True, verbose_name="头像",default="http://www.baimaohui.net/home/image/icon-anquan-logo.png") + role = models.CharField(max_length=10, default="注册用户", verbose_name="角色") + + def __str__(self): + return self.username diff --git a/vulfocus-api/user/serializers.py b/vulfocus-api/user/serializers.py new file mode 100644 index 00000000..8ab38413 --- /dev/null +++ b/vulfocus-api/user/serializers.py @@ -0,0 +1,56 @@ +from django.contrib.auth import get_user_model +from rest_framework import serializers +from rest_framework.validators import UniqueValidator +from dockerapi.models import ContainerVul +import datetime +User = get_user_model() + + +class UserRegisterSerializer(serializers.ModelSerializer): + # 利用drf中的validators验证username是否唯一 + username = serializers.CharField(required=True, allow_blank=False, validators=[UniqueValidator(queryset=User.objects.all(),message='用户已经存在')]) + password = serializers.CharField( + style={"input_type": "password"},help_text="密码", label="密码", write_only=True, + ) + + def create(self, validated_data): + user = super(UserRegisterSerializer, self).create(validated_data= validated_data) + user.set_password(validated_data["password"]) + user.save() + return user + + class Meta: + model = User + fields = ("username","password","email") + + +class UserProfileSerializer(serializers.ModelSerializer): + name = serializers.SerializerMethodField('get_user_name') + rank = serializers.SerializerMethodField('rankAD') + status_moudel = serializers.SerializerMethodField('set_status_moudel') + roles = serializers.SerializerMethodField("set_role") + + class Meta: + model = User + fields = ("id", "name", "roles", "avatar", "email", "rank", "status_moudel") + + def get_user_name(self, obj): + return obj.username + + def set_status_moudel(self, obj): + return 0 + + def rankAD(self, obj): + rank = 0 + user_id = obj.id + time_model_id = '' + successful = ContainerVul.objects.filter(is_check=True, user_id=user_id, time_model_id=time_model_id) + for i in successful: + rank += i.image_id.rank + return rank + + def set_role(self, obj): + if obj.is_superuser: + return ["admin"] + else: + return ["member"] diff --git a/vulfocus-api/user/tests.py b/vulfocus-api/user/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/vulfocus-api/user/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/vulfocus-api/user/views.py b/vulfocus-api/user/views.py new file mode 100644 index 00000000..04e4a623 --- /dev/null +++ b/vulfocus-api/user/views.py @@ -0,0 +1,61 @@ +from django.http import JsonResponse +from rest_framework import viewsets,mixins +from user.serializers import UserProfileSerializer, User, UserRegisterSerializer +from rest_framework.views import APIView +from django.contrib.auth import logout +from django.views.generic.base import View +from user.models import UserProfile +from dockerapi.common import R +from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token + + +class ListAndUpdateViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): + """ + A viewset that provides default `update()`, `list()`actions. + """ + pass + + +class UserSet(ListAndUpdateViewSet): + serializer_class = UserProfileSerializer + + def get_queryset(self): + if self.request.user.is_superuser: + return UserProfile.objects.all() + else: + return [] + + def update(self, request, *args, **kwargs): + user = request.user + if not user.is_superuser: + return JsonResponse(R.build(msg="权限不足")) + print(self.get_object()) + new_pwd = request.data.get("pwd", "") + new_pwd = new_pwd.strip() + print(new_pwd) + if len(new_pwd) < 6: + return JsonResponse(R.build(msg="密码格式不正确")) + user_info = self.get_object() + user_info.set_password(new_pwd) + user_info.save() + return JsonResponse(R.ok()) + + +class get_user_info(APIView): + def get(self, request): + user_info = User.objects.get(pk=request.user.id) + serializer = UserProfileSerializer(user_info) + return JsonResponse(serializer.data) + + +class LogoutView(View): + def get(self, request): + logout(request) + return JsonResponse({"msg": "OK"}) + + +class UserRegView(viewsets.mixins.CreateModelMixin,viewsets.GenericViewSet): + authentication_classes = [] + permission_classes = [] + queryset = UserProfile.objects.all() + serializer_class = UserRegisterSerializer diff --git a/vulfocus-api/vulfocus/__init__.py b/vulfocus-api/vulfocus/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/vulfocus-api/vulfocus/settings.py b/vulfocus-api/vulfocus/settings.py new file mode 100644 index 00000000..9b8c8611 --- /dev/null +++ b/vulfocus-api/vulfocus/settings.py @@ -0,0 +1,162 @@ +""" +Django settings for vulfocus project. + +Generated by 'django-admin startproject' using Django 2.2.5. + +For more information on this file, see +https://docs.djangoproject.com/en/2.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/2.2/ref/settings/ +""" + +import os +import docker +import datetime + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'v!bz(7o_5u_4m-m7dgl-&-%81018li0u2)923fd)sp-pw%=c()' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = False + +ALLOWED_HOSTS = ["*"] + +AUTH_USER_MODEL = "user.UserProfile" + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'rest_framework', + 'user', + 'corsheaders', + 'dockerapi', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'corsheaders.middleware.CorsMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +CORS_ORIGIN_WHITELIST = [ + "http://localhost:9527", +] +CORS_ORIGIN_ALLOW_ALL = True + +REST_FRAMEWORK = { + # Use Django's standard `django.contrib.auth` permissions, + # or allow read-only access for unauthenticated users. + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.IsAuthenticated' + ], + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', + 'rest_framework.authentication.SessionAuthentication', + 'rest_framework.authentication.BasicAuthentication', + ] +} + +JWT_AUTH = { + # 'JWT_RESPONSE_PAYLOAD_HANDLER':'user.jwt.jwt_response_payload_handler', + # 指明token的有效期 + 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), + 'JWT_AUTH_HEADER_PREFIX': 'BMH', + +} + + +ROOT_URLCONF = 'vulfocus.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [os.path.join(BASE_DIR, 'templates')] + , + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'vulfocus.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/2.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/2.2/topics/i18n/ +LANGUAGE_CODE = 'zh-hans' + +TIME_ZONE = 'Asia/Shanghai' + +# TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +# docker api 连接, 本机默认为 127.0.0.1 +# client = docker.DockerClient("tcp://127.0.0.1:2375") +client = docker.DockerClient(base_url='unix://var/run/docker.sock') +# 靶场绑定 IP,提供用户访问靶场与 Docker 服务IP保持一致。 +VUL_IP = "" +if os.environ['VUL_IP']: + VUL_IP = os.environ['VUL_IP'] +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/2.2/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/vulfocus-api/vulfocus/urls.py b/vulfocus-api/vulfocus/urls.py new file mode 100644 index 00000000..99f15a0f --- /dev/null +++ b/vulfocus-api/vulfocus/urls.py @@ -0,0 +1,39 @@ +"""vulbox URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +# from django.contrib import admin +from django.conf.urls import url, include +from rest_framework import routers +from dockerapi.views import ImageInfoViewSet, ContainerVulViewSet, SysLogSet +from user.views import UserRegView, UserSet +from rest_framework_jwt.views import obtain_jwt_token +from user.views import get_user_info, LogoutView + +router = routers.DefaultRouter() +router.register('images', ImageInfoViewSet, base_name='Images') +router.register('container', ContainerVulViewSet, base_name='Container') +router.register('user/register', UserRegView, base_name='register') +router.register('user', UserSet, base_name='user') +router.register('syslog', SysLogSet, base_name="SysLog") +# check_docker_status + +urlpatterns = [ + url(r'^', include(router.urls)), + url(r'^user/login', obtain_jwt_token), + url(r'^user/logout', LogoutView.as_view(), name="logout"), + url(r'user/info', get_user_info.as_view()), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), + # path('admin/', admin.site.urls), +] diff --git a/vulfocus-api/vulfocus/wsgi.py b/vulfocus-api/vulfocus/wsgi.py new file mode 100644 index 00000000..1361ed6b --- /dev/null +++ b/vulfocus-api/vulfocus/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for vulfocus project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vulfocus.settings') + +application = get_wsgi_application() diff --git a/vulfocus-frontend/.editorconfig b/vulfocus-frontend/.editorconfig new file mode 100644 index 00000000..ea6e20f5 --- /dev/null +++ b/vulfocus-frontend/.editorconfig @@ -0,0 +1,14 @@ +# http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +insert_final_newline = false +trim_trailing_whitespace = false diff --git a/vulfocus-frontend/.env.development b/vulfocus-frontend/.env.development new file mode 100644 index 00000000..554ff517 --- /dev/null +++ b/vulfocus-frontend/.env.development @@ -0,0 +1,15 @@ +# just a flag +ENV = 'development' + +# base api +#VUE_APP_BASE_API = '/dev-api' +VUE_APP_BASE_API = 'http://127.0.0.1:8000' +VUE_APP_BASE_API = 'http://10.10.10.172:8000' +# vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, +# to control whether the babel-plugin-dynamic-import-node plugin is enabled. +# It only does one thing by converting all import() to require(). +# This configuration can significantly increase the speed of hot updates, +# when you have a large number of pages. +# Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js + +VUE_CLI_BABEL_TRANSPILE_MODULES = true diff --git a/vulfocus-frontend/.env.production b/vulfocus-frontend/.env.production new file mode 100644 index 00000000..07d391ea --- /dev/null +++ b/vulfocus-frontend/.env.production @@ -0,0 +1,6 @@ +# just a flag +ENV = 'production' + +# base api +VUE_APP_BASE_API = '/api' + diff --git a/vulfocus-frontend/.env.staging b/vulfocus-frontend/.env.staging new file mode 100644 index 00000000..a8793a09 --- /dev/null +++ b/vulfocus-frontend/.env.staging @@ -0,0 +1,8 @@ +NODE_ENV = production + +# just a flag +ENV = 'staging' + +# base api +VUE_APP_BASE_API = '/stage-api' + diff --git a/vulfocus-frontend/.eslintignore b/vulfocus-frontend/.eslintignore new file mode 100644 index 00000000..51525879 --- /dev/null +++ b/vulfocus-frontend/.eslintignore @@ -0,0 +1,5 @@ +build/*.js +src/assets +public +dist +src diff --git a/vulfocus-frontend/.eslintrc.js b/vulfocus-frontend/.eslintrc.js new file mode 100644 index 00000000..c9775054 --- /dev/null +++ b/vulfocus-frontend/.eslintrc.js @@ -0,0 +1,198 @@ +module.exports = { + root: true, + parserOptions: { + parser: 'babel-eslint', + sourceType: 'module' + }, + env: { + browser: true, + node: true, + es6: true, + }, + extends: ['plugin:vue/recommended', 'eslint:recommended'], + + // add your custom rules here + //it is base on https://github.com/vuejs/eslint-config-vue + rules: { + "vue/max-attributes-per-line": [2, { + "singleline": 10, + "multiline": { + "max": 1, + "allowFirstLine": false + } + }], + "vue/singleline-html-element-content-newline": "off", + "vue/multiline-html-element-content-newline":"off", + "vue/name-property-casing": ["error", "PascalCase"], + "vue/no-v-html": "off", + 'accessor-pairs': 2, + 'arrow-spacing': [2, { + 'before': true, + 'after': true + }], + 'block-spacing': [2, 'always'], + 'brace-style': [2, '1tbs', { + 'allowSingleLine': true + }], + 'camelcase': [0, { + 'properties': 'always' + }], + 'comma-dangle': [2, 'never'], + 'comma-spacing': [2, { + 'before': false, + 'after': true + }], + 'comma-style': [2, 'last'], + 'constructor-super': 2, + 'curly': [2, 'multi-line'], + 'dot-location': [2, 'property'], + 'eol-last': 2, + 'eqeqeq': ["error", "always", {"null": "ignore"}], + 'generator-star-spacing': [2, { + 'before': true, + 'after': true + }], + 'handle-callback-err': [2, '^(err|error)$'], + 'indent': [2, 2, { + 'SwitchCase': 1 + }], + 'jsx-quotes': [2, 'prefer-single'], + 'key-spacing': [2, { + 'beforeColon': false, + 'afterColon': true + }], + 'keyword-spacing': [2, { + 'before': true, + 'after': true + }], + 'new-cap': [2, { + 'newIsCap': true, + 'capIsNew': false + }], + 'new-parens': 2, + 'no-array-constructor': 2, + 'no-caller': 2, + 'no-console': 'off', + 'no-class-assign': 2, + 'no-cond-assign': 2, + 'no-const-assign': 2, + 'no-control-regex': 0, + 'no-delete-var': 2, + 'no-dupe-args': 2, + 'no-dupe-class-members': 2, + 'no-dupe-keys': 2, + 'no-duplicate-case': 2, + 'no-empty-character-class': 2, + 'no-empty-pattern': 2, + 'no-eval': 2, + 'no-ex-assign': 2, + 'no-extend-native': 2, + 'no-extra-bind': 2, + 'no-extra-boolean-cast': 2, + 'no-extra-parens': [2, 'functions'], + 'no-fallthrough': 2, + 'no-floating-decimal': 2, + 'no-func-assign': 2, + 'no-implied-eval': 2, + 'no-inner-declarations': [2, 'functions'], + 'no-invalid-regexp': 2, + 'no-irregular-whitespace': 2, + 'no-iterator': 2, + 'no-label-var': 2, + 'no-labels': [2, { + 'allowLoop': false, + 'allowSwitch': false + }], + 'no-lone-blocks': 2, + 'no-mixed-spaces-and-tabs': 2, + 'no-multi-spaces': 2, + 'no-multi-str': 2, + 'no-multiple-empty-lines': [2, { + 'max': 1 + }], + 'no-native-reassign': 2, + 'no-negated-in-lhs': 2, + 'no-new-object': 2, + 'no-new-require': 2, + 'no-new-symbol': 2, + 'no-new-wrappers': 2, + 'no-obj-calls': 2, + 'no-octal': 2, + 'no-octal-escape': 2, + 'no-path-concat': 2, + 'no-proto': 2, + 'no-redeclare': 2, + 'no-regex-spaces': 2, + 'no-return-assign': [2, 'except-parens'], + 'no-self-assign': 2, + 'no-self-compare': 2, + 'no-sequences': 2, + 'no-shadow-restricted-names': 2, + 'no-spaced-func': 2, + 'no-sparse-arrays': 2, + 'no-this-before-super': 2, + 'no-throw-literal': 2, + 'no-trailing-spaces': 2, + 'no-undef': 2, + 'no-undef-init': 2, + 'no-unexpected-multiline': 2, + 'no-unmodified-loop-condition': 2, + 'no-unneeded-ternary': [2, { + 'defaultAssignment': false + }], + 'no-unreachable': 2, + 'no-unsafe-finally': 2, + 'no-unused-vars': [2, { + 'vars': 'all', + 'args': 'none' + }], + 'no-useless-call': 2, + 'no-useless-computed-key': 2, + 'no-useless-constructor': 2, + 'no-useless-escape': 0, + 'no-whitespace-before-property': 2, + 'no-with': 2, + 'one-var': [2, { + 'initialized': 'never' + }], + 'operator-linebreak': [2, 'after', { + 'overrides': { + '?': 'before', + ':': 'before' + } + }], + 'padded-blocks': [2, 'never'], + 'quotes': [2, 'single', { + 'avoidEscape': true, + 'allowTemplateLiterals': true + }], + 'semi': [2, 'never'], + 'semi-spacing': [2, { + 'before': false, + 'after': true + }], + 'space-before-blocks': [2, 'always'], + 'space-before-function-paren': [2, 'never'], + 'space-in-parens': [2, 'never'], + 'space-infix-ops': 2, + 'space-unary-ops': [2, { + 'words': true, + 'nonwords': false + }], + 'spaced-comment': [2, 'always', { + 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ','] + }], + 'template-curly-spacing': [2, 'never'], + 'use-isnan': 2, + 'valid-typeof': 2, + 'wrap-iife': [2, 'any'], + 'yield-star-spacing': [2, 'both'], + 'yoda': [2, 'never'], + 'prefer-const': 2, + 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, + 'object-curly-spacing': [2, 'always', { + objectsInObjects: false + }], + 'array-bracket-spacing': [2, 'never'] + } +} diff --git a/vulfocus-frontend/.gitignore b/vulfocus-frontend/.gitignore new file mode 100644 index 00000000..9ad28d23 --- /dev/null +++ b/vulfocus-frontend/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +node_modules/ +dist/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +package-lock.json +tests/**/coverage/ + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln diff --git a/vulfocus-frontend/.travis.yml b/vulfocus-frontend/.travis.yml new file mode 100644 index 00000000..f4be7a08 --- /dev/null +++ b/vulfocus-frontend/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: 10 +script: npm run test +notifications: + email: false diff --git a/vulfocus-frontend/LICENSE b/vulfocus-frontend/LICENSE new file mode 100644 index 00000000..61515750 --- /dev/null +++ b/vulfocus-frontend/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-present PanJiaChen + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the 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. diff --git a/vulfocus-frontend/README.md b/vulfocus-frontend/README.md new file mode 100644 index 00000000..64536878 --- /dev/null +++ b/vulfocus-frontend/README.md @@ -0,0 +1,30 @@ +# vulfocus WEB + +vulfocus 前端项目,通过 Element-ui + VUE 构建。 + +环境: +- UI:Element UI +- 框架:vue +- node:v12.16.2 +- npm:6.14.4 + +## 部署 + +安装依赖: +```shell script +npm install +``` + +构建项目: +``` +npm run build:prod +``` + +将 dist 目录部署至 nginx 中,默认 nginx 静态目录位于 `/var/www/html`。 + +## 开发 + +```shell script +npm run dev +``` + diff --git a/vulfocus-frontend/babel.config.js b/vulfocus-frontend/babel.config.js new file mode 100644 index 00000000..ba179669 --- /dev/null +++ b/vulfocus-frontend/babel.config.js @@ -0,0 +1,5 @@ +module.exports = { + presets: [ + '@vue/app' + ] +} diff --git a/vulfocus-frontend/dist.zip b/vulfocus-frontend/dist.zip new file mode 100644 index 00000000..46f99983 Binary files /dev/null and b/vulfocus-frontend/dist.zip differ diff --git a/vulfocus-frontend/jest.config.js b/vulfocus-frontend/jest.config.js new file mode 100644 index 00000000..143cdc86 --- /dev/null +++ b/vulfocus-frontend/jest.config.js @@ -0,0 +1,24 @@ +module.exports = { + moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], + transform: { + '^.+\\.vue$': 'vue-jest', + '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': + 'jest-transform-stub', + '^.+\\.jsx?$': 'babel-jest' + }, + moduleNameMapper: { + '^@/(.*)$': '/src/$1' + }, + snapshotSerializers: ['jest-serializer-vue'], + testMatch: [ + '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)' + ], + collectCoverageFrom: ['src/utils/**/*.{js,vue}', '!src/utils/auth.js', '!src/utils/request.js', 'src/components/**/*.{js,vue}'], + coverageDirectory: '/tests/unit/coverage', + // 'collectCoverage': true, + 'coverageReporters': [ + 'lcov', + 'text-summary' + ], + testURL: 'http://localhost/' +} diff --git a/vulfocus-frontend/mock/index.js b/vulfocus-frontend/mock/index.js new file mode 100644 index 00000000..e14f94ed --- /dev/null +++ b/vulfocus-frontend/mock/index.js @@ -0,0 +1,66 @@ +import Mock from 'mockjs' +import { param2Obj } from '../src/utils' + +import user from './user' +import table from './table' + +const mocks = [ + ...user, + ...table +] + +// for front mock +// please use it cautiously, it will redefine XMLHttpRequest, +// which will cause many of your third-party libraries to be invalidated(like progress event). +export function mockXHR() { + // mock patch + // https://github.com/nuysoft/Mock/issues/300 + Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send + Mock.XHR.prototype.send = function() { + if (this.custom.xhr) { + this.custom.xhr.withCredentials = this.withCredentials || false + + if (this.responseType) { + this.custom.xhr.responseType = this.responseType + } + } + this.proxy_send(...arguments) + } + + function XHR2ExpressReqWrap(respond) { + return function(options) { + let result = null + if (respond instanceof Function) { + const { body, type, url } = options + // https://expressjs.com/en/4x/api.html#req + result = respond({ + method: type, + body: JSON.parse(body), + query: param2Obj(url) + }) + } else { + result = respond + } + return Mock.mock(result) + } + } + + for (const i of mocks) { + Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response)) + } +} + +// for mock server +const responseFake = (url, type, respond) => { + return { + url: new RegExp(`/mock${url}`), + type: type || 'get', + response(req, res) { + res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond)) + } + } +} + +export default mocks.map(route => { + return responseFake(route.url, route.type, route.response) +}) diff --git a/vulfocus-frontend/mock/mock-server.js b/vulfocus-frontend/mock/mock-server.js new file mode 100644 index 00000000..4c4cb2af --- /dev/null +++ b/vulfocus-frontend/mock/mock-server.js @@ -0,0 +1,68 @@ +const chokidar = require('chokidar') +const bodyParser = require('body-parser') +const chalk = require('chalk') +const path = require('path') + +const mockDir = path.join(process.cwd(), 'mock') + +function registerRoutes(app) { + let mockLastIndex + const { default: mocks } = require('./index.js') + for (const mock of mocks) { + app[mock.type](mock.url, mock.response) + mockLastIndex = app._router.stack.length + } + const mockRoutesLength = Object.keys(mocks).length + return { + mockRoutesLength: mockRoutesLength, + mockStartIndex: mockLastIndex - mockRoutesLength + } +} + +function unregisterRoutes() { + Object.keys(require.cache).forEach(i => { + if (i.includes(mockDir)) { + delete require.cache[require.resolve(i)] + } + }) +} + +module.exports = app => { + // es6 polyfill + require('@babel/register') + + // parse app.body + // https://expressjs.com/en/4x/api.html#req.body + app.use(bodyParser.json()) + app.use(bodyParser.urlencoded({ + extended: true + })) + + const mockRoutes = registerRoutes(app) + var mockRoutesLength = mockRoutes.mockRoutesLength + var mockStartIndex = mockRoutes.mockStartIndex + + // watch files, hot reload mock server + chokidar.watch(mockDir, { + ignored: /mock-server/, + ignoreInitial: true + }).on('all', (event, path) => { + if (event === 'change' || event === 'add') { + try { + // remove mock routes stack + app._router.stack.splice(mockStartIndex, mockRoutesLength) + + // clear routes cache + unregisterRoutes() + + const mockRoutes = registerRoutes(app) + mockRoutesLength = mockRoutes.mockRoutesLength + mockStartIndex = mockRoutes.mockStartIndex + + console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`)) + } catch (error) { + console.log(chalk.redBright(error)) + } + } + }) +} diff --git a/vulfocus-frontend/mock/table.js b/vulfocus-frontend/mock/table.js new file mode 100644 index 00000000..a072a211 --- /dev/null +++ b/vulfocus-frontend/mock/table.js @@ -0,0 +1,29 @@ +import Mock from 'mockjs' + +const data = Mock.mock({ + 'items|30': [{ + id: '@id', + title: '@sentence(10, 20)', + 'status|1': ['published', 'draft', 'deleted'], + author: 'name', + display_time: '@datetime', + pageviews: '@integer(300, 5000)' + }] +}) + +export default [ + { + url: '/table/list', + type: 'get', + response: config => { + const items = data.items + return { + code: 20000, + data: { + total: items.length, + items: items + } + } + } + } +] diff --git a/vulfocus-frontend/mock/user.js b/vulfocus-frontend/mock/user.js new file mode 100644 index 00000000..43f93a04 --- /dev/null +++ b/vulfocus-frontend/mock/user.js @@ -0,0 +1,84 @@ + +const tokens = { + admin: { + token: 'admin-token' + }, + editor: { + token: 'editor-token' + } +} + +const users = { + 'admin-token': { + roles: ['admin'], + introduction: 'I am a super administrator', + avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif', + name: 'Super Admin' + }, + 'editor-token': { + roles: ['editor'], + introduction: 'I am an editor', + avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif', + name: 'Normal Editor' + } +} + +export default [ + // user login + { + url: '/user/login', + type: 'post', + response: config => { + const { username } = config.body + const token = tokens[username] + + // mock error + if (!token) { + return { + code: 60204, + message: 'Account and password are incorrect.' + } + } + + return { + code: 20000, + data: token + } + } + }, + + // get user info + { + url: '/user/info\.*', + type: 'get', + response: config => { + const { token } = config.query + const info = users[token] + + // mock error + if (!info) { + return { + code: 50008, + message: 'Login failed, unable to get user details.' + } + } + + return { + code: 20000, + data: info + } + } + }, + + // user logout + { + url: '/user/logout', + type: 'post', + response: _ => { + return { + code: 20000, + data: 'success' + } + } + } +] diff --git a/vulfocus-frontend/package.json b/vulfocus-frontend/package.json new file mode 100644 index 00000000..fb83df59 --- /dev/null +++ b/vulfocus-frontend/package.json @@ -0,0 +1,66 @@ +{ + "name": "vue-admin-template", + "version": "4.2.1", + "description": "A vue admin template with Element UI & axios & iconfont & permission control & lint", + "author": "Pan ", + "license": "MIT", + "scripts": { + "dev": "vue-cli-service serve", + "build:prod": "vue-cli-service build", + "build:stage": "vue-cli-service build --mode staging", + "preview": "node build/index.js --preview", + "lint": "eslint --ext .js,.vue src", + "test:unit": "jest --clearCache && vue-cli-service test:unit", + "test:ci": "npm run lint && npm run test:unit", + "svgo": "svgo -f src/icons/svg --config=src/icons/svgo.yml" + }, + "dependencies": { + "axios": "0.18.1", + "element-ui": "2.7.2", + "js-cookie": "2.2.0", + "normalize.css": "7.0.0", + "nprogress": "0.2.0", + "path-to-regexp": "2.4.0", + "vue": "2.6.10", + "vue-good-wizard": "^1.4.1", + "vue-router": "3.0.6", + "vue2-countdown": "^1.0.8", + "vuex": "3.1.0" + }, + "devDependencies": { + "@babel/core": "7.0.0", + "@babel/register": "7.0.0", + "@vue/cli-plugin-babel": "3.6.0", + "@vue/cli-plugin-eslint": "^3.9.1", + "@vue/cli-plugin-unit-jest": "3.6.3", + "@vue/cli-service": "3.6.0", + "@vue/test-utils": "1.0.0-beta.29", + "autoprefixer": "^9.5.1", + "babel-core": "7.0.0-bridge.0", + "babel-eslint": "10.0.1", + "babel-jest": "23.6.0", + "chalk": "2.4.2", + "connect": "3.6.6", + "eslint": "5.15.3", + "eslint-plugin-vue": "5.2.2", + "html-webpack-plugin": "3.2.0", + "mockjs": "1.0.1-beta3", + "node-sass": "^4.9.0", + "runjs": "^4.3.2", + "sass-loader": "^7.1.0", + "script-ext-html-webpack-plugin": "2.1.3", + "script-loader": "0.7.2", + "serve-static": "^1.13.2", + "svg-sprite-loader": "4.1.3", + "svgo": "1.2.2", + "vue-template-compiler": "2.6.10" + }, + "engines": { + "node": ">=8.9", + "npm": ">= 3.0.0" + }, + "browserslist": [ + "> 1%", + "last 2 versions" + ] +} diff --git a/vulfocus-frontend/postcss.config.js b/vulfocus-frontend/postcss.config.js new file mode 100644 index 00000000..10473efc --- /dev/null +++ b/vulfocus-frontend/postcss.config.js @@ -0,0 +1,8 @@ +// https://github.com/michael-ciniawsky/postcss-load-config + +module.exports = { + 'plugins': { + // to edit target browsers: use "browserslist" field in package.json + 'autoprefixer': {} + } +} diff --git a/vulfocus-frontend/public/favicon.ico b/vulfocus-frontend/public/favicon.ico new file mode 100644 index 00000000..34b63ac6 Binary files /dev/null and b/vulfocus-frontend/public/favicon.ico differ diff --git a/vulfocus-frontend/public/index.html b/vulfocus-frontend/public/index.html new file mode 100644 index 00000000..fa2be916 --- /dev/null +++ b/vulfocus-frontend/public/index.html @@ -0,0 +1,17 @@ + + + + + + + + <%= webpackConfig.name %> + + + +
+ + + diff --git a/vulfocus-frontend/src/App.vue b/vulfocus-frontend/src/App.vue new file mode 100644 index 00000000..ec9032c1 --- /dev/null +++ b/vulfocus-frontend/src/App.vue @@ -0,0 +1,11 @@ + + + diff --git a/vulfocus-frontend/src/api/container.js b/vulfocus-frontend/src/api/container.js new file mode 100644 index 00000000..cb6dccaa --- /dev/null +++ b/vulfocus-frontend/src/api/container.js @@ -0,0 +1,31 @@ +import request from '@/utils/request' + +export function containerList(flag) { + return request({ + url: '/container/?flag='+flag, + method: 'get' + }) +} + +export function containerStop(id) { + return request({ + url: '/container/'+id+'/stop/?flag=list', + method: 'get' + }) +} + +export function containerStart(id) { + return request({ + url: '/container/'+id+'/start/?flag=list', + method: 'get' + }) +} + +export function containerDel(id) { + return request({ + url: '/container/'+id+'/delete/?flag=list', + method: 'delete' + }) +} + + diff --git a/vulfocus-frontend/src/api/docker.js b/vulfocus-frontend/src/api/docker.js new file mode 100644 index 00000000..8a666ba5 --- /dev/null +++ b/vulfocus-frontend/src/api/docker.js @@ -0,0 +1,68 @@ +import request from '@/utils/request' + +export function ImgList(data) { + if(data === undefined){ + data = "" + } + return request({ + url: '/images/?query='+data, + method: 'get' + }) +} + +export function ContainerINFO(id) { + return request({ + url: '/images/'+id, + method: 'get' + }) +} +export function ContainerSTATUS(id) { + return request({ + url: '/container/'+id+'/status/', + method: 'get' + }) +} + + +export function ContainerSTART(id) { + return request({ + url: '/images/'+id+'/start/', + method: 'get' + }) +} + +export function ContainerHisory() { + return request({ + url: '/container/', + method: 'get', + }) +} + +export function ContainerDelete(id) { + return request({ + url: '/container/'+id+'/delete/', + method: 'delete' + }) +} + +export function ContainerStop(id) { + return request({ + url: '/container/'+id+'/stop/', + method: 'get' + }) +} + +export function SubFlag(id,flag) { + return request({ + url: '/container/'+id+'/flag/?flag='+flag, + method: 'get', + }) +} + +export function ContainerStart(id) { + return request({ + url: '/container/'+id+'/start/', + method: 'get' + }) +} + diff --git a/vulfocus-frontend/src/api/image.js b/vulfocus-frontend/src/api/image.js new file mode 100644 index 00000000..16aa91e3 --- /dev/null +++ b/vulfocus-frontend/src/api/image.js @@ -0,0 +1,19 @@ +import request from '@/utils/request' + +export function ImageAdd(data) { + return request({ + url: '/images/', + method: 'post', + headers: { + 'Content-Type': 'multipart/form-data' + }, + data + }) +} + +export function ImageDelete(id) { + return request({ + url: '/images/'+id+'/', + method: 'DELETE', + }) +} diff --git a/vulfocus-frontend/src/api/log.js b/vulfocus-frontend/src/api/log.js new file mode 100644 index 00000000..2a785a2f --- /dev/null +++ b/vulfocus-frontend/src/api/log.js @@ -0,0 +1,8 @@ +import request from '@/utils/request' + +export function LogList() { + return request({ + url: '/syslog/', + method: 'get' + }) +} diff --git a/vulfocus-frontend/src/api/table.js b/vulfocus-frontend/src/api/table.js new file mode 100644 index 00000000..e29c2943 --- /dev/null +++ b/vulfocus-frontend/src/api/table.js @@ -0,0 +1,9 @@ +import request from '@/utils/request' + +export function getList(params) { + return request({ + url: '/table/list', + method: 'get', + params + }) +} diff --git a/vulfocus-frontend/src/api/user.js b/vulfocus-frontend/src/api/user.js new file mode 100644 index 00000000..14381530 --- /dev/null +++ b/vulfocus-frontend/src/api/user.js @@ -0,0 +1,47 @@ +import request from '@/utils/request' + +export function login(data) { + return request({ + url: '/user/login', + method: 'post', + data + }) +} + +export function userList() { + return request({ + url: '/user/', + method: 'get' + }) +} + +export function userChangePwd(data,id) { + return request({ + url: '/user/'+id+'/', + method: 'PUT', + data + }) +} + +export function getInfo() { + return request({ + url: '/user/info', + method: 'get' + // params: { token } + }) +} + +export function logout() { + return request({ + url: '/user/logout', + method: 'get' + }) +} + +export function register(data) { + return request({ + url: '/user/register/', + method: 'post', + data + }) +} diff --git a/vulfocus-frontend/src/assets/404_images/404.png b/vulfocus-frontend/src/assets/404_images/404.png new file mode 100644 index 00000000..3d8e2305 Binary files /dev/null and b/vulfocus-frontend/src/assets/404_images/404.png differ diff --git a/vulfocus-frontend/src/assets/404_images/404_cloud.png b/vulfocus-frontend/src/assets/404_images/404_cloud.png new file mode 100644 index 00000000..c6281d09 Binary files /dev/null and b/vulfocus-frontend/src/assets/404_images/404_cloud.png differ diff --git a/vulfocus-frontend/src/assets/bmh.jpg b/vulfocus-frontend/src/assets/bmh.jpg new file mode 100644 index 00000000..5c26d7d0 Binary files /dev/null and b/vulfocus-frontend/src/assets/bmh.jpg differ diff --git a/vulfocus-frontend/src/assets/bmh.png b/vulfocus-frontend/src/assets/bmh.png new file mode 100644 index 00000000..959fbfba Binary files /dev/null and b/vulfocus-frontend/src/assets/bmh.png differ diff --git a/vulfocus-frontend/src/components/Breadcrumb/index.vue b/vulfocus-frontend/src/components/Breadcrumb/index.vue new file mode 100644 index 00000000..29f9a04c --- /dev/null +++ b/vulfocus-frontend/src/components/Breadcrumb/index.vue @@ -0,0 +1,78 @@ + + + + + diff --git a/vulfocus-frontend/src/components/Hamburger/index.vue b/vulfocus-frontend/src/components/Hamburger/index.vue new file mode 100644 index 00000000..368b0021 --- /dev/null +++ b/vulfocus-frontend/src/components/Hamburger/index.vue @@ -0,0 +1,44 @@ + + + + + diff --git a/vulfocus-frontend/src/components/PanThumb/index.vue b/vulfocus-frontend/src/components/PanThumb/index.vue new file mode 100644 index 00000000..1bcf4170 --- /dev/null +++ b/vulfocus-frontend/src/components/PanThumb/index.vue @@ -0,0 +1,142 @@ + + + + + diff --git a/vulfocus-frontend/src/components/SvgIcon/index.vue b/vulfocus-frontend/src/components/SvgIcon/index.vue new file mode 100644 index 00000000..b07ded2a --- /dev/null +++ b/vulfocus-frontend/src/components/SvgIcon/index.vue @@ -0,0 +1,62 @@ + + + + + diff --git a/vulfocus-frontend/src/icons/index.js b/vulfocus-frontend/src/icons/index.js new file mode 100644 index 00000000..2c6b309c --- /dev/null +++ b/vulfocus-frontend/src/icons/index.js @@ -0,0 +1,9 @@ +import Vue from 'vue' +import SvgIcon from '@/components/SvgIcon'// svg component + +// register globally +Vue.component('svg-icon', SvgIcon) + +const req = require.context('./svg', false, /\.svg$/) +const requireAll = requireContext => requireContext.keys().map(requireContext) +requireAll(req) diff --git a/vulfocus-frontend/src/icons/svg/bug.svg b/vulfocus-frontend/src/icons/svg/bug.svg new file mode 100644 index 00000000..05a150dc --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/bug.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/dashboard.svg b/vulfocus-frontend/src/icons/svg/dashboard.svg new file mode 100644 index 00000000..5317d370 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/dashboard.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/example.svg b/vulfocus-frontend/src/icons/svg/example.svg new file mode 100644 index 00000000..46f42b53 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/example.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/eye-open.svg b/vulfocus-frontend/src/icons/svg/eye-open.svg new file mode 100644 index 00000000..88dcc98e --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/eye-open.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/eye.svg b/vulfocus-frontend/src/icons/svg/eye.svg new file mode 100644 index 00000000..16ed2d87 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/eye.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/form.svg b/vulfocus-frontend/src/icons/svg/form.svg new file mode 100644 index 00000000..dcbaa185 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/form.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/link.svg b/vulfocus-frontend/src/icons/svg/link.svg new file mode 100644 index 00000000..48197ba4 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/link.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/nested.svg b/vulfocus-frontend/src/icons/svg/nested.svg new file mode 100644 index 00000000..06713a86 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/nested.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/password.svg b/vulfocus-frontend/src/icons/svg/password.svg new file mode 100644 index 00000000..e291d85d --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/password.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/table.svg b/vulfocus-frontend/src/icons/svg/table.svg new file mode 100644 index 00000000..0e3dc9de --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/table.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/tree.svg b/vulfocus-frontend/src/icons/svg/tree.svg new file mode 100644 index 00000000..dd4b7dd2 --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/tree.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svg/user.svg b/vulfocus-frontend/src/icons/svg/user.svg new file mode 100644 index 00000000..0ba0716a --- /dev/null +++ b/vulfocus-frontend/src/icons/svg/user.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vulfocus-frontend/src/icons/svgo.yml b/vulfocus-frontend/src/icons/svgo.yml new file mode 100644 index 00000000..d11906ae --- /dev/null +++ b/vulfocus-frontend/src/icons/svgo.yml @@ -0,0 +1,22 @@ +# replace default config + +# multipass: true +# full: true + +plugins: + + # - name + # + # or: + # - name: false + # - name: true + # + # or: + # - name: + # param1: 1 + # param2: 2 + +- removeAttrs: + attrs: + - 'fill' + - 'fill-rule' diff --git a/vulfocus-frontend/src/layout/components/AppMain.vue b/vulfocus-frontend/src/layout/components/AppMain.vue new file mode 100644 index 00000000..d08d197e --- /dev/null +++ b/vulfocus-frontend/src/layout/components/AppMain.vue @@ -0,0 +1,55 @@ + + + + + + + diff --git a/vulfocus-frontend/src/layout/components/Navbar.vue b/vulfocus-frontend/src/layout/components/Navbar.vue new file mode 100644 index 00000000..ac981be2 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Navbar.vue @@ -0,0 +1,140 @@ + + + + + diff --git a/vulfocus-frontend/src/layout/components/Sidebar/FixiOSBug.js b/vulfocus-frontend/src/layout/components/Sidebar/FixiOSBug.js new file mode 100644 index 00000000..bc14856f --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/FixiOSBug.js @@ -0,0 +1,26 @@ +export default { + computed: { + device() { + return this.$store.state.app.device + } + }, + mounted() { + // In order to fix the click on menu on the ios device will trigger the mouseleave bug + // https://github.com/PanJiaChen/vue-element-admin/issues/1135 + this.fixBugIniOS() + }, + methods: { + fixBugIniOS() { + const $subMenu = this.$refs.subMenu + if ($subMenu) { + const handleMouseleave = $subMenu.handleMouseleave + $subMenu.handleMouseleave = (e) => { + if (this.device === 'mobile') { + return + } + handleMouseleave(e) + } + } + } + } +} diff --git a/vulfocus-frontend/src/layout/components/Sidebar/Item.vue b/vulfocus-frontend/src/layout/components/Sidebar/Item.vue new file mode 100644 index 00000000..b515f615 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/Item.vue @@ -0,0 +1,29 @@ + diff --git a/vulfocus-frontend/src/layout/components/Sidebar/Link.vue b/vulfocus-frontend/src/layout/components/Sidebar/Link.vue new file mode 100644 index 00000000..eb4dd107 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/Link.vue @@ -0,0 +1,36 @@ + + + + diff --git a/vulfocus-frontend/src/layout/components/Sidebar/Logo.vue b/vulfocus-frontend/src/layout/components/Sidebar/Logo.vue new file mode 100644 index 00000000..040fab64 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/Logo.vue @@ -0,0 +1,82 @@ + + + + + diff --git a/vulfocus-frontend/src/layout/components/Sidebar/SidebarItem.vue b/vulfocus-frontend/src/layout/components/Sidebar/SidebarItem.vue new file mode 100644 index 00000000..2d49dd87 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/SidebarItem.vue @@ -0,0 +1,95 @@ + + + diff --git a/vulfocus-frontend/src/layout/components/Sidebar/index.vue b/vulfocus-frontend/src/layout/components/Sidebar/index.vue new file mode 100644 index 00000000..890affd9 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/Sidebar/index.vue @@ -0,0 +1,59 @@ + + + diff --git a/vulfocus-frontend/src/layout/components/index.js b/vulfocus-frontend/src/layout/components/index.js new file mode 100644 index 00000000..97ee3cd1 --- /dev/null +++ b/vulfocus-frontend/src/layout/components/index.js @@ -0,0 +1,3 @@ +export { default as Navbar } from './Navbar' +export { default as Sidebar } from './Sidebar' +export { default as AppMain } from './AppMain' diff --git a/vulfocus-frontend/src/layout/index.vue b/vulfocus-frontend/src/layout/index.vue new file mode 100644 index 00000000..0565e3aa --- /dev/null +++ b/vulfocus-frontend/src/layout/index.vue @@ -0,0 +1,94 @@ + + + + + diff --git a/vulfocus-frontend/src/layout/mixin/ResizeHandler.js b/vulfocus-frontend/src/layout/mixin/ResizeHandler.js new file mode 100644 index 00000000..e8d0df8c --- /dev/null +++ b/vulfocus-frontend/src/layout/mixin/ResizeHandler.js @@ -0,0 +1,45 @@ +import store from '@/store' + +const { body } = document +const WIDTH = 992 // refer to Bootstrap's responsive design + +export default { + watch: { + $route(route) { + if (this.device === 'mobile' && this.sidebar.opened) { + store.dispatch('app/closeSideBar', { withoutAnimation: false }) + } + } + }, + beforeMount() { + window.addEventListener('resize', this.$_resizeHandler) + }, + beforeDestroy() { + window.removeEventListener('resize', this.$_resizeHandler) + }, + mounted() { + const isMobile = this.$_isMobile() + if (isMobile) { + store.dispatch('app/toggleDevice', 'mobile') + store.dispatch('app/closeSideBar', { withoutAnimation: true }) + } + }, + methods: { + // use $_ for mixins properties + // https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential + $_isMobile() { + const rect = body.getBoundingClientRect() + return rect.width - 1 < WIDTH + }, + $_resizeHandler() { + if (!document.hidden) { + const isMobile = this.$_isMobile() + store.dispatch('app/toggleDevice', isMobile ? 'mobile' : 'desktop') + + if (isMobile) { + store.dispatch('app/closeSideBar', { withoutAnimation: true }) + } + } + } + } +} diff --git a/vulfocus-frontend/src/main.js b/vulfocus-frontend/src/main.js new file mode 100644 index 00000000..a555ead9 --- /dev/null +++ b/vulfocus-frontend/src/main.js @@ -0,0 +1,45 @@ +import Vue from 'vue' + +import 'normalize.css/normalize.css' // A modern alternative to CSS resets + +import ElementUI from 'element-ui' +import 'element-ui/lib/theme-chalk/index.css' +import locale from 'element-ui/lib/locale/lang/en' // lang i18n + +import '@/styles/index.scss' // global css + +import App from './App' +import store from './store' +import router from './router' + + +import { GoodWizard } from 'vue-good-wizard' + +import '@/icons' // icon +import '@/permission' // permission control + +/** + * If you don't want to use mock-server + * you want to use MockJs for mock api + * you can execute: mockXHR() + * + * Currently MockJs will be used in the production environment, + * please remove it before going online! ! ! + */ +// import { mockXHR } from '../mock' +// if (process.env.NODE_ENV === 'production') { +// mockXHR() +// } + +// set ElementUI lang to EN +Vue.use(ElementUI, { locale }) + + +Vue.config.productionTip = false + +new Vue({ + el: '#app', + router, + store, + render: h => h(App) +}) diff --git a/vulfocus-frontend/src/permission.js b/vulfocus-frontend/src/permission.js new file mode 100644 index 00000000..33323767 --- /dev/null +++ b/vulfocus-frontend/src/permission.js @@ -0,0 +1,85 @@ +import router from './router' +import store from './store' +import { Message } from 'element-ui' +import NProgress from 'nprogress' // progress bar +import 'nprogress/nprogress.css' // progress bar style +import { getToken } from '@/utils/auth' // get token from cookie +import getPageTitle from '@/utils/get-page-title' + +NProgress.configure({ showSpinner: false }) // NProgress Configuration + +const whiteList = ['/login','/register'] // no redirect whitelist + +router.beforeEach(async(to, from, next) => { + // start progress bar + NProgress.start() + + // set page title + document.title = getPageTitle(to.meta.title) + + // determine whether the user has logged in + const hasToken = getToken() + + if (hasToken) { + if (to.path === '/login') { + // if is logged in, redirect to the home page + next({ path: '/' }) + NProgress.done() + } else { + const hasRoles = store.getters.roles && store.getters.roles.length > 0 + if(hasRoles){ + next() + }else{ + // const { roles } = await + try { + store.dispatch('user/getInfo').then(userInfo => { + let roles = userInfo.roles + store.dispatch('permission/generateRoutes', roles).then(accessRoutes => { + router.addRoutes(accessRoutes) + next({ ...to, replace: true }) + }) + }) + } catch (error) { + // remove token and go to login page to re-login + await store.dispatch('user/resetToken') + Message.error(error || 'Has Error') + next(`/login?redirect=${to.path}`) + NProgress.done() + } + } + /* + const hasGetUserInfo = store.getters.name + if (hasGetUserInfo) { + next() + } else { + try { + // get user info + await store.dispatch('user/getInfo') + next() + } catch (error) { + // remove token and go to login page to re-login + await store.dispatch('user/resetToken') + Message.error(error || 'Has Error') + next(`/login?redirect=${to.path}`) + NProgress.done() + } + }*/ + } + } else { + /* has no token*/ + + if (whiteList.indexOf(to.path) !== -1) { + // in the free login whitelist, go directly + next() + } else { + // other pages that do not have permission to access are redirected to the login page. + next(`/login?redirect=${to.path}`) + NProgress.done() + } + } +}) + +router.afterEach(() => { + // finish progress bar + NProgress.done() +}) diff --git a/vulfocus-frontend/src/router/index.js b/vulfocus-frontend/src/router/index.js new file mode 100644 index 00000000..779c81ed --- /dev/null +++ b/vulfocus-frontend/src/router/index.js @@ -0,0 +1,140 @@ +import Vue from 'vue' +import Router from 'vue-router' + +Vue.use(Router) + +/* Layout */ +import Layout from '@/layout' + +/** + * Note: sub-menu only appear when route children.length >= 1 + * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html + * + * hidden: true if set true, item will not show in the sidebar(default is false) + * alwaysShow: true if set true, will always show the root menu + * if not set alwaysShow, when item has more than one children route, + * it will becomes nested mode, otherwise not show the root menu + * redirect: noRedirect if set noRedirect will no redirect in the breadcrumb + * name:'router-name' the name is used by (must set!!!) + * meta : { + roles: ['admin','editor'] control the page roles (you can set multiple roles) + title: 'title' the name show in sidebar and breadcrumb (recommend set) + icon: 'svg-name' the icon show in the sidebar + breadcrumb: false if set false, the item will hidden in breadcrumb(default is true) + activeMenu: '/example/list' if set path, the sidebar will highlight the path you set + } + */ + +/** + * constantRoutes + * a base page that does not have permission requirements + * all roles can be accessed + */ +export const constantRoutes = [ + { + path: '/login', + component: () => import('@/views/login/index'), + hidden: true + }, + { + path: '/register', + component: () => import('@/views/register/index'), + hidden: false + }, + { + path: '/404', + component: () => import('@/views/404'), + hidden: true + }, + { + path: '/', + component: Layout, + redirect: '/dashboard', + children: [{ + path: 'dashboard', + affix: true, + name: 'Dashboard', + component: () => import('@/views/dashboard/index'), + meta: { title: '首页', icon: 'dashboard' } + }] + }, + { + path: '/profile', + component: Layout, + redirect: '/profile/index', + children: [ + { + path: 'index', + component: () => import('@/views/profile/index'), + name: 'Profile', + meta: { title: '用户', icon: 'user', noCache: true } + } + ] + } +] + +const createRouter = () => new Router({ + // mode: 'history', // require service support + scrollBehavior: () => ({ y: 0 }), + routes: constantRoutes +}) + +const router = createRouter() + +// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465 +export function resetRouter() { + const newRouter = createRouter() + router.matcher = newRouter.matcher // reset router +} + +export const asyncRoutes = [ + { + // 镜像管理 + path: '/image', + component: Layout, + redirect: '/image', + meta: {role: ['admin']}, + children: [{ + path: 'image', + affix: true, + name: 'image', + component: () => import('@/views/image/index'), + meta: { title: '镜像管理', icon: 'table' , role: ['admin']} + }] + }, + + { + // 账户管理 + path: '/manager', + component: Layout, + redirect: '/manager', + meta: {role: ['admin'],title: "账户管理", icon: 'table'}, + children: [ + { + path: 'user', + affix: true, + name: 'user', + component: () => import("@/views/manager/user"), + meta: { title: '用户信息管理', icon: 'table' , role: ['admin']} + }, + { + path: 'images', + affix: true, + name: 'images', + component: () => import("@/views/manager/images"), + meta: { title: '使用靶场管理', icon: 'table' , role: ['admin']} + }, + { + path: 'log', + affix: true, + name: 'log', + component: () => import("@/views/manager/log"), + meta: { title: '操作日志记录', icon: 'table' , role: ['admin']} + } + ] + }, + { path: '*', redirect: '/404', hidden: true } +] + + +export default router diff --git a/vulfocus-frontend/src/settings.js b/vulfocus-frontend/src/settings.js new file mode 100644 index 00000000..5e3a0911 --- /dev/null +++ b/vulfocus-frontend/src/settings.js @@ -0,0 +1,16 @@ +module.exports = { + + title: 'vulfocus', + + /** + * @type {boolean} true | false + * @description Whether fix the header + */ + fixedHeader: true, + + /** + * @type {boolean} true | false + * @description Whether show the logo in sidebar + */ + sidebarLogo: false +} diff --git a/vulfocus-frontend/src/store/getters.js b/vulfocus-frontend/src/store/getters.js new file mode 100644 index 00000000..3869459c --- /dev/null +++ b/vulfocus-frontend/src/store/getters.js @@ -0,0 +1,11 @@ +const getters = { + sidebar: state => state.app.sidebar, + device: state => state.app.device, + token: state => state.user.token, + avatar: state => state.user.avatar, + rank: state => state.user.rank, + name: state => state.user.name, + roles: state => state.user.roles, + permission_routes: state => state.permission.routes +} +export default getters diff --git a/vulfocus-frontend/src/store/index.js b/vulfocus-frontend/src/store/index.js new file mode 100644 index 00000000..f3aa58f7 --- /dev/null +++ b/vulfocus-frontend/src/store/index.js @@ -0,0 +1,21 @@ +import Vue from 'vue' +import Vuex from 'vuex' +import getters from './getters' +import app from './modules/app' +import settings from './modules/settings' +import user from './modules/user' +import permission from './modules/permission' + +Vue.use(Vuex) + +const store = new Vuex.Store({ + modules: { + app, + settings, + user, + permission, + }, + getters +}) + +export default store diff --git a/vulfocus-frontend/src/store/modules/app.js b/vulfocus-frontend/src/store/modules/app.js new file mode 100644 index 00000000..7ea7e332 --- /dev/null +++ b/vulfocus-frontend/src/store/modules/app.js @@ -0,0 +1,48 @@ +import Cookies from 'js-cookie' + +const state = { + sidebar: { + opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true, + withoutAnimation: false + }, + device: 'desktop' +} + +const mutations = { + TOGGLE_SIDEBAR: state => { + state.sidebar.opened = !state.sidebar.opened + state.sidebar.withoutAnimation = false + if (state.sidebar.opened) { + Cookies.set('sidebarStatus', 1) + } else { + Cookies.set('sidebarStatus', 0) + } + }, + CLOSE_SIDEBAR: (state, withoutAnimation) => { + Cookies.set('sidebarStatus', 0) + state.sidebar.opened = false + state.sidebar.withoutAnimation = withoutAnimation + }, + TOGGLE_DEVICE: (state, device) => { + state.device = device + } +} + +const actions = { + toggleSideBar({ commit }) { + commit('TOGGLE_SIDEBAR') + }, + closeSideBar({ commit }, { withoutAnimation }) { + commit('CLOSE_SIDEBAR', withoutAnimation) + }, + toggleDevice({ commit }, device) { + commit('TOGGLE_DEVICE', device) + } +} + +export default { + namespaced: true, + state, + mutations, + actions +} diff --git a/vulfocus-frontend/src/store/modules/permission.js b/vulfocus-frontend/src/store/modules/permission.js new file mode 100644 index 00000000..db42637c --- /dev/null +++ b/vulfocus-frontend/src/store/modules/permission.js @@ -0,0 +1,71 @@ +import { asyncRoutes, constantRoutes } from '@/router' + +/** + * Use meta.role to determine if the current user has permission + * @param roles + * @param route + */ +function hasPermission(roles, route) { + if(route.meta == undefined){ + return true + } + if (route.meta.role.length > 0) { + return roles.some(role => route.meta.role.includes(role)) + } else { + return true + } +} + +/** + * Filter asynchronous routing tables by recursion + * @param routes asyncRoutes + * @param roles + */ +export function filterAsyncRoutes(routes, roles) { + const res = [] + routes.forEach(route => { + const tmp = { ...route } + let hasPer = hasPermission(roles, tmp) + if (hasPer) { + if (tmp.children) { + tmp.children = filterAsyncRoutes(tmp.children, roles) + } + res.push(tmp) + } + }) + return res +} + +const state = { + routes: [], + addRoutes: [] +} + +const mutations = { + SET_ROUTES: (state, routes) => { + state.addRoutes = routes + state.routes = constantRoutes.concat(routes) + } +} + +const actions = { + generateRoutes({ commit }, roles) { + return new Promise(resolve => { + let accessedRoutes + if (roles.includes('admin')) { + accessedRoutes = asyncRoutes // || [] + } else { + accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) + } + commit('SET_ROUTES', accessedRoutes) + resolve(accessedRoutes) + }) + } +} + +export default { + namespaced: true, + state, + mutations, + actions +} diff --git a/vulfocus-frontend/src/store/modules/settings.js b/vulfocus-frontend/src/store/modules/settings.js new file mode 100644 index 00000000..aab31a28 --- /dev/null +++ b/vulfocus-frontend/src/store/modules/settings.js @@ -0,0 +1,31 @@ +import defaultSettings from '@/settings' + +const { showSettings, fixedHeader, sidebarLogo } = defaultSettings + +const state = { + showSettings: showSettings, + fixedHeader: fixedHeader, + sidebarLogo: sidebarLogo +} + +const mutations = { + CHANGE_SETTING: (state, { key, value }) => { + if (state.hasOwnProperty(key)) { + state[key] = value + } + } +} + +const actions = { + changeSetting({ commit }, data) { + commit('CHANGE_SETTING', data) + } +} + +export default { + namespaced: true, + state, + mutations, + actions +} + diff --git a/vulfocus-frontend/src/store/modules/user.js b/vulfocus-frontend/src/store/modules/user.js new file mode 100644 index 00000000..7b57a595 --- /dev/null +++ b/vulfocus-frontend/src/store/modules/user.js @@ -0,0 +1,112 @@ +import { login, logout, getInfo,register } from '@/api/user' +import { getToken, setToken, removeToken } from '@/utils/auth' +import { resetRouter } from '@/router' +import { Message } from 'element-ui' + +const state = { + token: getToken(), + name: '', + avatar: '', + rank:'', + email:'', + roles: [], +} + +const mutations = { + SET_TOKEN: (state, token) => { + state.token = token + }, + SET_NAME: (state, name) => { + state.name = name + }, + SET_AVATAR: (state, avatar) => { + state.avatar = avatar + }, + SET_RANK: (state, rank) => { + state.rank = rank + }, + SET_ROLES: (state, roles) => { + state.roles = roles + } +} + +const actions = { + // user login + login({ commit }, userInfo) { + const { username, password } = userInfo + return new Promise((resolve, reject) => { + login({ username: username.trim(), password: password }).then(response => { + const { data } = response + commit('SET_TOKEN', data.token) + setToken(data.token) + resolve() + }).catch(error => { + reject(error) + }) + }) + }, + register({ commit }, userInfo) { + const { name,pass,checkPass,email} = userInfo + return new Promise((resolve, reject) => { + register({ username: name.trim(), password: pass ,email:email}).then(response => { + resolve(response) + }).catch(error => { + reject(error) + }) + }) + }, + + // get user info + getInfo({ commit, state }) { + return new Promise((resolve, reject) => { + getInfo(state.token).then(response => { + const { data } = response + if (!data) { + reject('Verification failed, please Login again.') + } + const { name, avatar,rank, roles } = data + commit('SET_NAME', name) + commit('SET_AVATAR', avatar) + commit('SET_RANK', rank) + commit("SET_ROLES", roles) + resolve(data) + }).catch(error => { + reject(error) + }) + }) + }, + + // user logout + logout({ commit, state }) { + return new Promise((resolve, reject) => { + logout(state.token).then(() => { + commit('SET_TOKEN', '') + removeToken() + commit('SET_ROLES', []) + resetRouter() + resolve() + }).catch(error => { + reject(error) + }) + }) + }, + + // remove token + resetToken({ commit }) { + return new Promise(resolve => { + commit('SET_TOKEN', '') + commit('SET_ROLES', []) + removeToken() + console.log("删除COOKIE") + resolve() + }) + } +} + +export default { + namespaced: true, + state, + mutations, + actions +} + diff --git a/vulfocus-frontend/src/styles/element-ui.scss b/vulfocus-frontend/src/styles/element-ui.scss new file mode 100644 index 00000000..6af3bfde --- /dev/null +++ b/vulfocus-frontend/src/styles/element-ui.scss @@ -0,0 +1,44 @@ +// cover some element-ui styles + +.el-breadcrumb__inner, +.el-breadcrumb__inner a { + font-weight: 400 !important; +} + +.el-upload { + input[type="file"] { + display: none !important; + } +} + +.el-upload__input { + display: none; +} + + +// to fixed https://github.com/ElemeFE/element/issues/2461 +.el-dialog { + transform: none; + left: 0; + position: relative; + margin: 0 auto; +} + +// refine element ui upload +.upload-container { + .el-upload { + width: 100%; + + .el-upload-dragger { + width: 100%; + height: 200px; + } + } +} + +// dropdown +.el-dropdown-menu { + a { + display: block + } +} diff --git a/vulfocus-frontend/src/styles/index.scss b/vulfocus-frontend/src/styles/index.scss new file mode 100644 index 00000000..3b4da517 --- /dev/null +++ b/vulfocus-frontend/src/styles/index.scss @@ -0,0 +1,65 @@ +@import './variables.scss'; +@import './mixin.scss'; +@import './transition.scss'; +@import './element-ui.scss'; +@import './sidebar.scss'; + +body { + height: 100%; + -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; + font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif; +} + +label { + font-weight: 700; +} + +html { + height: 100%; + box-sizing: border-box; +} + +#app { + height: 100%; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +a:focus, +a:active { + outline: none; +} + +a, +a:focus, +a:hover { + cursor: pointer; + color: inherit; + text-decoration: none; +} + +div:focus { + outline: none; +} + +.clearfix { + &:after { + visibility: hidden; + display: block; + font-size: 0; + content: " "; + clear: both; + height: 0; + } +} + +// main-container global css +.app-container { + padding: 20px; +} diff --git a/vulfocus-frontend/src/styles/mixin.scss b/vulfocus-frontend/src/styles/mixin.scss new file mode 100644 index 00000000..36b74bbd --- /dev/null +++ b/vulfocus-frontend/src/styles/mixin.scss @@ -0,0 +1,28 @@ +@mixin clearfix { + &:after { + content: ""; + display: table; + clear: both; + } +} + +@mixin scrollBar { + &::-webkit-scrollbar-track-piece { + background: #d3dce6; + } + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-thumb { + background: #99a9bf; + border-radius: 20px; + } +} + +@mixin relative { + position: relative; + width: 100%; + height: 100%; +} diff --git a/vulfocus-frontend/src/styles/sidebar.scss b/vulfocus-frontend/src/styles/sidebar.scss new file mode 100644 index 00000000..3dad4c39 --- /dev/null +++ b/vulfocus-frontend/src/styles/sidebar.scss @@ -0,0 +1,209 @@ +#app { + + .main-container { + min-height: 100%; + transition: margin-left .28s; + margin-left: $sideBarWidth; + position: relative; + } + + .sidebar-container { + transition: width 0.28s; + width: $sideBarWidth !important; + background-color: $menuBg; + height: 100%; + position: fixed; + font-size: 0px; + top: 0; + bottom: 0; + left: 0; + z-index: 1001; + overflow: hidden; + + // reset element-ui css + .horizontal-collapse-transition { + transition: 0s width ease-in-out, 0s padding-left ease-in-out, 0s padding-right ease-in-out; + } + + .scrollbar-wrapper { + overflow-x: hidden !important; + } + + .el-scrollbar__bar.is-vertical { + right: 0px; + } + + .el-scrollbar { + height: 100%; + } + + &.has-logo { + .el-scrollbar { + height: calc(100% - 50px); + } + } + + .is-horizontal { + display: none; + } + + a { + display: inline-block; + width: 100%; + overflow: hidden; + } + + .svg-icon { + margin-right: 16px; + } + + .el-menu { + border: none; + height: 100%; + width: 100% !important; + } + + // menu hover + .submenu-title-noDropdown, + .el-submenu__title { + &:hover { + background-color: $menuHover !important; + } + } + + .is-active>.el-submenu__title { + color: $subMenuActiveText !important; + } + + & .nest-menu .el-submenu>.el-submenu__title, + & .el-submenu .el-menu-item { + min-width: $sideBarWidth !important; + background-color: $subMenuBg !important; + + &:hover { + background-color: $subMenuHover !important; + } + } + } + + .hideSidebar { + .sidebar-container { + width: 54px !important; + } + + .main-container { + margin-left: 54px; + } + + .submenu-title-noDropdown { + padding: 0 !important; + position: relative; + + .el-tooltip { + padding: 0 !important; + + .svg-icon { + margin-left: 20px; + } + } + } + + .el-submenu { + overflow: hidden; + + &>.el-submenu__title { + padding: 0 !important; + + .svg-icon { + margin-left: 20px; + } + + .el-submenu__icon-arrow { + display: none; + } + } + } + + .el-menu--collapse { + .el-submenu { + &>.el-submenu__title { + &>span { + height: 0; + width: 0; + overflow: hidden; + visibility: hidden; + display: inline-block; + } + } + } + } + } + + .el-menu--collapse .el-menu .el-submenu { + min-width: $sideBarWidth !important; + } + + // mobile responsive + .mobile { + .main-container { + margin-left: 0px; + } + + .sidebar-container { + transition: transform .28s; + width: $sideBarWidth !important; + } + + &.hideSidebar { + .sidebar-container { + pointer-events: none; + transition-duration: 0.3s; + transform: translate3d(-$sideBarWidth, 0, 0); + } + } + } + + .withoutAnimation { + + .main-container, + .sidebar-container { + transition: none; + } + } +} + +// when menu collapsed +.el-menu--vertical { + &>.el-menu { + .svg-icon { + margin-right: 16px; + } + } + + .nest-menu .el-submenu>.el-submenu__title, + .el-menu-item { + &:hover { + // you can use $subMenuHover + background-color: $menuHover !important; + } + } + + // the scroll bar appears when the subMenu is too long + >.el-menu--popup { + max-height: 100vh; + overflow-y: auto; + + &::-webkit-scrollbar-track-piece { + background: #d3dce6; + } + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-thumb { + background: #99a9bf; + border-radius: 20px; + } + } +} diff --git a/vulfocus-frontend/src/styles/transition.scss b/vulfocus-frontend/src/styles/transition.scss new file mode 100644 index 00000000..4cb27cc8 --- /dev/null +++ b/vulfocus-frontend/src/styles/transition.scss @@ -0,0 +1,48 @@ +// global transition css + +/* fade */ +.fade-enter-active, +.fade-leave-active { + transition: opacity 0.28s; +} + +.fade-enter, +.fade-leave-active { + opacity: 0; +} + +/* fade-transform */ +.fade-transform-leave-active, +.fade-transform-enter-active { + transition: all .5s; +} + +.fade-transform-enter { + opacity: 0; + transform: translateX(-30px); +} + +.fade-transform-leave-to { + opacity: 0; + transform: translateX(30px); +} + +/* breadcrumb transition */ +.breadcrumb-enter-active, +.breadcrumb-leave-active { + transition: all .5s; +} + +.breadcrumb-enter, +.breadcrumb-leave-active { + opacity: 0; + transform: translateX(20px); +} + +.breadcrumb-move { + transition: all .5s; +} + +.breadcrumb-leave-active { + position: absolute; +} diff --git a/vulfocus-frontend/src/styles/variables.scss b/vulfocus-frontend/src/styles/variables.scss new file mode 100644 index 00000000..be557726 --- /dev/null +++ b/vulfocus-frontend/src/styles/variables.scss @@ -0,0 +1,25 @@ +// sidebar +$menuText:#bfcbd9; +$menuActiveText:#409EFF; +$subMenuActiveText:#f4f4f5; //https://github.com/ElemeFE/element/issues/12951 + +$menuBg:#304156; +$menuHover:#263445; + +$subMenuBg:#1f2d3d; +$subMenuHover:#001528; + +$sideBarWidth: 210px; + +// the :export directive is the magic sauce for webpack +// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass +:export { + menuText: $menuText; + menuActiveText: $menuActiveText; + subMenuActiveText: $subMenuActiveText; + menuBg: $menuBg; + menuHover: $menuHover; + subMenuBg: $subMenuBg; + subMenuHover: $subMenuHover; + sideBarWidth: $sideBarWidth; +} diff --git a/vulfocus-frontend/src/utils/auth.js b/vulfocus-frontend/src/utils/auth.js new file mode 100644 index 00000000..059af188 --- /dev/null +++ b/vulfocus-frontend/src/utils/auth.js @@ -0,0 +1,15 @@ +import Cookies from 'js-cookie' + +const TokenKey = 'vue_admin_template_token' + +export function getToken() { + return Cookies.get(TokenKey) +} + +export function setToken(token) { + return Cookies.set(TokenKey, token) +} + +export function removeToken() { + return Cookies.remove(TokenKey) +} diff --git a/vulfocus-frontend/src/utils/get-page-title.js b/vulfocus-frontend/src/utils/get-page-title.js new file mode 100644 index 00000000..a6de99dd --- /dev/null +++ b/vulfocus-frontend/src/utils/get-page-title.js @@ -0,0 +1,10 @@ +import defaultSettings from '@/settings' + +const title = defaultSettings.title || 'Vue Admin Template' + +export default function getPageTitle(pageTitle) { + if (pageTitle) { + return `${pageTitle} - ${title}` + } + return `${title}` +} diff --git a/vulfocus-frontend/src/utils/index.js b/vulfocus-frontend/src/utils/index.js new file mode 100644 index 00000000..cd14bd5e --- /dev/null +++ b/vulfocus-frontend/src/utils/index.js @@ -0,0 +1,110 @@ +/** + * Created by PanJiaChen on 16/11/18. + */ + +/** + * Parse the time to string + * @param {(Object|string|number)} time + * @param {string} cFormat + * @returns {string} + */ +export function parseTime(time, cFormat) { + if (arguments.length === 0) { + return null + } + const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' + let date + if (typeof time === 'object') { + date = time + } else { + if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { + time = parseInt(time) + } + if ((typeof time === 'number') && (time.toString().length === 10)) { + time = time * 1000 + } + date = new Date(time) + } + const formatObj = { + y: date.getFullYear(), + m: date.getMonth() + 1, + d: date.getDate(), + h: date.getHours(), + i: date.getMinutes(), + s: date.getSeconds(), + a: date.getDay() + } + const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { + let value = formatObj[key] + // Note: getDay() returns 0 on Sunday + if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } + if (result.length > 0 && value < 10) { + value = '0' + value + } + return value || 0 + }) + return time_str +} + +/** + * @param {number} time + * @param {string} option + * @returns {string} + */ +export function formatTime(time, option) { + if (('' + time).length === 10) { + time = parseInt(time) * 1000 + } else { + time = +time + } + const d = new Date(time) + const now = Date.now() + + const diff = (now - d) / 1000 + + if (diff < 30) { + return '刚刚' + } else if (diff < 3600) { + // less 1 hour + return Math.ceil(diff / 60) + '分钟前' + } else if (diff < 3600 * 24) { + return Math.ceil(diff / 3600) + '小时前' + } else if (diff < 3600 * 24 * 2) { + return '1天前' + } + if (option) { + return parseTime(time, option) + } else { + return ( + d.getMonth() + + 1 + + '月' + + d.getDate() + + '日' + + d.getHours() + + '时' + + d.getMinutes() + + '分' + ) + } +} + +/** + * @param {string} url + * @returns {Object} + */ +export function param2Obj(url) { + const search = url.split('?')[1] + if (!search) { + return {} + } + return JSON.parse( + '{"' + + decodeURIComponent(search) + .replace(/"/g, '\\"') + .replace(/&/g, '","') + .replace(/=/g, '":"') + .replace(/\+/g, ' ') + + '"}' + ) +} diff --git a/vulfocus-frontend/src/utils/request.js b/vulfocus-frontend/src/utils/request.js new file mode 100644 index 00000000..fd3da412 --- /dev/null +++ b/vulfocus-frontend/src/utils/request.js @@ -0,0 +1,117 @@ +import axios from 'axios' +import { MessageBox, Message } from 'element-ui' +import store from '@/store' +import { getToken } from '@/utils/auth' + +// create an axios instance +const service = axios.create({ + baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url + // withCredentials: true, // send cookies when cross-domain requests + timeout: 600000 // request timeout +}) + +// request interceptor +service.interceptors.request.use( + config => { + // do something before request is sent + + if (store.getters.token) { + // let each request carry token + // ['X-Token'] is a custom headers key + // please modify it according to the actual situation + config.headers['Authorization'] = "BMH "+getToken() + } + return config + }, + error => { + // do something with request error + console.log(error) // for debug + return Promise.reject(error) + } +) + +// response interceptor +service.interceptors.response.use( + /** + * If you want to get http information such as headers or status + * Please return response => response + */ + + /** + * Determine the request status by custom code + * Here is just an example + * You can also judge the status by HTTP Status Code + */ + response => { + const res = response + console.log("response -->"+ response) + + // if the custom code is not 20000, it is judged as an error. + if (res.status > 300) { + // Message({ + // message: 'Error', + // type: 'error', + // duration: 5 * 1000 + // }) + if (res.status === 500 || res.status === 401 || res.status === 403) { + // to re-login + MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', { + confirmButtonText: 'Re-Login', + cancelButtonText: 'Cancel', + type: 'warning' + }).then(() => { + if(res.status === 401){ + store.dispatch('user/resetToken').then(() => { + location.reload() + }) + } + /** + * else{ + this.$message({ + type: 'success', + message: res.data.data + }) + } + */ + }) + } + return Promise.reject(new Error( 'Error')) + } else { + return res + } + }, + error => { + let response = error.response + console.log(response) + let status = response.status + // data + let data = response.data + let errorMsg = error.toString(); + if(status === 401 || errorMsg.indexOf("status code 401") > 0){ + store.dispatch('user/resetToken').then(() => { + location.reload() + }) + }else if(status === 400){ + if(data["non_field_errors"] != null){ + errorMsg = data["non_field_errors"][0] + }else if(data["username"] != null ){ + errorMsg = data["username"][0] + }else if(data["email"] != null ){ + errorMsg = data["email"][0] + } + }else if(status === 500){ + errorMsg = "服务器内部错误,请联系管理员" + }else if(status === 202){ + errorMsg = "端口无效" + } + // || errorMsg.indexOf("status code 403") > 0 || errorMsg.indexOf("status code 500") > 0 + Message({ + message: errorMsg, + type: "error", + duration: 5 * 1000 + }) + return Promise.reject(error) + } +) + +export default service diff --git a/vulfocus-frontend/src/utils/validate.js b/vulfocus-frontend/src/utils/validate.js new file mode 100644 index 00000000..8d962ad4 --- /dev/null +++ b/vulfocus-frontend/src/utils/validate.js @@ -0,0 +1,20 @@ +/** + * Created by PanJiaChen on 16/11/18. + */ + +/** + * @param {string} path + * @returns {Boolean} + */ +export function isExternal(path) { + return /^(https?:|mailto:|tel:)/.test(path) +} + +/** + * @param {string} str + * @returns {Boolean} + */ +export function validUsername(str) { + const valid_map = ['admin', 'editor'] + return valid_map.indexOf(str.trim()) >= 0 +} diff --git a/vulfocus-frontend/src/views/404.vue b/vulfocus-frontend/src/views/404.vue new file mode 100644 index 00000000..1791f55a --- /dev/null +++ b/vulfocus-frontend/src/views/404.vue @@ -0,0 +1,228 @@ + + + + + diff --git a/vulfocus-frontend/src/views/dashboard/components/Vullist.vue b/vulfocus-frontend/src/views/dashboard/components/Vullist.vue new file mode 100644 index 00000000..df983f93 --- /dev/null +++ b/vulfocus-frontend/src/views/dashboard/components/Vullist.vue @@ -0,0 +1,173 @@ + + + + + diff --git a/vulfocus-frontend/src/views/dashboard/index.vue b/vulfocus-frontend/src/views/dashboard/index.vue new file mode 100644 index 00000000..11fd66bc --- /dev/null +++ b/vulfocus-frontend/src/views/dashboard/index.vue @@ -0,0 +1,296 @@ + + + + + diff --git a/vulfocus-frontend/src/views/image/index.vue b/vulfocus-frontend/src/views/image/index.vue new file mode 100644 index 00000000..5ec3d1c8 --- /dev/null +++ b/vulfocus-frontend/src/views/image/index.vue @@ -0,0 +1,216 @@ + + + + + diff --git a/vulfocus-frontend/src/views/login/index.vue b/vulfocus-frontend/src/views/login/index.vue new file mode 100644 index 00000000..4e854105 --- /dev/null +++ b/vulfocus-frontend/src/views/login/index.vue @@ -0,0 +1,236 @@ + + + + + + + diff --git a/vulfocus-frontend/src/views/manager/images.vue b/vulfocus-frontend/src/views/manager/images.vue new file mode 100644 index 00000000..943e8973 --- /dev/null +++ b/vulfocus-frontend/src/views/manager/images.vue @@ -0,0 +1,150 @@ + + + + + diff --git a/vulfocus-frontend/src/views/manager/log.vue b/vulfocus-frontend/src/views/manager/log.vue new file mode 100644 index 00000000..5b926de5 --- /dev/null +++ b/vulfocus-frontend/src/views/manager/log.vue @@ -0,0 +1,80 @@ + + + + + diff --git a/vulfocus-frontend/src/views/manager/user.vue b/vulfocus-frontend/src/views/manager/user.vue new file mode 100644 index 00000000..68ed5731 --- /dev/null +++ b/vulfocus-frontend/src/views/manager/user.vue @@ -0,0 +1,107 @@ + + + + + diff --git a/vulfocus-frontend/src/views/profile/components/Activity.vue b/vulfocus-frontend/src/views/profile/components/Activity.vue new file mode 100644 index 00000000..dd5db3a5 --- /dev/null +++ b/vulfocus-frontend/src/views/profile/components/Activity.vue @@ -0,0 +1,185 @@ + + + + + diff --git a/vulfocus-frontend/src/views/profile/components/Timeline.vue b/vulfocus-frontend/src/views/profile/components/Timeline.vue new file mode 100644 index 00000000..1816934f --- /dev/null +++ b/vulfocus-frontend/src/views/profile/components/Timeline.vue @@ -0,0 +1,34 @@ + + + diff --git a/vulfocus-frontend/src/views/profile/components/UserCard.vue b/vulfocus-frontend/src/views/profile/components/UserCard.vue new file mode 100644 index 00000000..34a37864 --- /dev/null +++ b/vulfocus-frontend/src/views/profile/components/UserCard.vue @@ -0,0 +1,108 @@ + + + + + diff --git a/vulfocus-frontend/src/views/profile/index.vue b/vulfocus-frontend/src/views/profile/index.vue new file mode 100644 index 00000000..f092f360 --- /dev/null +++ b/vulfocus-frontend/src/views/profile/index.vue @@ -0,0 +1,62 @@ + + + diff --git a/vulfocus-frontend/src/views/register/index.vue b/vulfocus-frontend/src/views/register/index.vue new file mode 100644 index 00000000..5aaced24 --- /dev/null +++ b/vulfocus-frontend/src/views/register/index.vue @@ -0,0 +1,231 @@ + + + + + + + diff --git a/vulfocus-frontend/tests/unit/.eslintrc.js b/vulfocus-frontend/tests/unit/.eslintrc.js new file mode 100644 index 00000000..958d51ba --- /dev/null +++ b/vulfocus-frontend/tests/unit/.eslintrc.js @@ -0,0 +1,5 @@ +module.exports = { + env: { + jest: true + } +} diff --git a/vulfocus-frontend/tests/unit/components/Breadcrumb.spec.js b/vulfocus-frontend/tests/unit/components/Breadcrumb.spec.js new file mode 100644 index 00000000..1d94c8fc --- /dev/null +++ b/vulfocus-frontend/tests/unit/components/Breadcrumb.spec.js @@ -0,0 +1,98 @@ +import { mount, createLocalVue } from '@vue/test-utils' +import VueRouter from 'vue-router' +import ElementUI from 'element-ui' +import Breadcrumb from '@/components/Breadcrumb/index.vue' + +const localVue = createLocalVue() +localVue.use(VueRouter) +localVue.use(ElementUI) + +const routes = [ + { + path: '/', + name: 'home', + children: [{ + path: 'dashboard', + name: 'dashboard' + }] + }, + { + path: '/menu', + name: 'menu', + children: [{ + path: 'menu1', + name: 'menu1', + meta: { title: 'menu1' }, + children: [{ + path: 'menu1-1', + name: 'menu1-1', + meta: { title: 'menu1-1' } + }, + { + path: 'menu1-2', + name: 'menu1-2', + redirect: 'noredirect', + meta: { title: 'menu1-2' }, + children: [{ + path: 'menu1-2-1', + name: 'menu1-2-1', + meta: { title: 'menu1-2-1' } + }, + { + path: 'menu1-2-2', + name: 'menu1-2-2' + }] + }] + }] + }] + +const router = new VueRouter({ + routes +}) + +describe('Breadcrumb.vue', () => { + const wrapper = mount(Breadcrumb, { + localVue, + router + }) + it('dashboard', () => { + router.push('/dashboard') + const len = wrapper.findAll('.el-breadcrumb__inner').length + expect(len).toBe(1) + }) + it('normal route', () => { + router.push('/menu/menu1') + const len = wrapper.findAll('.el-breadcrumb__inner').length + expect(len).toBe(2) + }) + it('nested route', () => { + router.push('/menu/menu1/menu1-2/menu1-2-1') + const len = wrapper.findAll('.el-breadcrumb__inner').length + expect(len).toBe(4) + }) + it('no meta.title', () => { + router.push('/menu/menu1/menu1-2/menu1-2-2') + const len = wrapper.findAll('.el-breadcrumb__inner').length + expect(len).toBe(3) + }) + // it('click link', () => { + // router.push('/menu/menu1/menu1-2/menu1-2-2') + // const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') + // const second = breadcrumbArray.at(1) + // console.log(breadcrumbArray) + // const href = second.find('a').attributes().href + // expect(href).toBe('#/menu/menu1') + // }) + // it('noRedirect', () => { + // router.push('/menu/menu1/menu1-2/menu1-2-1') + // const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') + // const redirectBreadcrumb = breadcrumbArray.at(2) + // expect(redirectBreadcrumb.contains('a')).toBe(false) + // }) + it('last breadcrumb', () => { + router.push('/menu/menu1/menu1-2/menu1-2-1') + const breadcrumbArray = wrapper.findAll('.el-breadcrumb__inner') + const redirectBreadcrumb = breadcrumbArray.at(3) + expect(redirectBreadcrumb.contains('a')).toBe(false) + }) +}) diff --git a/vulfocus-frontend/tests/unit/components/Hamburger.spec.js b/vulfocus-frontend/tests/unit/components/Hamburger.spec.js new file mode 100644 index 00000000..01ea303a --- /dev/null +++ b/vulfocus-frontend/tests/unit/components/Hamburger.spec.js @@ -0,0 +1,18 @@ +import { shallowMount } from '@vue/test-utils' +import Hamburger from '@/components/Hamburger/index.vue' +describe('Hamburger.vue', () => { + it('toggle click', () => { + const wrapper = shallowMount(Hamburger) + const mockFn = jest.fn() + wrapper.vm.$on('toggleClick', mockFn) + wrapper.find('.hamburger').trigger('click') + expect(mockFn).toBeCalled() + }) + it('prop isActive', () => { + const wrapper = shallowMount(Hamburger) + wrapper.setProps({ isActive: true }) + expect(wrapper.contains('.is-active')).toBe(true) + wrapper.setProps({ isActive: false }) + expect(wrapper.contains('.is-active')).toBe(false) + }) +}) diff --git a/vulfocus-frontend/tests/unit/components/SvgIcon.spec.js b/vulfocus-frontend/tests/unit/components/SvgIcon.spec.js new file mode 100644 index 00000000..31467a9f --- /dev/null +++ b/vulfocus-frontend/tests/unit/components/SvgIcon.spec.js @@ -0,0 +1,22 @@ +import { shallowMount } from '@vue/test-utils' +import SvgIcon from '@/components/SvgIcon/index.vue' +describe('SvgIcon.vue', () => { + it('iconClass', () => { + const wrapper = shallowMount(SvgIcon, { + propsData: { + iconClass: 'test' + } + }) + expect(wrapper.find('use').attributes().href).toBe('#icon-test') + }) + it('className', () => { + const wrapper = shallowMount(SvgIcon, { + propsData: { + iconClass: 'test' + } + }) + expect(wrapper.classes().length).toBe(1) + wrapper.setProps({ className: 'test' }) + expect(wrapper.classes().includes('test')).toBe(true) + }) +}) diff --git a/vulfocus-frontend/tests/unit/utils/formatTime.spec.js b/vulfocus-frontend/tests/unit/utils/formatTime.spec.js new file mode 100644 index 00000000..24e165b4 --- /dev/null +++ b/vulfocus-frontend/tests/unit/utils/formatTime.spec.js @@ -0,0 +1,30 @@ +import { formatTime } from '@/utils/index.js' + +describe('Utils:formatTime', () => { + const d = new Date('2018-07-13 17:54:01') // "2018-07-13 17:54:01" + const retrofit = 5 * 1000 + + it('ten digits timestamp', () => { + expect(formatTime((d / 1000).toFixed(0))).toBe('7月13日17时54分') + }) + it('test now', () => { + expect(formatTime(+new Date() - 1)).toBe('刚刚') + }) + it('less two minute', () => { + expect(formatTime(+new Date() - 60 * 2 * 1000 + retrofit)).toBe('2分钟前') + }) + it('less two hour', () => { + expect(formatTime(+new Date() - 60 * 60 * 2 * 1000 + retrofit)).toBe('2小时前') + }) + it('less one day', () => { + expect(formatTime(+new Date() - 60 * 60 * 24 * 1 * 1000)).toBe('1天前') + }) + it('more than one day', () => { + expect(formatTime(d)).toBe('7月13日17时54分') + }) + it('format', () => { + expect(formatTime(d, '{y}-{m}-{d} {h}:{i}')).toBe('2018-07-13 17:54') + expect(formatTime(d, '{y}-{m}-{d}')).toBe('2018-07-13') + expect(formatTime(d, '{y}/{m}/{d} {h}-{i}')).toBe('2018/07/13 17-54') + }) +}) diff --git a/vulfocus-frontend/tests/unit/utils/parseTime.spec.js b/vulfocus-frontend/tests/unit/utils/parseTime.spec.js new file mode 100644 index 00000000..41d1b028 --- /dev/null +++ b/vulfocus-frontend/tests/unit/utils/parseTime.spec.js @@ -0,0 +1,28 @@ +import { parseTime } from '@/utils/index.js' + +describe('Utils:parseTime', () => { + const d = new Date('2018-07-13 17:54:01') // "2018-07-13 17:54:01" + it('timestamp', () => { + expect(parseTime(d)).toBe('2018-07-13 17:54:01') + }) + it('ten digits timestamp', () => { + expect(parseTime((d / 1000).toFixed(0))).toBe('2018-07-13 17:54:01') + }) + it('new Date', () => { + expect(parseTime(new Date(d))).toBe('2018-07-13 17:54:01') + }) + it('format', () => { + expect(parseTime(d, '{y}-{m}-{d} {h}:{i}')).toBe('2018-07-13 17:54') + expect(parseTime(d, '{y}-{m}-{d}')).toBe('2018-07-13') + expect(parseTime(d, '{y}/{m}/{d} {h}-{i}')).toBe('2018/07/13 17-54') + }) + it('get the day of the week', () => { + expect(parseTime(d, '{a}')).toBe('五') // 星期五 + }) + it('get the day of the week', () => { + expect(parseTime(+d + 1000 * 60 * 60 * 24 * 2, '{a}')).toBe('日') // 星期日 + }) + it('empty argument', () => { + expect(parseTime()).toBeNull() + }) +}) diff --git a/vulfocus-frontend/tests/unit/utils/validate.spec.js b/vulfocus-frontend/tests/unit/utils/validate.spec.js new file mode 100644 index 00000000..f774905b --- /dev/null +++ b/vulfocus-frontend/tests/unit/utils/validate.spec.js @@ -0,0 +1,17 @@ +import { validUsername, isExternal } from '@/utils/validate.js' + +describe('Utils:validate', () => { + it('validUsername', () => { + expect(validUsername('admin')).toBe(true) + expect(validUsername('editor')).toBe(true) + expect(validUsername('xxxx')).toBe(false) + }) + it('isExternal', () => { + expect(isExternal('https://github.com/PanJiaChen/vue-element-admin')).toBe(true) + expect(isExternal('http://github.com/PanJiaChen/vue-element-admin')).toBe(true) + expect(isExternal('github.com/PanJiaChen/vue-element-admin')).toBe(false) + expect(isExternal('/dashboard')).toBe(false) + expect(isExternal('./dashboard')).toBe(false) + expect(isExternal('dashboard')).toBe(false) + }) +}) diff --git a/vulfocus-frontend/vue.config.js b/vulfocus-frontend/vue.config.js new file mode 100644 index 00000000..ccdcfda2 --- /dev/null +++ b/vulfocus-frontend/vue.config.js @@ -0,0 +1,139 @@ +'use strict' +const path = require('path') +const defaultSettings = require('./src/settings.js') + +function resolve(dir) { + return path.join(__dirname, dir) +} + +const name = defaultSettings.title || 'vue Admin Template' // page title + +// If your port is set to 80, +// use administrator privileges to execute the command line. +// For example, Mac: sudo npm run +// You can change the port by the following methods: +// port = 9528 npm run dev OR npm run dev --port = 9528 +const port = process.env.port || process.env.npm_config_port || 9528 // dev port + +// All configuration item explanations can be find in https://cli.vuejs.org/config/ +module.exports = { + /** + * You will need to set publicPath if you plan to deploy your site under a sub path, + * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/, + * then publicPath should be set to "/bar/". + * In most cases please use '/' !!! + * Detail: https://cli.vuejs.org/config/#publicpath + */ + publicPath: '/', + outputDir: 'dist', + assetsDir: 'static', + lintOnSave: process.env.NODE_ENV === 'development', + productionSourceMap: true, + // devServer: { + // port: port, + // open: true, + // overlay: { + // warnings: false, + // errors: true + // }, + // // proxy: { + // // // change xxx-api/login => mock/login + // // // detail: https://cli.vuejs.org/config/#devserver-proxy + // // [process.env.VUE_APP_BASE_API]: { + // // target: `http://127.0.0.1:${port}/mock`, + // // changeOrigin: true, + // // pathRewrite: { + // // ['^' + process.env.VUE_APP_BASE_API]: '' + // // } + // // } + // // }, + // // after: require('./mock/mock-server.js') + // }, + configureWebpack: { + // provide the app's title in webpack's name field, so that + // it can be accessed in index.html to inject the correct title. + name: name, + resolve: { + alias: { + '@': resolve('src') + } + } + }, + chainWebpack(config) { + config.plugins.delete('preload') // TODO: need test + config.plugins.delete('prefetch') // TODO: need test + + // set svg-sprite-loader + config.module + .rule('svg') + .exclude.add(resolve('src/icons')) + .end() + config.module + .rule('icons') + .test(/\.svg$/) + .include.add(resolve('src/icons')) + .end() + .use('svg-sprite-loader') + .loader('svg-sprite-loader') + .options({ + symbolId: 'icon-[name]' + }) + .end() + + // set preserveWhitespace + config.module + .rule('vue') + .use('vue-loader') + .loader('vue-loader') + .tap(options => { + options.compilerOptions.preserveWhitespace = true + return options + }) + .end() + + config + // https://webpack.js.org/configuration/devtool/#development + .when(process.env.NODE_ENV === 'development', + config => config.devtool('source-map') + ) + + config + .when(process.env.NODE_ENV !== 'development', + config => { + config + .plugin('ScriptExtHtmlWebpackPlugin') + .after('html') + .use('script-ext-html-webpack-plugin', [{ + // `runtime` must same as runtimeChunk name. default is `runtime` + inline: /runtime\..*\.js$/ + }]) + .end() + config + .optimization.splitChunks({ + chunks: 'all', + cacheGroups: { + libs: { + name: 'chunk-libs', + test: /[\\/]node_modules[\\/]/, + priority: 10, + chunks: 'initial' // only package third parties that are initially dependent + }, + elementUI: { + name: 'chunk-elementUI', // split elementUI into a single package + priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app + test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm + }, + commons: { + name: 'chunk-commons', + test: resolve('src/components'), // can customize your rules + minChunks: 3, // minimum common number + priority: 5, + reuseExistingChunk: true + } + } + }) + config.optimization.runtimeChunk('single') + } + ) + } +}