selfhostedops-stack/filesync/client/sec.py

82 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Was geht standardmäßig: Freigabelink ohne Passwort und Ablauf, 10 falsche Anmeldungen.
sec.py P share|brute (P = nc|oc|sf). Anmeldungen über das Web-Anmeldeformular des Produkts."""
import os, sys, re, time, json, requests
E = {k: v.strip("'") for k, v in (l.strip().split('=', 1) for l in open('/root/ep19fs/env') if '=' in l and not l.startswith('#'))}
P, what = sys.argv[1], sys.argv[2]
T = lambda: time.strftime('%H:%M:%S', time.gmtime())
def nc_login(pw):
s = requests.Session(); u = E['NC_URL']
s.get(u + '/login'); tok = s.get(u + '/csrftoken').json()['token']
t = time.time()
r = s.post(u + '/login', data={'user': E['NC_USER'], 'password': pw, 'requesttoken': tok}, headers={'requesttoken': tok, 'Origin': u}, allow_redirects=False)
ok = r.status_code == 303 and '/login' not in r.headers.get('Location', '/login')
return r.status_code, time.time() - t, ok, r.headers.get('Location', '')[-40:]
def sf_login(pw):
s = requests.Session(); u = E['SF_URL']
r = s.get(u + '/accounts/login/'); tok = s.cookies.get('sfcsrftoken') or s.cookies.get('csrftoken')
t = time.time()
r = s.post(u + '/accounts/login/', data={'csrfmiddlewaretoken': tok, 'login': E['SF_USER'], 'password': pw, 'next': '/'}, headers={'Referer': u + '/accounts/login/'}, allow_redirects=False)
ok = r.status_code == 302
captcha = 'captcha' in r.text.lower()
return r.status_code, time.time() - t, ok, ('captcha verlangt' if captcha else '') + re.sub(r'\s+', ' ', ' '.join(re.findall(r'class="error[^"]*"[^>]*>([^<]{0,120})', r.text)))[:120]
def oc_login(pw):
u = E['OC_URL']; s = requests.Session()
body = {'params': [E['OC_USER'], pw, '1'], 'hello': {'scope': 'openid profile email', 'client_id': 'web', 'redirect_uri': u + '/oidc-callback.html', 'flow': 'oidc'}}
t = time.time()
r = s.post(u + '/signin/v1/identifier/_/logon', json=body, headers={'Kopano-Konnect-XSRF': '1', 'Referer': u + '/signin/v1/identifier', 'Origin': u})
ok = r.status_code == 200 and '"success":true' in r.text.replace(' ', '')
return r.status_code, time.time() - t, ok, r.text[:80].replace('\n', ' ')
login = {'nc': nc_login, 'sf': sf_login, 'oc': oc_login}[P]
if what == 'brute':
real = {'nc': 'NC_PASS', 'sf': 'SF_PASS', 'oc': 'OC_PASS'}[P]
print(f'# {T()} UTC: 10 falsche Passwörter für den Admin über das Anmeldeformular, danach das richtige')
for i in range(1, 11):
c, dt, ok, info = login(f'falsch-{i}-xyz')
print(f' {T()} Versuch {i:2d} falsch : HTTP {c}, Antwort nach {dt:6.2f} s, angemeldet={ok} {info}')
c, dt, ok, info = login(E[real])
print(f' {T()} Versuch 11 richtig: HTTP {c}, Antwort nach {dt:6.2f} s, angemeldet={ok} {info}')
if what == 'share' and P == 'nc':
u = E['NC_URL']; a = (E['NC_USER'], E['NC_PASS']); dav = f"{u}/remote.php/dav/files/{E['NC_USER']}"
requests.request('MKCOL', dav + '/freigabe', auth=a); requests.put(dav + '/freigabe/vertrag.txt', data=b'Vertrag Entwurf\n', auth=a)
print(f'# {T()} UTC: öffentlicher Link auf /freigabe, ohne Passwort und ohne Ablaufdatum angefordert (OCS-API, wie der Knopf in der Oberfläche)')
r = requests.post(u + '/ocs/v2.php/apps/files_sharing/api/v1/shares', auth=a, headers={'OCS-APIRequest': 'true', 'Accept': 'application/json'}, data={'path': '/freigabe', 'shareType': 3})
d = r.json()['ocs']; print(' HTTP', r.status_code, 'OCS', d['meta']['statuscode'], d['meta']['message'])
if d['data']:
x = d['data']; print(' expiration =', x.get('expiration'), '| password gesetzt =', bool(x.get('password')), '| permissions =', x.get('permissions'))
link = x['url']; r2 = requests.get(link); print(' anonymer Abruf des Links:', r2.status_code, '| Datei sichtbar:', 'vertrag.txt' in r2.text)
r = requests.get(u + '/ocs/v2.php/cloud/capabilities', auth=a, headers={'OCS-APIRequest': 'true', 'Accept': 'application/json'})
pub = r.json()['ocs']['data']['capabilities']['files_sharing']['public']
print(' capabilities public:', json.dumps({k: pub.get(k) for k in ('enabled', 'password', 'expire_date', 'upload')}))
if what == 'wrongonly': # wrongonly N: nur falsche Versuche, kein richtiger am Ende
n = int(sys.argv[3])
for i in range(1, n + 1):
c, dt, ok, info = login(f'falsch-{i}-xyz')
print(f' {T()} Versuch {i:2d} falsch : HTTP {c}, Antwort nach {dt:6.2f} s {info}', flush=True)
if what == 'share' and P == 'oc':
u = E['OC_URL']; a = (E['OC_USER'], E['OC_TOKEN']); sp = E['OC_SPACE']; dav = f"{u}/remote.php/dav/spaces/{sp}"
requests.request('MKCOL', dav + '/freigabe', auth=a); requests.put(dav + '/freigabe/vertrag.txt', data=b'Vertrag Entwurf\n', auth=a)
r = requests.request('PROPFIND', dav + '/freigabe', auth=a, headers={'Depth': '0'}, data='<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><oc:fileid/></d:prop></d:propfind>')
fid = re.search(r'<oc:fileid>([^<]+)</oc:fileid>', r.text).group(1)
print(f'# {T()} UTC: öffentlicher Link auf /freigabe, ohne Passwort und ohne Ablaufdatum angefordert (Graph-API createLink, wie der Knopf in der Oberfläche)')
r = requests.post(f"{u}/graph/v1beta1/drives/{sp}/items/{fid}/createLink", auth=a, json={'type': 'view'})
print(' type=view ohne Passwort: HTTP', r.status_code, r.text[:160].replace('\n', ' '))
r = requests.post(f"{u}/graph/v1beta1/drives/{sp}/items/{fid}/createLink", auth=a, json={'type': 'edit'})
print(' type=edit ohne Passwort: HTTP', r.status_code, r.text[:160].replace('\n', ' '))
r = requests.post(f"{u}/graph/v1beta1/drives/{sp}/items/{fid}/createLink", auth=a, json={'type': 'view', 'password': 'Lab-Passwort-19!x'})
j = r.json() if r.ok else {}
print(' type=view mit Passwort: HTTP', r.status_code, '| expirationDateTime =', j.get('expirationDateTime'), '| hasPassword =', j.get('hasPassword'))
r = requests.get(u + '/ocs/v1.php/cloud/capabilities?format=json', auth=a)
pub = r.json()['ocs']['data']['capabilities']['files_sharing']['public']
print(' capabilities public:', json.dumps({k: pub.get(k) for k in ('enabled', 'password', 'expire_date')}))
if what == 'share' and P == 'sf':
u = E['SF_URL']; h = {'Authorization': 'Token ' + E['SF_TOKEN'], 'Accept': 'application/json'}; rid = E['SF_REPO']
requests.post(f"{u}/api2/repos/{rid}/dir/?p=/freigabe", headers=h, data={'operation': 'mkdir'})
up = requests.get(f"{u}/api2/repos/{rid}/upload-link/?p=/freigabe", headers=h).json()
requests.post(up, headers=h, files={'file': ('vertrag.txt', b'Vertrag Entwurf\n')}, data={'parent_dir': '/freigabe'})
print(f'# {T()} UTC: öffentlicher Link auf /freigabe, ohne Passwort und ohne Ablaufdatum angefordert (API v2.1 share-links, wie der Knopf in der Oberfläche)')
r = requests.post(f"{u}/api/v2.1/share-links/", headers=h, json={'repo_id': rid, 'path': '/freigabe/'})
j = r.json(); print(' HTTP', r.status_code, '| is_expired =', j.get('is_expired'), '| expire_date =', j.get('expire_date'), '| password gesetzt =', bool(j.get('password')), '| permissions =', j.get('permissions'))
link = j.get('link')
if link:
r2 = requests.get(link); print(' anonymer Abruf des Links:', r2.status_code, '| Datei sichtbar:', 'vertrag.txt' in r2.text)