1# Copyright (c) 2023, exiledkingcc
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright notice,
9# this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above copyright notice,
11# this list of conditions and the following disclaimer in the documentation
12# and/or other materials provided with the distribution.
13# * The name of the author may not be used to endorse or promote products
14# derived from this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26# POSSIBILITY OF SUCH DAMAGE.
27
28import secrets
29
30from cryptography import __version__
31from cryptography.exceptions import UnsupportedAlgorithm
32from cryptography.hazmat.decrepit.ciphers.algorithms import ARC4
33from cryptography.hazmat.primitives.ciphers.algorithms import AES
34from cryptography.hazmat.primitives.ciphers.base import Cipher
35from cryptography.hazmat.primitives.ciphers.modes import CBC, ECB
36from cryptography.hazmat.primitives.padding import PKCS7
37
38from pypdf._crypt_providers._base import CryptBase
39from pypdf._utils import logger_warning
40from pypdf.errors import PdfStreamError
41
42crypt_provider = ("cryptography", __version__)
43_warned_rc4_key_sizes: set[int] = set()
44
45
46def _needs_rc4_key_length_fallback(key: bytes) -> bool:
47 """Detect and warn about PDF RC4 keys that cryptography cannot handle."""
48 key_size = len(key) * 8
49 # ISO 32000-1:2008, Table 20: RC4 file keys are 40 to 128 bits in steps of 8.
50 # Section 7.6.2, Algorithm 1(d), caps the derived object key at 16 bytes.
51 if not 40 <= key_size <= 128 or key_size in ARC4.key_sizes:
52 return False
53
54 if key_size not in _warned_rc4_key_sizes:
55 _warned_rc4_key_sizes.add(key_size)
56 logger_warning(
57 (
58 "cryptography does not support %(key_size)d-bit RC4 keys; "
59 "falling back to the pure-Python RC4 implementation."
60 ),
61 source=__name__,
62 key_size=key_size,
63 )
64 return True
65
66
67class CryptRC4(CryptBase):
68 # Assume OpenSSL provides RC4; flipped to False the first time it rejects
69 # the cipher (e.g. legacy provider disabled), so the failing attempt is
70 # paid once.
71 _is_rc4_supported = True
72
73 def __init__(self, key: bytes) -> None:
74 self._key = key
75 self._fallback = None
76 if CryptRC4._is_rc4_supported and not _needs_rc4_key_length_fallback(key):
77 self.cipher = Cipher(ARC4(key), mode=None)
78 else:
79 self._fallback = self._pure_python_rc4(key)
80
81 @staticmethod
82 def _pure_python_rc4(key: bytes) -> CryptBase:
83 from pypdf._crypt_providers import _fallback # noqa: PLC0415
84
85 return _fallback.CryptRC4(key)
86
87 @classmethod
88 def _disable_rc4(cls, key: bytes) -> CryptBase:
89 if cls._is_rc4_supported:
90 logger_warning(
91 (
92 "RC4 is not supported by the current OpenSSL build; "
93 "falling back to the pure-Python RC4 implementation."
94 ),
95 source=__name__,
96 )
97 cls._is_rc4_supported = False
98 return cls._pure_python_rc4(key)
99
100 def encrypt(self, data: bytes) -> bytes:
101 if self._fallback is not None:
102 return self._fallback.encrypt(data)
103 try:
104 encryptor = self.cipher.encryptor()
105 return encryptor.update(data) + encryptor.finalize()
106 except UnsupportedAlgorithm:
107 self._fallback = self._disable_rc4(self._key)
108 return self._fallback.encrypt(data)
109
110 def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
111 if self._fallback is not None:
112 return self._fallback.decrypt(data, strict=strict)
113 try:
114 decryptor = self.cipher.decryptor()
115 return decryptor.update(data) + decryptor.finalize()
116 except UnsupportedAlgorithm:
117 self._fallback = self._disable_rc4(self._key)
118 return self._fallback.decrypt(data, strict=strict)
119
120
121class CryptAES(CryptBase):
122 def __init__(self, key: bytes) -> None:
123 self.alg = AES(key)
124
125 def encrypt(self, data: bytes) -> bytes:
126 iv = secrets.token_bytes(16)
127 padder = PKCS7(128).padder()
128 padded_data = padder.update(data) + padder.finalize()
129
130 cipher = Cipher(self.alg, CBC(iv))
131 encryptor = cipher.encryptor()
132 return iv + encryptor.update(padded_data) + encryptor.finalize()
133
134 def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
135 iv = data[:16]
136 data = data[16:]
137 # for empty encrypted data
138 if not data:
139 return data
140
141 if not strict and len(data) % 16 != 0:
142 logger_warning("Adding missing padding.", source=__name__)
143 padder = PKCS7(128).padder()
144 data = padder.update(data) + padder.finalize()
145
146 cipher = Cipher(self.alg, CBC(iv))
147 decryptor = cipher.decryptor()
148 try:
149 padded_data = decryptor.update(data) + decryptor.finalize()
150 except ValueError as exception:
151 # Only raised in strict mode. Non-strict mode fixes padding.
152 raise PdfStreamError(exception) from exception
153
154 unpadder = PKCS7(128).unpadder()
155 try:
156 return unpadder.update(padded_data) + unpadder.finalize()
157 except ValueError as exception:
158 if strict:
159 raise PdfStreamError(exception) from exception
160 logger_warning("Ignoring padding error: %(exception)s", source=__name__, exception=exception)
161 return padded_data[: -padded_data[-1]]
162
163
164def rc4_encrypt(key: bytes, data: bytes) -> bytes:
165 if CryptRC4._is_rc4_supported and not _needs_rc4_key_length_fallback(key):
166 try:
167 encryptor = Cipher(ARC4(key), mode=None).encryptor()
168 return encryptor.update(data) + encryptor.finalize()
169 except UnsupportedAlgorithm:
170 return CryptRC4._disable_rc4(key).encrypt(data)
171 return CryptRC4._pure_python_rc4(key).encrypt(data)
172
173
174def rc4_decrypt(key: bytes, data: bytes) -> bytes:
175 if CryptRC4._is_rc4_supported and not _needs_rc4_key_length_fallback(key):
176 try:
177 decryptor = Cipher(ARC4(key), mode=None).decryptor()
178 return decryptor.update(data) + decryptor.finalize()
179 except UnsupportedAlgorithm:
180 return CryptRC4._disable_rc4(key).decrypt(data)
181 return CryptRC4._pure_python_rc4(key).decrypt(data)
182
183
184def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
185 encryptor = Cipher(AES(key), mode=ECB()).encryptor()
186 return encryptor.update(data) + encryptor.finalize()
187
188
189def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
190 decryptor = Cipher(AES(key), mode=ECB()).decryptor()
191 return decryptor.update(data) + decryptor.finalize()
192
193
194def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
195 encryptor = Cipher(AES(key), mode=CBC(iv)).encryptor()
196 return encryptor.update(data) + encryptor.finalize()
197
198
199def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
200 decryptor = Cipher(AES(key), mode=CBC(iv)).decryptor()
201 return decryptor.update(data) + decryptor.finalize()