| 1 |
""" |
| 2 |
Copyright (c) 2023 Proton AG |
| 3 |
|
| 4 |
This file is part of Proton. |
| 5 |
|
| 6 |
Proton is free software: you can redistribute it and/or modify |
| 7 |
it under the terms of the GNU General Public License as published by |
| 8 |
the Free Software Foundation, either version 3 of the License, or |
| 9 |
(at your option) any later version. |
| 10 |
|
| 11 |
Proton is distributed in the hope that it will be useful, |
| 12 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
GNU General Public License for more details. |
| 15 |
|
| 16 |
You should have received a copy of the GNU General Public License |
| 17 |
along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>. |
| 18 |
""" |
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
from proton.session.formdata import FormData |
| 22 |
from .. import Session |
| 23 |
from ..exceptions import * |
| 24 |
from .base import Transport, RawResponse |
| 25 |
|
| 26 |
import json, base64, asyncio, aiohttp, hashlib |
| 27 |
from OpenSSL import crypto |
| 28 |
from typing import Iterable, Union, Optional |
| 29 |
|
| 30 |
NOT_MODIFIED = 304 |
| 31 |
|
| 32 |
# It's stupid, but we have to inherit from aiohttp.Fingerprint to trigger the correct logic in aiohttp |
| 33 |
class AiohttpCertkeyFingerprint(aiohttp.Fingerprint): |
| 34 |
def __init__(self, fingerprints: Optional[Iterable[Union[bytes, str]]]) -> None: |
| 35 |
if fingerprints is not None: |
| 36 |
self._fingerprints = [] |
| 37 |
for fp in fingerprints: |
| 38 |
if type(fp) == str: |
| 39 |
self._fingerprints.append(base64.b64decode(fp)) |
| 40 |
else: |
| 41 |
self._fingerprints.append(fp) |
| 42 |
else: |
| 43 |
self._fingerprints = None |
| 44 |
|
| 45 |
def check(self, transport: asyncio.Transport) -> None: |
| 46 |
if not transport.get_extra_info("sslcontext"): |
| 47 |
return |
| 48 |
# Can't check anything if we don't have fingerprints |
| 49 |
if self._fingerprints is None: |
| 50 |
return |
| 51 |
sslobj = transport.get_extra_info("ssl_object") |
| 52 |
cert = sslobj.getpeercert(binary_form=True) |
| 53 |
|
| 54 |
cert_obj = crypto.load_certificate(crypto.FILETYPE_ASN1, cert) |
| 55 |
pubkey_obj = cert_obj.get_pubkey() |
| 56 |
pubkey = crypto.dump_publickey(crypto.FILETYPE_ASN1, pubkey_obj) |
| 57 |
|
| 58 |
pubkey_hash = hashlib.sha256(pubkey).digest() |
| 59 |
|
| 60 |
if pubkey_hash not in self._fingerprints: |
| 61 |
# Dump certificate, so we can diagnose if needed with: |
| 62 |
# base64 -d|openssl x509 -text -inform DER |
| 63 |
raise ProtonAPINotReachable(f"TLS pinning verification failed: {base64.b64encode(cert)}") |
| 64 |
|
| 65 |
|
| 66 |
class AiohttpTransport(Transport): |
| 67 |
def __init__(self, session: Session, form_data_transformer: FormDataTransformer = None): |
| 68 |
super().__init__(session) |
| 69 |
self._form_data_transformer = form_data_transformer or FormDataTransformer() |
| 70 |
|
| 71 |
@classmethod |
| 72 |
def _get_priority(cls): |
| 73 |
return 10 |
| 74 |
|
| 75 |
@property |
| 76 |
def tls_pinning_hashes(self): |
| 77 |
return self._environment.tls_pinning_hashes |
| 78 |
|
| 79 |
@property |
| 80 |
def http_base_url(self): |
| 81 |
return self._environment.http_base_url |
| 82 |
|
| 83 |
async def async_api_request( |
| 84 |
self, endpoint, |
| 85 |
jsondata=None, data=None, additional_headers=None, |
| 86 |
method=None, params=None, return_raw=False |
| 87 |
) -> dict | RawResponse: |
| 88 |
if self.tls_pinning_hashes is not None: |
| 89 |
ssl_specs = AiohttpCertkeyFingerprint(self.tls_pinning_hashes) |
| 90 |
else: |
| 91 |
# Validate SSL normally if we didn't have fingerprints |
| 92 |
import ssl |
| 93 |
ssl_specs = ssl.create_default_context() |
| 94 |
ssl_specs.verify_mode = ssl.CERT_REQUIRED |
| 95 |
|
| 96 |
headers = { |
| 97 |
'x-pm-appversion': self._session.appversion, |
| 98 |
'User-Agent': self._session.user_agent, |
| 99 |
} |
| 100 |
if self._session.authenticated: |
| 101 |
headers['x-pm-uid'] = self._session.UID |
| 102 |
headers['Authorization'] = 'Bearer ' + self._session.AccessToken |
| 103 |
headers.update(self._environment.http_extra_headers) |
| 104 |
|
| 105 |
async with aiohttp.ClientSession(headers=headers) as s: |
| 106 |
# If we don't have an explicit method, default to get if there's no data, post otherwise |
| 107 |
if method is None: |
| 108 |
if not jsondata and not data: |
| 109 |
fct = s.get |
| 110 |
else: |
| 111 |
fct = s.post |
| 112 |
else: |
| 113 |
fct = { |
| 114 |
'get': s.get, |
| 115 |
'post': s.post, |
| 116 |
'put': s.put, |
| 117 |
'delete': s.delete, |
| 118 |
'patch': s.patch |
| 119 |
}.get(method.lower()) |
| 120 |
|
| 121 |
if fct is None: |
| 122 |
raise ValueError("Unknown method: {}".format(method)) |
| 123 |
|
| 124 |
form_data = self._form_data_transformer.to_aiohttp_form_data(data) if data else None |
| 125 |
|
| 126 |
try: |
| 127 |
async with fct( |
| 128 |
self.http_base_url + endpoint, headers=additional_headers, |
| 129 |
json=jsondata, data=form_data, params=params, ssl=ssl_specs |
| 130 |
) as ret: |
| 131 |
if return_raw: |
| 132 |
return await self._build_raw(ret) |
| 133 |
|
| 134 |
ret_json = await self._parse_json(ret) |
| 135 |
|
| 136 |
return ret_json |
| 137 |
except aiohttp.ClientError as e: |
| 138 |
raise ProtonAPINotReachable("Connection error.") from e |
| 139 |
except asyncio.TimeoutError as e: |
| 140 |
raise ProtonAPINotReachable("Timeout error.") from e |
| 141 |
except ProtonAPINotReachable: |
| 142 |
raise |
| 143 |
except ProtonAPIError: |
| 144 |
raise |
| 145 |
except Exception as e: |
| 146 |
raise ProtonAPIUnexpectedError(e) |
| 147 |
|
| 148 |
async def _build_raw(self, ret): |
| 149 |
response = RawResponse(ret.status, |
| 150 |
tuple(ret.headers.items()), None, None) |
| 151 |
|
| 152 |
if ret.status == NOT_MODIFIED: |
| 153 |
return response |
| 154 |
|
| 155 |
response.data = await ret.read() |
| 156 |
|
| 157 |
if ret.headers['content-type'] != 'application/octet-stream': |
| 158 |
response.json = await self._parse_json(ret, allow_unmodified=True) |
| 159 |
|
| 160 |
return response |
| 161 |
|
| 162 |
async def _parse_json(self, ret, allow_unmodified=False): |
| 163 |
if ret.headers['content-type'] != 'application/json': |
| 164 |
raise ProtonAPINotReachable("API returned non-json results") |
| 165 |
try: |
| 166 |
ret_json = await ret.json() |
| 167 |
except json.decoder.JSONDecodeError: |
| 168 |
raise ProtonAPIError(ret.status, dict(ret.headers), {}) |
| 169 |
|
| 170 |
if ret_json['Code'] not in [1000, 1001]: |
| 171 |
raise ProtonAPIError(ret.status, dict(ret.headers), ret_json) |
| 172 |
|
| 173 |
return ret_json |
| 174 |
|
| 175 |
|
| 176 |
class FormDataTransformer: |
| 177 |
@staticmethod |
| 178 |
def to_aiohttp_form_data(form_data: FormData) -> aiohttp.FormData: |
| 179 |
""" |
| 180 |
Converts proton.session.data.FormData into aiohttp.FormData. |
| 181 |
https://docs.aiohttp.org/en/stable/client_reference.html#formdata |
| 182 |
""" |
| 183 |
result = aiohttp.FormData() |
| 184 |
for field in form_data.fields: |
| 185 |
result.add_field( |
| 186 |
name=field.name, value=field.value, |
| 187 |
content_type=field.content_type, filename=field.filename |
| 188 |
) |
| 189 |
return result |