Commit 39476904 authored by SBassett's avatar SBassett
Browse files

wikimedia/security/tooling repository cleanup

(see details on bug)

Bug: T246392
Change-Id: Ie5662486c26ef4974f2198ed394aba4dfa592d8a
parent 4ca00677
# Wikimedia Security Tooling
Public git repository for ad-hoc wikimedia security tooling, currently managed
by the WMF Security Team (mw:Wikimedia_Security_Team). Please direct any
comments or questions to security@wikimedia.org.
This repository is an incubator of sorts for ad-hoc wikimedia security tooling, currently managed by [the Wikimedia Security Team](https://www.mediawiki.org/wiki/Wikimedia_Security_Team). Please direct any comments or questions to one of the authors listed below.
## Installing
## Usage
For now, simply clone this repository:
......@@ -12,9 +10,16 @@ For now, simply clone this repository:
git clone https://gerrit.wikimedia.org/r/wikimedia/security/tooling
```
## Deployment
Useful but not necessarily production-worthy code should be placed within the ```bin``` directory with a README or appropriate, clear code comments. If these scripts and projects ever develop into larger, more mature codebases, then they should be migrated to their own directories under the more general ```wikimedia/security``` namespace (e.g. https://w.wiki/ado). See [this related task](https://phabricator.wikimedia.org/T246392) for an example of this process.
Please contact the WMF Security Team.
Here is a current list of larger, more stand-alone tools:
1. [Deployer Audit](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/deployer-audit)
1. [Github User Audit](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/github-user-audit)
1. [Gitmonitor](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/gitmonitor)
1. [PHP Security Tools](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/php-security-tools)
1. [Spam Account Stats](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/spamaccountstats)
1. [Usertracker](https://gerrit.wikimedia.org/r/admin/repos/wikimedia/security/usertracker)
## Authors
......@@ -23,4 +28,4 @@ Please contact the WMF Security Team.
## License
This project is licensed under the Apache 2 License - see the [LICENSE] file for details
This project is licensed under the Apache 2 License - see the [LICENSE](LICENSE) file for details.
.env
token.pickle
credentials.json
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Tool to audit Wikimedia deployers
Author: sbassett@wikimedia.org
License: Apache 2.0
Uses: github.com (for raw data.yaml file), google sheets API
"""
import argparse
import datetime
import pickle
import os
import re
import requests
import sys
import urllib.parse
import yaml
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dotenv import load_dotenv
""" constants """
load_dotenv()
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
GET_RANGE = "Deployers Audit!A2:G"
WRITE_RANGE = "Deployers Audit!A2"
ADMIN_DATA_FILE = os.getenv('DTG_ADMIN_DATA_FILE')
SPREADSHEET_ID = os.getenv('DTG_GOOGLE_SHEET_ID')
SAL_URL_BASE = os.getenv('DTG_SAL_URL_BASE')
SAL_YEARS_PREV = os.getenv('DTG_SAL_YEARS_PREV')
NO_DEPLOYS = 'No deploys last 2 years'
def main():
""" cli args/control """
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--phab', action='store_true',
default=False,
help='Optionally print Phab-formatted\
table to stdout')
parser.add_argument('-n', '--nodeploys', action='store_true',
default=False,
help='Only print "no deploy" users for\
Phab-formatted table')
args, unknown = parser.parse_known_args()
""" process Google Sheets API creds """
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
""" If there are no (valid) credentials available, let the user log in. """
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
""" Save the credentials for the next run """
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
""" get and process admin.yaml """
resp = requests.get(ADMIN_DATA_FILE)
if resp.status_code != 200:
print("Response Error, status code = {}".format(resp.status_code))
sys.exit(1)
else:
deployers_from_yaml = []
data = yaml.safe_load(resp.text)
if isinstance(data, dict):
deployers_from_yaml = data['groups']['deployment']['members']
deployers_from_yaml.sort()
""" try to find last deployed data for a deployer
wikitech:index.php?title=Server_admin_log/Archives&action=raw
wikitech:index.php?title=Server_admin_log&action=raw
search back dates for user - pattern: 'nn:nn {user}:' """
full_log_text = ''
deployers_last_deploy = {}
""" current last deploy data from sal """
current_url = ''.join([SAL_URL_BASE, 'Server%20Admin%20Log&action=raw'])
resp = requests.get(current_url)
if resp.status_code != 200:
print("Response Error, status code = {}".format(resp.status_code))
sys.exit(1)
else:
full_log_text = ''.join([full_log_text, resp.text])
""" historic last deploy data from sal """
historic_url = ''.join([SAL_URL_BASE,
'Server_admin_log/Archives&action=raw'])
resp = requests.get(historic_url)
if resp.status_code != 200:
print("Response Error, status code = {}".format(resp.status_code))
sys.exit(1)
else:
years = [datetime.datetime.now().year,
datetime.datetime.now().year - int(SAL_YEARS_PREV)]
for year in years:
for line in resp.text.split('\n'):
pat = ''.join([r'\[\[(.+)\|', str(year), r'.+'])
found = re.findall(pat, line)
if found:
for archive in found:
archive_url = ''.join([SAL_URL_BASE,
urllib.parse.quote(archive),
'&action=raw'])
aresp = requests.get(archive_url)
if aresp.status_code != 200:
print("Response Error, status code = {}".format(
resp.status_code))
sys.exit(1)
else:
full_log_text = ''.join([full_log_text,
aresp.text])
""" process last deploy data """
for dep in deployers_from_yaml:
for line in full_log_text.split('\n'):
pat_date = r'==\s*(\d{4}\-\d{2}\-\d{2})\s*=='
found_date = re.match(pat_date, line)
if 'current_last_deploy_date' not in locals():
current_last_deploy_date = NO_DEPLOYS
if found_date and len(found_date.groups(0)) > 0:
current_last_deploy_date = found_date.groups(0)[0]
continue
pat_dep = ''.join([r'(\*\s?\d\d\:\d\d\s+)(', str(dep), r')'])
if re.search(pat_dep, line, re.I):
if ((dep in deployers_last_deploy and
deployers_last_deploy[dep] <
current_last_deploy_date) or
dep not in deployers_last_deploy):
deployers_last_deploy[dep] = current_last_deploy_date
continue
if dep not in deployers_last_deploy:
deployers_last_deploy[dep] = NO_DEPLOYS
""" get current data from Google Sheet """
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
range=GET_RANGE).execute()
deployers_from_sheet_data = result.get('values', [])
""" update and sync all data thus far """
deployers_all = []
deployers_from_sheet = []
deployers_to_write_to_sheet = []
for dep in deployers_from_sheet_data:
if(isinstance(dep, list) and len(dep) > 0 and isinstance(dep[0], str)):
deployers_from_sheet.append(dep[0])
deployers_all = list(set().union(
deployers_from_sheet,
deployers_from_yaml)
)
deployers_all.sort()
update_time = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M')
for dep in deployers_all:
if(len(deployers_from_sheet_data) > 0):
dep_found = False
dep_last_deploy = deployers_last_deploy[dep] if\
dep in deployers_last_deploy else NO_DEPLOYS
for dep_data in deployers_from_sheet_data:
if(isinstance(dep_data, list) and
isinstance(dep, str) and
dep == dep_data[0]):
if len(dep_data) == 1:
dep_data.append("")
if len(dep_data) == 2:
dep_data.append("0")
if len(dep_data) == 3:
dep_data.append("0")
if len(dep_data) == 4:
dep_data.append("0")
if len(dep_data) == 5:
dep_data.append("")
elif(len(dep_data[5]) == 0 or
dep_data[5] != dep_last_deploy):
dep_data[5] = dep_last_deploy
if len(dep_data) == 6:
dep_data.append(update_time)
else:
dep_data[6] = update_time
dep_data.pop(0)
deployers_to_write_to_sheet.append([dep] + dep_data)
dep_found = True
if(dep_found is False):
deployers_to_write_to_sheet.append(
[dep, "", "0", "0", "0", dep_last_deploy, update_time])
""" write updated data to Google Sheet """
result2 = sheet.values().update(
spreadsheetId=SPREADSHEET_ID,
range=WRITE_RANGE,
body={"range": WRITE_RANGE,
"values": deployers_to_write_to_sheet,
"majorDimension": "ROWS"},
valueInputOption="RAW").execute()
print('Google sheet has been updated.')
""" optionally format output as Phab table """
if(args.phab):
print('\n| Shell username | Name | WMF | WMDE | \
WMF Legal NDA? | Last Deployed | Date Updated')
print('| --- | --- | --- | --- | --- | --- | ---')
for row in deployers_to_write_to_sheet:
if(args.nodeploys and row[5] == NO_DEPLOYS):
print('|', ' | '.join(row))
elif(not args.nodeploys):
print('|', ' | '.join(row))
""" call main """
if __name__ == '__main__':
main()
# DeployersToGSheet
A Python script to get the current list of active WMF deployers via an admin
yaml file and store/update within a shared, private Google Sheet.
## Prerequisites
```
python3
argparse
datetime
dotenv
google-api-python-client
pickle
os
re
requests
sys
urllib.parse
yaml
```
## Installing
1. ```pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib```
2. ```git clone "https://gerrit.wikimedia.org/r/wikimedia/security/tooling"```
## Usage
1. Configure ```.env``` to your liking and run something like ```eval $(cat .env | sed 's/^/export /')``` - example values provided within sample.env.
2. Set up Google auth via: https://developers.google.com/sheets/api/quickstart/python
3. Download credentials.json file from step (2)
4. Run app, which then prompt you to auth in browser via Google's App Workflow system. This should only need to happen once per install.
2. ```chmod +x DeployersToGSheet.py && ./DeployersToGSheet.py {args...}```
3. DeployersToGSheet.py has a few arguments:
1. ```-h```, ```--help``` = show this help message and exit
2. ```-p```, ```--phab``` = Optionally print Phab-formatted table to stdout
3. ```-n```, ```--nodeploys``` = Only print "no deploy" users for Phab-formatted table
## Authors
* **Scott Bassett** [sbassett@wikimedia.org]
## License
This project is licensed under the Apache 2.0 License - see the [LICENSE](../LICENSE) file for details.
DTG_GOOGLE_CLIENT_ID="some_token"
DTG_GOOGLE_CLIENT_SECRET="some_secret"
DTG_GOOGLE_SHEET_ID="some_id"
DTG_ADMIN_DATA_FILE="https://raw.githubusercontent.com/wikimedia/puppet/production/modules/admin/data/data.yaml"
DTG_SAL_URL_BASE="https://wikitech.wikimedia.org/w/index.php?title="
DTG_SAL_YEARS_PREV=1
export GM_REPO_URL="https://gerrit.wikimedia.org/r/path/to/repo"
export GM_REPO_FILE="path/to/file.yaml"
export GM_REPO_BRANCH="master"
export GM_REPO_DIFF="https://gerrit.wikimedia.org/r/plugins/gitiles/"
export GM_SINCE="1 day ago"
export GM_GREP_PAT="pattern1\|pattern2"
export GM_SENDMAIL="/usr/sbin/sendmail"
export GM_MAIL_TO="test@exmaple.com"
export GM_DEBUG=
#/usr/bin/env bash
################################################################################
# Author: sbassett@wikimedia.org
# License: Apache 2 <https://opensource.org/licenses/Apache-2.0>
# Usage:
# Searches recent logs for simple grep patterns
# Env variables:
# GM_REPO_URL = gerrit repo url to clone and search (no .git at end)
# GM_REPO_FILE = a specific file within the repo that we care about
# GM_REPO_BRANCH = master or whatever
# GM_REPO_DIFF = gitiles
# GM_SINCE = since time passed to --date=""
# GM_GREP_PAT = a text pattern for grep to search git show commit data
# GM_SENDMAIL = path to sendmail bin
# GM_MAIL_TO = email to send report
# GM_DEBUG = if true, outputs sendmail report string
# (with set -u, script will exit if the above are not defined)
################################################################################
set -euo pipefail
# check binary dependencies
bins=("git" "grep" "printf" "cut" "date" "hostname" "basename")
for bin in "${bins[@]}"; do
if [[ -z $(which $bin) ]]; then
printf "dependency '$bin' does not appear to be installed - exiting.\n"
exit 1
fi
done
# clone repo locally
GM_REPO_PATH=${GM_REPO_URL##*/}
if [[ -d $GM_REPO_PATH ]]; then
if [[ -n "$GM_REPO_BRANCH" ]]; then
cd $GM_REPO_PATH && git checkout $GM_REPO_BRANCH && git pull && cd ..
else
rm -rf $GM_REPO_PATH && git clone $GM_REPO_URL
fi
else
if [[ -n "$GM_REPO_BRANCH" ]]; then
git clone -b $GM_REPO_BRANCH $GM_REPO_URL
else
git clone $GM_REPO_URL
fi
fi
# format SINCE
GM_SINCE=$(date --date="$GM_SINCE" "+%Y-%m-%d %H:%M:%S")
# build report
cd $GM_REPO_PATH
report_body=""
for git_hash in $(git log --since="$GM_SINCE" --pretty="%H" $GM_REPO_FILE)
do
repo_diff_url=""
if [[ -n "$GM_REPO_DIFF" ]]; then
repo_path_for_url=${GM_REPO_URL#*://*/*/}
repo_diff_url="<$GM_REPO_DIFF$repo_path_for_url/+/$git_hash%%5E%%21/#F0>\n"
fi
commit_marker=$(printf "\n" &&
printf -- '*%.0s' {1..10} &&
printf "\nCOMMIT ID: $git_hash\n\n" &&
printf '%s' "$repo_diff_url" &&
printf -- '*%.0s' {1..10})
git_show=$(git show $git_hash | cut -c -80 | grep -E -C 3 "$GM_GREP_PAT" || true)
if [[ -n "$git_show" ]]; then
report_body="$report_body $commit_marker\n$git_show\n"
fi
done
# send report, if necessary
if [[ -n "$report_body" ]]; then
script_name=$(basename "$0")
script_name=${script_name%%.*}
from=${script_name##*/}"@"$(hostname -A)
subject="Interesting git activity in: ${GM_REPO_URL#*://*/*/}"
if [[ -n "$GM_DEBUG" ]]; then
printf "To:$GM_MAIL_TO\nFrom:$from\nSubject: $subject\n\n$report_body \
| $GM_SENDMAIL -t"
else
printf "To:$GM_MAIL_TO\nFrom:$from\nSubject: $subject\n\n$report_body" \
| $GM_SENDMAIL -t
fi
fi
# GitMonitor.sh
Some quick-and-dirty bash to monitor string patterns within the commits to a git repo. Designed to be run via cron - see Usage.
## Prerequisites
```
* plain old bash
* cd
* git
* printf
* cut
* date
* hostname
* basename
* grep
* sendmail (as an env var)
```
*n.b. built and tested against Debian Stretch - tools like ```date``` and ```hostname``` may differ across platforms.*
## Installing
1. ```git clone https://gerrit.wikimedia.org/r/wikimedia/security/tooling```
2. Configure various environment variables - see comments within ```GitMonitor.sh``` header or [sample file provided](GM_env.sh). Note that GM_env* is a default pattern in [.gitignore](.gitignore)
3. Set proper execute perms and go!
## Usage
1. Simply configure the relevant environment variables and run ```./GitMonitor.sh```
2. Set up as a cron (e.g. every 2 minutes):
```bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin
SHELL=/bin/bash
*/2 * * * * cd /path/to/wikimedia/security/tooling/gitmonitor && source GM_env.sh && ./GitMonitor.sh
```
## Authors
* **Scott Bassett** [sbassett@wikimedia.org]
## License
This project is licensed under the Apache 2.0 License - see the [LICENSE](https://opensource.org/licenses/Apache-2.0) file for details.
[gerrit]
host=gerrit.wikimedia.org
port=29418
project=wikimedia/security/tooling.git
track=1
defaultrebase=0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.