blob: 75ecc356a9138440fadd1984c43029c4195b187a [file] [log] [blame]
Alex Gaynor5951f462014-11-16 09:08:42 -08001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
Alex Gaynor8912d3a2013-11-02 14:04:19 -07004
Alex Gaynorc37feed2014-03-08 08:32:56 -08005from __future__ import absolute_import, division, print_function
6
Alex Gaynor2b21b122013-10-31 09:39:25 -07007import base64
Alex Gaynorfb8adfc2013-10-31 14:16:24 -07008import calendar
Chris Wolfeaf6f9902017-10-18 14:23:53 -05009import datetime
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070010import json
Paul Kehrerfdae0702014-11-27 07:50:46 -100011import os
Alex Gaynor1d2901c2013-11-22 10:12:05 -080012import time
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070013
14import iso8601
15
16import pytest
Alex Gaynor2b21b122013-10-31 09:39:25 -070017
Alex Gaynorde36e902013-10-31 10:10:44 -070018import six
19
Alex Gaynor7b593e12014-10-19 19:09:44 -070020from cryptography.fernet import Fernet, InvalidToken, MultiFernet
Alex Gaynorfae20712013-12-16 15:29:30 -080021from cryptography.hazmat.backends import default_backend
Alex Gaynore6ac6022014-10-24 07:50:30 -070022from cryptography.hazmat.backends.interfaces import CipherBackend, HMACBackend
Paul Kehrer0abdf872014-01-09 22:21:14 -060023from cryptography.hazmat.primitives.ciphers import algorithms, modes
Alex Gaynor2b21b122013-10-31 09:39:25 -070024
Alex Stapletona39a3192014-03-14 20:03:12 +000025import cryptography_vectors
26
Alex Gaynor2b21b122013-10-31 09:39:25 -070027
Matthew Iversen68e77c72014-03-13 08:54:43 +110028def json_parametrize(keys, filename):
Paul Kehrerfdae0702014-11-27 07:50:46 -100029 vector_file = cryptography_vectors.open_vector_file(
30 os.path.join('fernet', filename), "r"
31 )
Alex Stapletona39a3192014-03-14 20:03:12 +000032 with vector_file:
33 data = json.load(vector_file)
34 return pytest.mark.parametrize(keys, [
35 tuple([entry[k] for k in keys])
36 for entry in data
37 ])
Alex Gaynor2b21b122013-10-31 09:39:25 -070038
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070039
Alex Gaynor732fbec2014-10-19 18:46:55 -070040def test_default_backend():
41 f = Fernet(Fernet.generate_key())
42 assert f._backend is default_backend()
43
44
Alex Gaynor7aab8b42014-10-23 11:01:25 -070045@pytest.mark.requires_backend_interface(interface=CipherBackend)
Alex Gaynore6ac6022014-10-24 07:50:30 -070046@pytest.mark.requires_backend_interface(interface=HMACBackend)
Alex Gaynor732fbec2014-10-19 18:46:55 -070047@pytest.mark.supported(
48 only_if=lambda backend: backend.cipher_supported(
Paul Kehrer4fc597d2016-03-07 08:41:51 -043049 algorithms.AES(b"\x00" * 32), modes.CBC(b"\x00" * 16)
Alex Gaynor732fbec2014-10-19 18:46:55 -070050 ),
51 skip_message="Does not support AES CBC",
52)
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070053class TestFernet(object):
54 @json_parametrize(
Alex Gaynor38f34552013-10-31 14:50:00 -070055 ("secret", "now", "iv", "src", "token"), "generate.json",
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070056 )
Alex Gaynorfae20712013-12-16 15:29:30 -080057 def test_generate(self, secret, now, iv, src, token, backend):
58 f = Fernet(secret.encode("ascii"), backend=backend)
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070059 actual_token = f._encrypt_from_parts(
60 src.encode("ascii"),
61 calendar.timegm(iso8601.parse_date(now).utctimetuple()),
62 b"".join(map(six.int2byte, iv))
Alex Gaynor5e87dfd2013-10-31 09:46:03 -070063 )
Alex Gaynor7ecd3142013-10-31 16:29:18 -070064 assert actual_token == token.encode("ascii")
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070065
66 @json_parametrize(
Alex Gaynor38f34552013-10-31 14:50:00 -070067 ("secret", "now", "src", "ttl_sec", "token"), "verify.json",
Alex Gaynorfb8adfc2013-10-31 14:16:24 -070068 )
Alex Gaynorfae20712013-12-16 15:29:30 -080069 def test_verify(self, secret, now, src, ttl_sec, token, backend,
70 monkeypatch):
71 f = Fernet(secret.encode("ascii"), backend=backend)
Alex Gaynorc1ea0a02013-10-31 15:03:53 -070072 current_time = calendar.timegm(iso8601.parse_date(now).utctimetuple())
Alex Gaynor1d2901c2013-11-22 10:12:05 -080073 monkeypatch.setattr(time, "time", lambda: current_time)
74 payload = f.decrypt(token.encode("ascii"), ttl=ttl_sec)
Alex Gaynor7ecd3142013-10-31 16:29:18 -070075 assert payload == src.encode("ascii")
Alex Gaynor38f34552013-10-31 14:50:00 -070076
77 @json_parametrize(("secret", "token", "now", "ttl_sec"), "invalid.json")
Alex Gaynorfae20712013-12-16 15:29:30 -080078 def test_invalid(self, secret, token, now, ttl_sec, backend, monkeypatch):
79 f = Fernet(secret.encode("ascii"), backend=backend)
Alex Gaynorc1ea0a02013-10-31 15:03:53 -070080 current_time = calendar.timegm(iso8601.parse_date(now).utctimetuple())
Alex Gaynor1d2901c2013-11-22 10:12:05 -080081 monkeypatch.setattr(time, "time", lambda: current_time)
Alex Gaynor38f34552013-10-31 14:50:00 -070082 with pytest.raises(InvalidToken):
Alex Gaynor1d2901c2013-11-22 10:12:05 -080083 f.decrypt(token.encode("ascii"), ttl=ttl_sec)
Alex Gaynor38f34552013-10-31 14:50:00 -070084
Alex Gaynora8f0b632013-12-16 15:44:06 -080085 def test_invalid_start_byte(self, backend):
Alex Gaynora1a21f42014-10-19 19:11:30 -070086 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
Alex Gaynora8f0b632013-12-16 15:44:06 -080087 with pytest.raises(InvalidToken):
88 f.decrypt(base64.urlsafe_b64encode(b"\x81"))
89
Alex Gaynore78960f2013-12-20 11:02:33 -080090 def test_timestamp_too_short(self, backend):
Alex Gaynora1a21f42014-10-19 19:11:30 -070091 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
Alex Gaynore78960f2013-12-20 11:02:33 -080092 with pytest.raises(InvalidToken):
93 f.decrypt(base64.urlsafe_b64encode(b"\x80abc"))
94
Alex Gaynora1a21f42014-10-19 19:11:30 -070095 def test_non_base64_token(self, backend):
96 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
97 with pytest.raises(InvalidToken):
98 f.decrypt(b"\x00")
99
Alex Gaynorfae20712013-12-16 15:29:30 -0800100 def test_unicode(self, backend):
101 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
Alex Gaynor38f34552013-10-31 14:50:00 -0700102 with pytest.raises(TypeError):
Eeshan Gargf1234152015-04-29 18:41:00 +0530103 f.encrypt(u"")
Alex Gaynor38f34552013-10-31 14:50:00 -0700104 with pytest.raises(TypeError):
Eeshan Gargf1234152015-04-29 18:41:00 +0530105 f.decrypt(u"")
Alex Gaynorce8f9a42013-10-31 15:23:15 -0700106
Paul Kehrera418e962016-01-21 08:54:59 -0600107 def test_timestamp_ignored_no_ttl(self, monkeypatch, backend):
108 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
109 pt = b"encrypt me"
110 token = f.encrypt(pt)
111 ts = "1985-10-26T01:20:01-07:00"
112 current_time = calendar.timegm(iso8601.parse_date(ts).utctimetuple())
113 monkeypatch.setattr(time, "time", lambda: current_time)
114 assert f.decrypt(token, ttl=None) == pt
115
Alex Gaynorce8f9a42013-10-31 15:23:15 -0700116 @pytest.mark.parametrize("message", [b"", b"Abc!", b"\x00\xFF\x00\x80"])
Alex Gaynorfae20712013-12-16 15:29:30 -0800117 def test_roundtrips(self, message, backend):
118 f = Fernet(Fernet.generate_key(), backend=backend)
Alex Gaynor6b9770b2013-10-31 16:07:35 -0700119 assert f.decrypt(f.encrypt(message)) == message
Alex Gaynorfae20712013-12-16 15:29:30 -0800120
Alex Gaynora8f0b632013-12-16 15:44:06 -0800121 def test_bad_key(self, backend):
122 with pytest.raises(ValueError):
123 Fernet(base64.urlsafe_b64encode(b"abc"), backend=backend)
Alex Gaynor7b593e12014-10-19 19:09:44 -0700124
Paul Kehrer36ad98f2018-05-12 11:57:32 -0400125 def test_extract_timestamp(self, monkeypatch, backend):
126 f = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
127 current_time = 1526138327
128 monkeypatch.setattr(time, "time", lambda: current_time)
129 token = f.encrypt(b'encrypt me')
130 assert f.extract_timestamp(token) == current_time
131 with pytest.raises(InvalidToken):
132 f.extract_timestamp(b"nonsensetoken")
133
Alex Gaynor7b593e12014-10-19 19:09:44 -0700134
Alex Gaynore6ac6022014-10-24 07:50:30 -0700135@pytest.mark.requires_backend_interface(interface=CipherBackend)
136@pytest.mark.requires_backend_interface(interface=HMACBackend)
Alex Gaynor7b593e12014-10-19 19:09:44 -0700137@pytest.mark.supported(
138 only_if=lambda backend: backend.cipher_supported(
Paul Kehrer4fc597d2016-03-07 08:41:51 -0430139 algorithms.AES(b"\x00" * 32), modes.CBC(b"\x00" * 16)
Alex Gaynor7b593e12014-10-19 19:09:44 -0700140 ),
141 skip_message="Does not support AES CBC",
142)
143class TestMultiFernet(object):
144 def test_encrypt(self, backend):
Alex Gaynor41b33b72014-10-20 14:34:35 -0700145 f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
146 f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
147 f = MultiFernet([f1, f2])
148
149 assert f1.decrypt(f.encrypt(b"abc")) == b"abc"
Alex Gaynor7b593e12014-10-19 19:09:44 -0700150
151 def test_decrypt(self, backend):
152 f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
Alex Gaynor41b33b72014-10-20 14:34:35 -0700153 f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
Alex Gaynor7b593e12014-10-19 19:09:44 -0700154 f = MultiFernet([f1, f2])
155
156 assert f.decrypt(f1.encrypt(b"abc")) == b"abc"
157 assert f.decrypt(f2.encrypt(b"abc")) == b"abc"
158
159 with pytest.raises(InvalidToken):
160 f.decrypt(b"\x00" * 16)
161
162 def test_no_fernets(self, backend):
163 with pytest.raises(ValueError):
164 MultiFernet([])
Alex Gaynor4f286ce2014-10-20 11:30:57 -0700165
166 def test_non_iterable_argument(self, backend):
167 with pytest.raises(TypeError):
168 MultiFernet(None)
Chris Wolfeaf6f9902017-10-18 14:23:53 -0500169
170 def test_rotate(self, backend):
171 f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
172 f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
173
174 mf1 = MultiFernet([f1])
175 mf2 = MultiFernet([f2, f1])
176
177 plaintext = b"abc"
178 mf1_ciphertext = mf1.encrypt(plaintext)
179
180 assert mf2.decrypt(mf1_ciphertext) == plaintext
181
182 rotated = mf2.rotate(mf1_ciphertext)
183
184 assert rotated != mf1_ciphertext
185 assert mf2.decrypt(rotated) == plaintext
186
187 with pytest.raises(InvalidToken):
188 mf1.decrypt(rotated)
189
190 def test_rotate_preserves_timestamp(self, backend, monkeypatch):
191 f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
192 f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
193
194 mf1 = MultiFernet([f1])
195 mf2 = MultiFernet([f2, f1])
196
197 plaintext = b"abc"
198 mf1_ciphertext = mf1.encrypt(plaintext)
199
200 later = datetime.datetime.now() + datetime.timedelta(minutes=5)
201 later_time = time.mktime(later.timetuple())
202 monkeypatch.setattr(time, "time", lambda: later_time)
203
204 original_time, _ = Fernet._get_unverified_token_data(mf1_ciphertext)
205 rotated_time, _ = Fernet._get_unverified_token_data(
206 mf2.rotate(mf1_ciphertext)
207 )
208
209 assert later_time != rotated_time
210 assert original_time == rotated_time
211
212 def test_rotate_decrypt_no_shared_keys(self, backend):
213 f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
214 f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)
215
216 mf1 = MultiFernet([f1])
217 mf2 = MultiFernet([f2])
218
219 with pytest.raises(InvalidToken):
220 mf2.rotate(mf1.encrypt(b"abc"))