├── .gitignore ├── LICENSE ├── README.md ├── client ├── murphysec-darwin-amd64 ├── murphysec-linux-amd64 └── murphysec-windows-amd64.exe ├── configs ├── __init__.py └── msg_template.json ├── libs ├── git.py └── murphy.py ├── message └── send.py ├── scan_all.py └── webapi.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | .idea/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | *.ini 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # murphysec-gitlab-scanner 2 | 3 | ## 使用方式 4 | ### 全量扫描 5 | python3 scan_all.py -A "your gitlab address" -T "your gitlab token" -t "your murphy token" 6 | ### 增量扫描 7 | 1、配置gitlab webhook,配置方式请自行百度
8 | 2、python3 webapi.py 9 | 10 | ## TODO 11 | * [x] 增加增量代码检测(gitlab webhook功能) 12 | * [ ] 增加检测结果消息提醒 13 | * [ ] 增加检测队列,加快检测速度 -------------------------------------------------------------------------------- /client/murphysec-darwin-amd64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphysecurity/murphysec-gitlab-scanner/55bf765f3c86c4ae46811aeb16b33267e9f69488/client/murphysec-darwin-amd64 -------------------------------------------------------------------------------- /client/murphysec-linux-amd64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphysecurity/murphysec-gitlab-scanner/55bf765f3c86c4ae46811aeb16b33267e9f69488/client/murphysec-linux-amd64 -------------------------------------------------------------------------------- /client/murphysec-windows-amd64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murphysecurity/murphysec-gitlab-scanner/55bf765f3c86c4ae46811aeb16b33267e9f69488/client/murphysec-windows-amd64.exe -------------------------------------------------------------------------------- /configs/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf8 2 | import datetime 3 | import github 4 | from sqlalchemy import create_engine 5 | from sqlalchemy.orm import sessionmaker 6 | from sqlalchemy.ext.declarative import declarative_base 7 | import redis 8 | import configparser 9 | from datetime import datetime 10 | import json 11 | import os 12 | 13 | config = configparser.ConfigParser() 14 | path = os.path.split(os.path.realpath(__file__))[0] 15 | config.read(path + "/conf.ini", encoding="utf-8") 16 | 17 | 18 | class GitLab: 19 | def __init__(self): 20 | self.address = config.get('gitlab', 'GITLABADDRESS') 21 | self.token = config.get('gitlab', 'GITLABTOKEN') 22 | 23 | def get_address(self): 24 | return self.address 25 | 26 | def get_token(self): 27 | return self.token 28 | 29 | 30 | class Murphy: 31 | def __init__(self): 32 | self.token = config.get('gitlab', 'MURPHYSECTOKEN') 33 | 34 | def get_token(self): 35 | return self.token 36 | 37 | 38 | gitlab = GitLab() 39 | murphy = Murphy() 40 | 41 | GITLABADDRESS = config.get('gitlab', 'GITLABADDRESS') 42 | GITLABTOKEN = config.get('gitlab', 'GITLABTOKEN') 43 | MURPHYSECTOKEN = config.get('gitlab', 'MURPHYSECTOKEN') 44 | -------------------------------------------------------------------------------- /configs/msg_template.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "wide_screen_mode": true 4 | }, 5 | "elements": [ 6 | { 7 | "fields": [ 8 | { 9 | "is_short": true, 10 | "text": { 11 | "content": "**👤 回复人:**\n$user", 12 | "tag": "lark_md" 13 | } 14 | }, 15 | { 16 | "is_short": true, 17 | "text": { 18 | "content": "**🕐 回复时间:**\n$comment_time", 19 | "tag": "lark_md" 20 | } 21 | } 22 | ], 23 | "tag": "div" 24 | }, 25 | { 26 | "tag": "hr" 27 | }, 28 | { 29 | "tag": "markdown", 30 | "content": "**📍 仓库:** $repo" 31 | }, 32 | { 33 | "tag": "hr" 34 | }, 35 | { 36 | "tag": "div", 37 | "text": { 38 | "content": "$content", 39 | "tag": "lark_md" 40 | } 41 | }, 42 | { 43 | "tag": "hr" 44 | }, 45 | { 46 | "actions": [ 47 | { 48 | "tag": "button", 49 | "text": { 50 | "content": "查看issues", 51 | "tag": "plain_text" 52 | }, 53 | "type": "primary", 54 | "url": "$issues_link" 55 | } 56 | ], 57 | "tag": "action" 58 | } 59 | ], 60 | "header": { 61 | "template": "red", 62 | "title": { 63 | "content": "✉️ 有新的issues回复了!", 64 | "tag": "plain_text" 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /libs/git.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import gitlab 3 | import subprocess 4 | from datetime import datetime 5 | import os 6 | import stat 7 | import shutil 8 | 9 | 10 | class MyGitlab: 11 | def __init__(self, addr, token): 12 | self.token = token 13 | self.addr = addr 14 | self.gl = gitlab.Gitlab(self.addr, private_token=self.token) 15 | 16 | def __runcmd(self, command): 17 | ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", 18 | timeout=3600) 19 | if ret.returncode == 0: 20 | return ret.stdout 21 | else: 22 | raise RuntimeError(f"runcmd {command} error") 23 | 24 | def get_repo_list(self): 25 | pro_list = self.gl.projects.list() 26 | clone_list = [] 27 | for pro in pro_list: 28 | clone_list.append(pro.http_url_to_repo) 29 | return clone_list 30 | 31 | def clone(self, git_url): 32 | path = datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f') 33 | clone_url = f"{git_url.split('://')[0]}://oauth2:{self.token}@{git_url.split('://')[1]}" 34 | res = self.__runcmd(f"git clone {clone_url} projects/{path}") 35 | if res == None: 36 | raise RuntimeError(f"clone {git_url} error") 37 | return path 38 | 39 | def clone_branch(self, git_url, branch): 40 | path = datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f') 41 | clone_url = f"{git_url.split('://')[0]}://oauth2:{self.token}@{git_url.split('://')[1]}" 42 | res = self.__runcmd(f"git clone -b {branch} {clone_url} projects/{path}") 43 | if res == None: 44 | raise RuntimeError(f"clone {git_url} error") 45 | return path 46 | 47 | def del_code(self, path): 48 | path = os.getcwd() + '/projects/' + path 49 | print(path) 50 | if os.path.exists(path): 51 | for fileList in os.walk(path): 52 | for name in fileList[2]: 53 | os.chmod(os.path.join(fileList[0], name), stat.S_IWRITE) 54 | os.remove(os.path.join(fileList[0], name)) 55 | shutil.rmtree(path) -------------------------------------------------------------------------------- /libs/murphy.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import subprocess 3 | import platform 4 | 5 | 6 | class MurphyScan: 7 | def __init__(self, token): 8 | self.token = token 9 | 10 | def scan(self, path): 11 | sysstr = platform.system() 12 | if sysstr == "Windows": 13 | cmd = f'./client/murphysec-cli-win.exe scan ./projects/{path} --json --token {self.token }' 14 | print("Call Windows tasks") 15 | elif sysstr == "Linux": 16 | cmd = f'./client/murphysec-linux-amd64 scan ./projects/{path} --json --token {self.token}' 17 | print("Call Linux tasks") 18 | elif sysstr == "Darwin": 19 | cmd = f'./client/murphysec-darwin-amd64 scan ./projects/{path} --json --token {self.token}' 20 | print("Call mac tasks") 21 | else: 22 | print('can not surport system {}'.format(sysstr)) 23 | cmd = '' 24 | return self.__runcmd(cmd) 25 | 26 | def __runcmd(self, cmd): 27 | ret = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", 28 | timeout=3600) 29 | if ret.returncode == 0: 30 | return ret.stdout 31 | else: 32 | print(ret) 33 | raise RuntimeError(f"scan {cmd} error") -------------------------------------------------------------------------------- /message/send.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import logging 3 | import requests 4 | import json 5 | from string import Template 6 | 7 | 8 | def getMsgContent(send_data): 9 | with open("configers/template.json") as f: 10 | msg_template = f.read() 11 | temp_Template = Template(msg_template) 12 | 13 | for key, value in send_data.items(): 14 | if value is None or not value: 15 | send_data[key] = "-" 16 | 17 | msg = temp_Template.substitute( 18 | comment_time=send_data.get("comment_time", "-"), 19 | user=send_data.get("user", "-"), 20 | repo=send_data.get("repo", "-"), 21 | content=send_data.get("content", "-"), 22 | issues_link=send_data.get("issues_link", "https://github.com") 23 | ) 24 | try: 25 | content = json.loads(msg, strict=False) 26 | return content 27 | except Exception as e: 28 | logging.error(f"Get msg content failed. {str(e)} {str(send_data)}") 29 | return 30 | 31 | 32 | class LarkRobot: 33 | def __init__(self, webhook): 34 | self.webhook = webhook 35 | 36 | def sendMsg(self, send_data): 37 | content = getMsgContent(send_data) 38 | if not content: 39 | logging.error(f"Get msg failed: {send_data}") 40 | try: 41 | post_body = { 42 | "msg_type": "interactive", 43 | "card": content 44 | } 45 | req = requests.post(self.webhook, data=json.dumps(post_body)) 46 | logging.info(f"Send msg status: {req.status_code} {req.text}") 47 | return req 48 | except Exception as e: 49 | logging.error(f"Send msg failed: {str(e)} - {content}") 50 | return 51 | 52 | def send_msg(comment_time, user, repo, content, issues_link): 53 | wk = "https://open.feishu.cn/open-apis/bot/v2/hook/e003eada-b96d-4a1c-ab9f-72556ad35adf" 54 | robot = LarkRobot(wk) 55 | msg = { 56 | "comment_time": comment_time, 57 | "user": user, 58 | "repo": repo, 59 | "content": content, 60 | "issues_link": issues_link 61 | } 62 | robot.sendMsg(msg) -------------------------------------------------------------------------------- /scan_all.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import json 3 | import optparse 4 | from libs.git import MyGitlab 5 | from libs.murphy import MurphyScan 6 | 7 | 8 | 9 | def run(git_addr, git_token, mf_token): 10 | my_gl = MyGitlab(addr=git_addr, token=git_token) 11 | mf = MurphyScan(token=mf_token) 12 | repos = my_gl.get_repo_list() 13 | for repo_url in repos: 14 | path = my_gl.clone(repo_url) 15 | scan_res = mf.scan(path) 16 | my_gl.del_code(path) 17 | print(json.loads(scan_res)) 18 | # 添加自己的逻辑 19 | 20 | 21 | if __name__ == '__main__': 22 | usage = "python %prog -A/--address -T/--Token -t/--token " 23 | parser = optparse.OptionParser(usage) 24 | parser.add_option('-A', '--address', dest='address', type='string', help='running gitlab address', default='') 25 | parser.add_option('-T', '--gitlab_token', dest='gitlab_token', type='string', help='running gitlab token', default='') 26 | parser.add_option('-t', '--mf_token', dest='mf_token', type='string', help='running murphy token', default='') 27 | options, args = parser.parse_args() 28 | run(options.address, options.gitlab_token, options.mf_token) 29 | -------------------------------------------------------------------------------- /webapi.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | from fastapi import FastAPI, Header, Request, Response 3 | import uvicorn 4 | import hmac 5 | from libs.git import MyGitlab 6 | from libs.murphy import MurphyScan 7 | from datetime import datetime 8 | from pydantic import BaseModel 9 | from uuid import UUID 10 | import configs 11 | 12 | app = FastAPI() 13 | APP_NAME = "webhook-listener" 14 | WEBHOOK_SECRET = "My precious" 15 | 16 | 17 | class WebhookData(BaseModel): 18 | username: str 19 | data: dict 20 | event: str 21 | timestamp: datetime 22 | model: str 23 | request_id: UUID 24 | 25 | 26 | @app.post("/gitlab/webhook") 27 | async def webhook( 28 | request: Request, 29 | response: Response, 30 | content_length: int = Header(...), 31 | x_hook_signature: str = Header(None) 32 | ): 33 | if content_length > 1000000: 34 | response.status_code = 400 35 | return {"result": "Content too long"} 36 | if x_hook_signature: 37 | raw_input = await request.body() 38 | input_hmac = hmac.new( 39 | key=WEBHOOK_SECRET.encode(), 40 | msg=raw_input, 41 | digestmod="sha512" 42 | ) 43 | if not hmac.compare_digest(input_hmac.hexdigest(), x_hook_signature): 44 | #logger.error("Invalid message signature") 45 | response.status_code = 400 46 | return {"result": "Invalid message signature"} 47 | #logger.info("Message signature checked ok") 48 | else: 49 | pass 50 | #logger.info("No message signature to check") 51 | body = await request.json() 52 | if body['event_name'] == 'event_name': 53 | branch = body['body'].split('/')[-1] 54 | user_name = body['user_name'] 55 | git_http_url = body['git_http_url'] 56 | my_gl = MyGitlab(addr=configs.gitlab.address, token=configs.gitlab.token) 57 | mf = MurphyScan(token=configs.murphy.token) 58 | path = my_gl.clone_branch(git_http_url, branch) 59 | scan_res = mf.scan(path) 60 | my_gl.del_code(path) 61 | else: 62 | pass 63 | return {"result": "ok"} 64 | 65 | 66 | if __name__ == "__main__": 67 | uvicorn.run("webapi:app", host="0.0.0.0", port=8888) 68 | --------------------------------------------------------------------------------