-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgit-protonmail
More file actions
executable file
·1724 lines (1459 loc) · 56 KB
/
git-protonmail
File metadata and controls
executable file
·1724 lines (1459 loc) · 56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright 2025 Aditya Garg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 only
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import base64
import bcrypt
import getpass
import hashlib
import json
import keyring
import os
import pickle
import random
import re
import string
import sys
import unicodedata
import warnings
warnings.filterwarnings("ignore", module="pgpy") # ignore deprecation warnings for pgpy
from base64 import b64decode, b64encode
from dataclasses import asdict, dataclass, field
from copy import deepcopy
from cryptography.hazmat.backends import default_backend
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from datetime import datetime
from email import message_from_file
from email.header import decode_header, make_header
from email.parser import Parser
from email.utils import getaddresses
from enum import Enum
from pgpy import PGPMessage, PGPKey
from requests import Session
from requests.models import Response
from requests_toolbelt import MultipartEncoder
from typing import Callable, Optional, Union
from typing_extensions import Self
"""Constants
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/constants.py
"""
PM_APP_VERSION_ACCOUNT = 'web-account@5.0.368.0'
# I used mitmproxy to find this version. URLs starting with 'https://mail.proton.me/api' have this version in the header.
# These days, opening all settings also shows this version.
PM_APP_VERSION_MAIL = 'web-mail@5.0.111.4'
# Can be found in Inbox on Proton Mail's website. Also seen in Activity monitor in Settings > Security and privacy.
PM_APP_VERSION_DEV = 'Other'
API_VERSION = '4'
SRP_LEN_BYTES = 256
SALT_LEN_BYTES = 10
DEFAULT_HEADERS = {
'authority': 'account.proton.me',
'accept': 'application/vnd.protonmail.v1+json',
'accept-language': 'en-US,en;q=0.5',
'content-type': 'application/json',
'origin': 'https://account.proton.me',
'referer': 'https://account.proton.me/mail',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36',
'x-pm-appversion': PM_APP_VERSION_ACCOUNT,
'x-pm-apiversion': API_VERSION,
'x-pm-locale': 'en_US',
}
urls_api = {
'api': 'https://api.protonmail.ch/api',
'mail': 'https://mail.proton.me/api',
'account': 'https://account.proton.me/api',
'account-api': 'https://account-api.proton.me',
'assets': 'https://account.proton.me/assets'
}
colors = {
"green": "\x1b[32m",
"red": "\x1b[31m",
"yellow": "\033[93m",
"bold": "\x1b[1m",
"reset": "\x1b[0m",
}
"""Exceptions
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/exceptions.py
"""
class SendMessageError(Exception):
"""Error when trying to send message"""
class InvalidPassword(Exception):
"""Invalid username or password"""
class InvalidTwoFactorCode(Exception):
"""Invalid Two-Factor Authentication (2FA) code"""
class NoKeysForDecryptThisMessage(Exception):
"""
No keys to decrypt this message
If you created a new key then you need to re-login
If you deleted the key then you can't decrypt this message
"""
class LoadSessionError(Exception):
"""Error while loading session, maybe this session file was created in other version? Try re-login."""
class AddressNotFound(Exception):
"""Email address was not found"""
class CantSolveImageCaptcha(Exception):
"""Error when trying to solve image CAPTCHA, maybe this image hard, just retry login"""
class InvalidCaptcha(Exception):
"""CAPTCHA solved, but something got wrong"""
"""Logger
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/logger.py
"""
class Logger:
"""
DEBUG = 1
INFO = 2
WARNING = 3
ERROR = 4
"""
def __init__(self, level, func):
self.level = level
self.func = func
self.do_color = func is print
def debug(self, status: str) -> None:
"""Debug."""
if self.level < 1:
return
self.func(status)
def info(self, status: str, color: str = 'reset') -> None:
"""Info."""
if self.level < 2:
return
if self.do_color:
status = f"{colors[color]}{status}{colors['reset']}"
self.func(status)
def warning(self, status: str, color: str = 'yellow') -> None:
"""Warning."""
if self.level < 3:
return
if self.do_color:
status = f"{colors[color]}{status}{colors['reset']}"
self.func(status)
def error(self, status: str, color: str = 'red') -> None:
"""Error."""
if self.level < 4:
return
if self.do_color:
status = f"{colors[color]}{status}{colors['reset']}"
self.func(status)
"""Dataclasses
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/models.py
"""
class LoginType(Enum):
"""
Login type
Attributes:
WEB: Harder auth, more requests, CAPTCHA like in web
DEV: Simpler auth, fewer requests, maybe more often CAPTCHA
"""
WEB = 'web'
DEV = 'dev'
def default_function_for_manual_solve_captcha(auth_data: dict) -> str:
"""Default function to manual solve CAPTCHA"""
print("Open the URL below on a web browser in incognito mode:")
print(f"URL: {auth_data['Details']['WebUrl']}\n")
print("Follow the instructions on https://github.com/opulentfox-29/protonmail-api-client/blob/master/README.md#captcha to get token.")
token_from_init = input('Enter the token: ')
return token_from_init
def get_token_from_url(url):
import urllib.parse
parsed_url = urllib.parse.urlparse(url)
parsed_query = urllib.parse.parse_qs(parsed_url.query)
return parsed_query.get('token', [''])[0]
def default_function_for_pyqt_solve_captcha(auth_data: dict) -> str:
"""Default function to solve CAPTCHA using Qt WebEngine"""
import os
import sys
try:
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import QWebEngineUrlRequestInterceptor, QWebEngineProfile, QWebEnginePage
from PyQt6.QtCore import QUrl, QLoggingCategory
except Exception:
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEngineUrlRequestInterceptor, QWebEngineProfile, QWebEnginePage
from PySide6.QtCore import QUrl, QLoggingCategory
QLoggingCategory("qt.webenginecontext").setFilterRules("*.info=false")
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = f"--enable-logging --log-level=3"
url = auth_data['Details']['WebUrl']
print("Opening a browser window to solve CAPTCHA...")
class QuietWebEnginePage(QWebEnginePage):
#js messages spam the console for no reason
def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID):
return
class RequestInterceptor(QWebEngineUrlRequestInterceptor):
def __init__(self):
super().__init__()
self.token = ''
def interceptRequest(self, info):
url_str = info.requestUrl().toString()
if "verify-api.proton.me/captcha/v1/api/bg" in url_str:
# This URL has the token we need
self.token = get_token_from_url(url_str)
if "verify-api.proton.me/captcha/v1/api/finalize" in url_str:
# This URL is when the CAPTCHA is solved, we can quit the app
QApplication.instance().quit()
class BrowserWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("OAuth2 Login")
self.resize(800, 600)
self.browser = QWebEngineView()
self.browser.setPage(QuietWebEnginePage(self.browser))
self.setCentralWidget(self.browser)
self.browser.load(QUrl(url))
self.show()
webapp = QApplication(sys.argv)
interceptor = RequestInterceptor()
QWebEngineProfile.defaultProfile().setUrlRequestInterceptor(interceptor)
window = BrowserWindow()
webapp.exec()
return interceptor.token
@dataclass
class CaptchaConfig:
"""Config to solve CAPTCHA"""
class CaptchaType(Enum):
"""
CAPTCHA solve type
Attributes:
MANUAL: Manual CAPTCHA solution. Requires additional actions from you, read more: https://github.com/opulentfox-29/protonmail-api-client?tab=readme-ov-file#solve-captcha
PYQT: Use Qt6 WebEngine to solve CAPTCHA.
"""
MANUAL = 'manual'
PYQT = 'pyqt'
type: CaptchaType = CaptchaType.PYQT
function_for_manual: Callable = default_function_for_manual_solve_captcha
function_for_pyqt: Callable = default_function_for_pyqt_solve_captcha
@dataclass
class UserMail:
"""User"""
name: str = ''
address: str = ''
extra: dict = field(default_factory=dict)
def __str__(self):
return f"<UserMail [{self.address}]>"
def to_dict(self) -> dict[str, any]:
"""
Object to dict
:returns: :py:obj:`dict`
"""
return asdict(self)
@dataclass
class AccountAddress:
"""One user can have many addresses"""
id: str = ''
email: str = ''
name: str = ''
def __str__(self):
return f"<AccountAddress [{self.email}, {self.name}]>"
def to_dict(self) -> dict[str, any]:
"""
Object to dict
:returns: :py:obj:`dict`
"""
return asdict(self)
@dataclass
class Message:
"""Message"""
id: str = ''
conversation_id: str = ''
subject: str = ''
unread: bool = False
sender: UserMail = field(default_factory=UserMail)
recipients: list[UserMail] = field(default_factory=list)
cc: list[UserMail] = field(default_factory=list)
bcc: list[UserMail] = field(default_factory=list)
time: int = 0
size: int = 0
body: str = ''
type: str = ''
external_id: str = ''
in_reply_to: str = ''
extra: dict = field(default_factory=dict)
def __str__(self):
ellipsis_str = '...' if len(self.subject) > 20 else ','
cropped_subject = self.subject[:20]
return f"<Message [{cropped_subject}{ellipsis_str} id: {self.id[:10]}...]>"
def to_dict(self) -> dict[str, any]:
"""
Object to dict
:returns: :py:obj:`dict`
"""
return asdict(self)
@dataclass
class PgpPairKeys:
"""PGP pair keys"""
is_primary: bool = False
is_user_key: bool = False
fingerprint_public: Optional[str] = None
fingerprint_private: Optional[str] = None
public_key: Optional[str] = None
private_key: Optional[str] = None
passphrase: Optional[str] = None
email: Optional[str] = None
def __str__(self):
fingerprint = self.fingerprint_private or self.fingerprint_public
return f"<PGPKey [{fingerprint or None}, is_primary: {self.is_primary}, is_user_key: {self.is_user_key}]>"
def to_dict(self) -> dict[str, any]:
"""
Object to dict
:returns: :py:obj:`dict`
"""
return asdict(self)
"""PGP
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/pgp.py
"""
class PGP:
def __init__(self):
self.iv = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
self.pairs_keys: list[PgpPairKeys] = list()
self.aes256_keys = dict()
def decrypt(self, data: str, private_key: Optional[str] = None, passphrase: Optional[str] = None) -> str:
"""Decrypt pgp with private key & passphrase."""
encrypted_message = self.message(data)
if not private_key:
fingerprint = self._get_public_fingerprint_from_message(encrypted_message)
pair = self._get_pair_keys(fingerprint=fingerprint)
if pair is None:
raise NoKeysForDecryptThisMessage(NoKeysForDecryptThisMessage.__doc__, 'you need private key for public key:', fingerprint)
private_key = pair.private_key
passphrase = pair.passphrase
pgp_private_key, _ = self.key(private_key)
with pgp_private_key.unlock(passphrase) as key:
message = key.decrypt(encrypted_message).message
# Some messages are encoded in latin_1, so we will recode them in utf-8
try:
if not isinstance(message, str):
message = message.decode('utf-8')
message = message.encode('latin_1').decode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
pass
return message
def encrypt(self, data: str, account_address: Optional[AccountAddress] = None, public_key: Optional[str] = None) -> str:
"""Encrypt pgp with public key."""
if not public_key:
public_key = self._get_pair_keys(is_primary=True, account_address=account_address).public_key
public_key, _ = self.key(public_key)
message = self.create_message(data)
encrypted_message = str(public_key.encrypt(message))
return encrypted_message
def decrypt_session_key(self, encrypted_key: str) -> bytes:
"""Decrypt session key."""
if self.aes256_keys.get(encrypted_key):
return self.aes256_keys[encrypted_key]
encrypted_message = self.message(b64decode(encrypted_key))
fingerprint = self._get_public_fingerprint_from_message(encrypted_message)
pair_keys = self._get_pair_keys(fingerprint=fingerprint)
pgp_private_key, _ = self.key(pair_keys.private_key)
with pgp_private_key.unlock(pair_keys.passphrase) as key:
subkey = tuple(dict(key.subkeys).values())[0]
pkesk = encrypted_message._sessionkeys[0]
alg, aes256_key = pkesk.decrypt_sk(subkey._key)
return aes256_key
def encrypt_session_key(self, session_key: bytes, account_address: Optional[AccountAddress] = None, public_key: Optional[Union[str, PGPKey]] = None) -> bytes:
"""Encrypt session key."""
if not public_key:
public_key = self._get_pair_keys(is_primary=True, account_address=account_address).public_key
if isinstance(public_key, str):
public_key, _ = self.key(public_key)
message = self.create_message('message for encrypt')
encrypted_message = public_key.encrypt(message, sessionkey=session_key)
encrypted_session_key = bytes(encrypted_message._sessionkeys[0])
return encrypted_session_key
def encrypt_with_session_key(self, message: str, account_address: Optional[AccountAddress] = None, session_key: Optional[bytes] = None) -> tuple[bytes, bytes, bytes]:
"""Encrypt message with session key"""
if not session_key:
session_key = os.urandom(32)
pgp_message = self.create_message(message)
pair_keys = self._get_pair_keys(is_primary=True, account_address=account_address)
pgp_private_key, _ = self.key(pair_keys.private_key)
with pgp_private_key.unlock(pair_keys.passphrase) as key:
pgp_message |= key.sign(pgp_message)
signature = bytes(pgp_message.signatures[0])
encrypted_message = pgp_message.encrypt(pair_keys.passphrase, session_key)
lines_encrypted_message_pgp = str(encrypted_message).split('\n')
del lines_encrypted_message_pgp[2] # delete information from PGPy (OpenPGP.js doesn't have it), Proton Mail doesn't work with it
encrypted_message_pgp = '\n'.join(lines_encrypted_message_pgp)
encrypted_message = self.message(encrypted_message_pgp)
return bytes(encrypted_message), session_key, signature
def aes256_decrypt(self, data: bytes, key: bytes) -> Union[bytes, int]:
"""Decrypt AES256."""
decryptor = Cipher(
algorithms.AES(key),
modes.CFB(self.iv),
backend=default_backend()
).decryptor()
decrypted_data = decryptor.update(data) + decryptor.finalize()
return decrypted_data[18:-22]
def aes256_encrypt(self, message: str, session_key: Optional[bytes] = None) -> tuple[bytes, bytes]:
"""Encrypt AES256."""
if not session_key:
session_key = os.urandom(32)
binary_message = message.encode() if isinstance(message, str) else message
encryptor = Cipher(
algorithms.AES(session_key),
modes.CFB(self.iv),
backend=default_backend()
).encryptor()
encrypted_message = encryptor.update(binary_message) + encryptor.finalize()
body_key = b64encode(session_key)
return encrypted_message, body_key
def aes_gcm_encrypt(self, message: str, session_key: Optional[bytes] = None) -> bytes:
"""Encrypt AES GCM."""
if not session_key:
session_key = os.urandom(32)
iv = os.urandom(16)
aesgcm = AESGCM(session_key)
binary_message = message.encode() if isinstance(message, str) else message
encrypted_message = aesgcm.encrypt(iv, binary_message, None)
iv_and_message = iv + encrypted_message
return iv_and_message
@staticmethod
def create_message(blob: any):
"""Create new pgp message from blob."""
return PGPMessage.new(blob, compression=False)
@staticmethod
def message(blob: any) -> PGPMessage:
"""Load pgp message from blob."""
return PGPMessage.from_blob(blob)
@staticmethod
def key(blob: any) -> PGPKey:
"""Load pgp key from blob."""
return PGPKey.from_blob(blob)
def _get_pair_keys(self, fingerprint: Optional[str] = None, is_primary: Optional[bool] = None, is_user_key: bool = False, account_address: Optional[AccountAddress] = None) -> Optional[PgpPairKeys]:
for pair in self.pairs_keys:
if is_primary is not None and is_primary != pair.is_primary:
continue
if pair.is_user_key != is_user_key:
continue
if account_address is not None and pair.email != account_address.email:
continue
fingerprint_public = pair.fingerprint_public or str()
fingerprint_private = pair.fingerprint_private or str()
if fingerprint is not None and fingerprint[-16:].upper() not in (fingerprint_public[-16:].upper(), fingerprint_private[-16:].upper()):
continue
return pair
return None
def _get_public_fingerprint_from_message(self, message: PGPMessage) -> str:
fingerprint = list(message.issuers)[0]
return fingerprint
"""Utils downloaded from the official repository:
https://github.com/ProtonMail/proton-python-client/blob/master/proton/srp/util.py
https://github.com/ProtonMail/proton-python-client/blob/master/proton/srp/pmhash.py
Modified here:
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/utils/utils.py
"""
class PMHash:
"""Custom expanded version of SHA512"""
def __init__(self, binary: bytes = b''):
self.binary = binary
def update(self, binary: bytes) -> None:
self.binary += binary
def digest(self) -> bytes:
return b''.join([
hashlib.sha512(self.binary + b'\0').digest(),
hashlib.sha512(self.binary + b'\1').digest(),
hashlib.sha512(self.binary + b'\2').digest(),
hashlib.sha512(self.binary + b'\3').digest()
])
def pm_hash(binary: bytes = b'') -> object:
return PMHash(binary)
def bcrypt_b64_encode(binary: bytes) -> bytes:
bcrypt_base64 = b'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' # noqa
std_base64chars = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' # noqa
binary = base64.b64encode(binary)
return binary.translate(bytes.maketrans(std_base64chars, bcrypt_base64))
def hash_password(hash_class: callable, password: bytes, salt: bytes, modulus: bytes) -> bytes:
salt = (salt + b'proton')[:16]
salt = bcrypt_b64_encode(salt)[:22]
hashed = bcrypt.hashpw(password, b'$2y$10$' + salt)
return hash_class(hashed + modulus).digest()
def bytes_to_long(binary: bytes) -> int:
return int.from_bytes(binary, 'little')
def long_to_bytes(num: int, num_bytes: int) -> bytes:
return num.to_bytes(num_bytes, 'little')
def get_random(num_bytes: int) -> int:
return bytes_to_long(os.urandom(num_bytes))
def get_random_of_length(num_bytes: int) -> int:
offset = (num_bytes * 8) - 1
return get_random(num_bytes) | (1 << offset)
def custom_hash(hash_class: callable, *args: int) -> int:
hashed = hash_class()
for i in args:
if i is not None:
data = long_to_bytes(i, SRP_LEN_BYTES) if isinstance(i, int) else i
hashed.update(data)
return bytes_to_long(hashed.digest())
def delete_duplicates_cookies_and_reset_domain(func):
def wrapper(self: Self, *args, **kwargs):
response = func(self, *args, **kwargs)
current_cookies: dict = self.session.cookies.get_dict()
new_cookies: dict = response.cookies.get_dict()
current_cookies.update(new_cookies) # cookies without duplicates
self.session.cookies.clear()
for name, value in current_cookies.items():
self.session.cookies.set(name=name, value=value) # reset domain
return response
return wrapper
"""Secure Remote Password(SRP) downloaded from the official repository:
https://github.com/ProtonMail/proton-python-client/blob/master/proton/srp/_pysrp.py
Modified here:
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/utils/pysrp.py
N A large safe prime (N = 2q+1, where q is prime)
All arithmetic is done modulo N.
g A generator modulo N
k Multiplier parameter (k = H(N, g) in SRP-6a, k = 3 for legacy SRP-6)
s User's salt
I Username
p Cleartext Password
H() One-way hash function
^ (Modular) Exponentiation
u Random scrambling parameter
a,b Secret ephemeral values
A,B Public ephemeral values
x Private key (derived from p and s)
v Password verifier
"""
def get_ng(modulus_bin: bytes, g_hex: bytes) -> tuple[int, int]:
return bytes_to_long(modulus_bin), int(g_hex, 16)
def hash_k(hash_class: callable, g: int, modulus: int, width: int) -> int:
hashed = hash_class()
hashed.update(g.to_bytes(width, 'little'))
hashed.update(modulus.to_bytes(width, 'little'))
return bytes_to_long(hashed.digest())
def password_hasher(hash_class: callable, salt: bytes, password: bytes, modulus: int) -> int:
hashed_password = hash_password(
hash_class,
password,
salt,
long_to_bytes(modulus, SRP_LEN_BYTES),
)
return bytes_to_long(hashed_password)
def calculate_client_proof(hash_class: callable, challenge_int: int, server_challenge_int: int, session_key: bytes) -> bytes:
hashed = hash_class()
hashed.update(long_to_bytes(challenge_int, SRP_LEN_BYTES))
hashed.update(long_to_bytes(server_challenge_int, SRP_LEN_BYTES))
hashed.update(session_key)
return hashed.digest()
def calculate_server_proof(hash_class: callable, challenge_int: int, client_proof: bytes, session_key: bytes) -> bytes:
hashed = hash_class()
hashed.update(long_to_bytes(challenge_int, SRP_LEN_BYTES))
hashed.update(client_proof)
hashed.update(session_key)
return hashed.digest()
class User:
def __init__(self, password: str, modulus_bin: bytes, g_hex: bytes = b"2"):
self.password: bin = password.encode()
self.hash_class = pm_hash
self.modulus_int, self.g = get_ng(modulus_bin, g_hex)
self.k = hash_k(self.hash_class, self.g, self.modulus_int, SRP_LEN_BYTES)
self.random_int = get_random_of_length(32)
self.challenge_int = pow(self.g, self.random_int, self.modulus_int)
self.expected_server_proof = None
self._authenticated = False
self.bytes_s = None
self.v = None
self.client_proof = None
self.session_key = None
self.S = None
self.server_challenge_int = None
self.hashed_server_challenge = None
self.hashed_password = None
def authenticated(self) -> bool:
return self._authenticated
def get_challenge(self) -> bytes:
return long_to_bytes(self.challenge_int, SRP_LEN_BYTES)
def process_challenge(self, bytes_s: bytes, bytes_server_challenge: bytes) -> Union[bytes, None]:
"""Returns M or None if SRP-6a safety check is violated."""
self.bytes_s = bytes_s
self.server_challenge_int = bytes_to_long(bytes_server_challenge)
# SRP-6a safety check
if (self.server_challenge_int % self.modulus_int) == 0:
return None
self.hashed_server_challenge = custom_hash(
self.hash_class,
self.challenge_int,
self.server_challenge_int
)
# SRP-6a safety check
if self.hashed_server_challenge == 0:
return None
self.hashed_password = password_hasher(
self.hash_class,
self.bytes_s,
self.password,
self.modulus_int
)
self.v = pow(self.g, self.hashed_password, self.modulus_int)
self.S = pow(
(self.server_challenge_int - self.k * self.v),
(self.random_int + self.hashed_server_challenge * self.hashed_password),
self.modulus_int
)
self.session_key = long_to_bytes(self.S, SRP_LEN_BYTES)
self.client_proof = calculate_client_proof(
self.hash_class,
self.challenge_int,
self.server_challenge_int,
self.session_key
)
self.expected_server_proof = calculate_server_proof(
self.hash_class,
self.challenge_int,
self.client_proof,
self.session_key
)
return self.client_proof
def verify_session(self, server_proof: bytes) -> None:
if self.expected_server_proof == server_proof:
self._authenticated = True
def compute_v(self, bytes_s: Optional[bytes] = None) -> tuple[bytes, bytes]:
if bytes_s is None:
self.bytes_s = long_to_bytes(
get_random_of_length(SALT_LEN_BYTES),
SALT_LEN_BYTES
)
else:
self.bytes_s = bytes_s
self.hashed_password = password_hasher(
self.hash_class,
self.bytes_s,
self.password,
self.modulus_int
)
return (
self.bytes_s,
long_to_bytes(pow(self.g, self.hashed_password, self.modulus_int), SRP_LEN_BYTES)
)
def get_ephemeral_secret(self) -> bytes:
return long_to_bytes(self.random_int, SRP_LEN_BYTES)
def get_session_key(self) -> Union[bytes, None]:
return self.session_key if self._authenticated else None
"""Client for Proton Mail API
https://github.com/opulentfox-29/protonmail-api-client/blob/master/src/protonmail/client.py
"""
class ProtonMail:
"""
Client for api protonmail.
"""
def __init__(self, proxy: Optional[str] = None, logging_level: Optional[int] = 2, logging_func: Optional[callable] = print):
"""
:param proxy: proxy for all requests, template: ``http://Username:Password@host-or-ip.com:port``
:type proxy: ``str``
:param logging_level: logging level 1-4 (DEBUG, INFO, WARNING, ERROR), default 2[INFO].
:type logging_level: ``int``
:param logging_func: logging function. default print.
:type logging_func: ``callable``
"""
self.logger = Logger(logging_level, logging_func)
self.proxy = proxy
self.pgp = PGP()
self.user = None
self._session_path = None
self._session_auto_save = False
self.account_addresses: list[AccountAddress] = []
self.session = Session()
self.session.proxies = {'http': self.proxy, 'https': self.proxy} if self.proxy else dict()
self.session.headers.update(DEFAULT_HEADERS)
def login(self, username: str, password: str, getter_2fa_code: callable = lambda: input("enter 2FA code:"), login_type: LoginType = LoginType.WEB,
captcha_config: CaptchaConfig = CaptchaConfig()) -> None:
"""
Authorization in Proton Mail.
:param username: your Proton Mail address.
:type username: ``str``
:param password: your password.
:type password: ``str``
:param getter_2fa_code: function to get Two-Factor Authentication(2FA) code. default: input
:type getter_2fa_code: ``callable``
:param login_type: Type for login, dev - simple login, fewer requests but maybe often CAPTCHA, web - more requests, CAPTCHA like in web. default: WEB
:type login_type: ``Enum: LoginType``
:param captcha_config: Config for CAPTCHA resolver (manual or pyqt). Default: pyqt. More: https://github.com/opulentfox-29/protonmail-api-client?tab=readme-ov-file#solve-captcha
:type login_type: ``CaptchaConfig``
:returns: :py:obj:`None`
"""
self.session.headers['x-pm-appversion'] = PM_APP_VERSION_DEV
if login_type == LoginType.WEB:
self.session.headers['x-pm-appversion'] = PM_APP_VERSION_ACCOUNT
anonym_session_info = self._crate_anonym_session()
self._get_tokens(anonym_session_info) # Cookies for anonym user (not logged in the account yet)
data = {'Username': username}
info = self._post('account', 'core/v4/auth/info', json=data).json()
client_challenge, client_proof, spr_session = self._parse_info_before_login(info, password)
auth = self._post('account', 'core/v4/auth', json={
'Username': username,
'ClientEphemeral': client_challenge,
'ClientProof': client_proof,
'SRPSession': spr_session,
'PersistentCookies': 1,
}).json()
if auth['Code'] == 9001: # Captcha
self._captcha_processing(auth, captcha_config)
auth = self._post('account', 'core/v4/auth', json={
'Username': username,
'ClientEphemeral': client_challenge,
'ClientProof': client_proof,
'SRPSession': spr_session,
'PersistentCookies': 1,
}).json()
if self._login_process(auth):
self.logger.info("Login success", "green")
else:
self.logger.error("Login failure", "red")
if login_type == LoginType.DEV:
self._get_tokens(auth)
if auth["TwoFactor"]:
if not auth["2FA"]["TOTP"]:
raise NotImplementedError("Only TOTP is supported as Two-Factor Authentication(2FA) method. Disable FIDO2/U2F.")
domain = 'account' if login_type == LoginType.WEB else 'mail'
response_2fa = self._post(domain, 'core/v4/auth/2fa', json={'TwoFactorCode': getter_2fa_code()})
if response_2fa.status_code != 200:
raise InvalidTwoFactorCode(f"Invalid Two-Factor Authentication(2FA) code: {response_2fa.json()['Error']}")
user_private_key_password = self._get_user_private_key_password(password)
if login_type == LoginType.WEB:
user_pk_password_data = {'type': 'default', 'keyPassword': user_private_key_password}
encrypted_user_pk_password_data = self.pgp.aes_gcm_encrypt(json.dumps(user_pk_password_data, separators=(',', ':')))
b64_encrypted_user_pk_password_data = b64encode(encrypted_user_pk_password_data).decode()
payload_for_create_fork = {
'Payload': b64_encrypted_user_pk_password_data,
'ChildClientID': 'web-mail',
'Independent': 0,
}
response_data = self._post('account', 'auth/v4/sessions/forks', json=payload_for_create_fork).json()
self.session.headers['x-pm-appversion'] = PM_APP_VERSION_MAIL
fork_data = self._get('mail', f"auth/v4/sessions/forks/{response_data['Selector']}").json()
self._get_tokens(fork_data)
self._parse_info_after_login(password, user_private_key_password)
def send_message(self, message: Message, delivery_time: Optional[int] = None, account_address: Optional[AccountAddress] = None) -> Message:
"""
Send the message.
:param message: The message you want to send.
:type message: ``Message``
:param delivery_time: timestamp (seconds) for scheduled delivery message, default: None (send now)
:type delivery_time: ``int``
:param account_address: If you have more than 1 address for 1 account (premium only), you can choose which address to send messages from,
default: None (send from first address)
:type account_address: ``AccountAddress``
:returns: :py:obj:`Message`
"""
if delivery_time and delivery_time <= datetime.now().timestamp():
raise ValueError(f"Delivery time ({delivery_time}) is less than current time. You can't send message to the past!")
recipients_info = []
for recipient in message.recipients + message.cc + message.bcc:
recipient_info = self.__check_email_address(recipient)
recipients_info.append({
'address': recipient.address,
'type': 1 if recipient_info['RecipientType'] == 1 else 4,
'public_key': recipient_info['Keys'][0]['PublicKey'] if recipient_info['Keys'] else None,
})
if not account_address:
account_address = self.account_addresses[0]
draft = self.create_draft(message, decrypt_body=False, account_address=account_address)
multipart = self._multipart_encrypt(message, recipients_info, account_address=account_address, delivery_time=delivery_time)
headers = {
"Content-Type": multipart.content_type
}
params = {
'Source': 'composer',
}
response = self._post(
'mail',
f'mail/v4/messages/{draft.id}',
headers=headers,
params=params,
data=multipart
).json()
if response.get('Error'):
raise SendMessageError(f"Can't send message: {response['Error']}")
sent_message_dict = response['Sent']
sent_message = self._convert_dict_to_message(sent_message_dict)
sent_message.body = self.pgp.decrypt(sent_message.body)
self._multipart_decrypt(sent_message)
return sent_message
def create_draft(self, message: Message, decrypt_body: Optional[bool] = True, account_address: Optional[AccountAddress] = None) -> Message:
"""Create the draft."""
if not account_address:
account_address = self.account_addresses[0]
pgp_body = self.pgp.encrypt(message.body, account_address=account_address)
# Sanitize external_id and in_reply_to if present
external_id = message.external_id
if external_id and external_id.startswith('<') and external_id.endswith('>'):
external_id = external_id[1:-1]
in_reply_to = message.in_reply_to
if in_reply_to and in_reply_to.startswith('<') and in_reply_to.endswith('>'):
in_reply_to = in_reply_to[1:-1]
parent_id = None
if in_reply_to:
# Search for parent message by ExternalID
filter_params = {
"Page": 0,
"PageSize": 1,
"ExternalID": in_reply_to,
"AddressID": account_address.id,
}
resp = self._get('mail', 'mail/v4/messages', params=filter_params).json()
msgs = resp.get("Messages", [])
if msgs:
parent_id = msgs[0]["ID"]
else:
parent_id = in_reply_to
data = {
'Message': {
'ToList': [],
'CCList': [],
'BCCList': [],
'Subject': message.subject,
'MIMEType': 'text/plain',
'RightToLeft': 0,
'Sender': {
'Name': account_address.name,
'Address': account_address.email,
},
'AddressID': account_address.id,
'Unread': 0,
'Body': pgp_body,