summaryrefslogtreecommitdiff
path: root/test/unit/common/middleware/test_encrypter_decrypter.py
blob: 701c995b3f9f0bf29ed43702b8d01c38b0c6644d (plain)
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
# Copyright (c) 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import json
import unittest
import uuid

from swift.common import storage_policy
from swift.common.middleware import encrypter, decrypter, keymaster
from swift.common.middleware.crypto_utils import load_crypto_meta, Crypto
from swift.common.ring import Ring
from swift.common.swob import Request
from swift.obj import diskfile

from test.unit import FakeLogger
from test.unit.common.middleware.crypto_helpers import (
    md5hex, encrypt, TEST_KEYMASTER_CONF)
from test.unit.helpers import setup_servers, teardown_servers


class TestCryptoPipelineChanges(unittest.TestCase):
    # Tests the consequences of crypto middleware being in/out of the pipeline
    # for PUT/GET requests on same object. Uses real backend servers so that
    # the handling of headers and sysmeta is verified to diskfile and back.
    _test_context = None

    @classmethod
    def setUpClass(cls):
        cls._test_context = setup_servers()
        cls.proxy_app = cls._test_context["test_servers"][0]

    @classmethod
    def tearDownClass(cls):
        if cls._test_context is not None:
            teardown_servers(cls._test_context)
            cls._test_context = None

    def setUp(self):
        self.container_name = uuid.uuid4().hex
        self.container_path = 'http://localhost:8080/v1/a/' + \
                              self.container_name
        self.object_path = self.container_path + '/o'
        self.plaintext = 'unencrypted body content'
        self.plaintext_etag = md5hex(self.plaintext)

        # Set up a pipeline of crypto middleware ending in the proxy app so
        # that tests can make requests to either the proxy server directly or
        # via the crypto middleware. Make a fresh instance for each test to
        # avoid any state coupling.
        enc = encrypter.Encrypter(self.proxy_app, {})
        self.km = keymaster.KeyMaster(enc, TEST_KEYMASTER_CONF)
        self.crypto_app = decrypter.Decrypter(self.km, {})

    def _create_container(self, app, policy_name='one'):
        req = Request.blank(
            self.container_path, method='PUT',
            headers={'X-Storage-Policy': policy_name})
        resp = req.get_response(app)
        self.assertEqual('201 Created', resp.status)
        # sanity check
        req = Request.blank(
            self.container_path, method='HEAD',
            headers={'X-Storage-Policy': policy_name})
        resp = req.get_response(app)
        self.assertEqual(policy_name, resp.headers['X-Storage-Policy'])

    def _put_object(self, app, body):
        req = Request.blank(self.object_path, method='PUT', body=body,
                            headers={'Content-Type': 'application/test'})
        resp = req.get_response(app)
        self.assertEqual('201 Created', resp.status)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        return resp

    def _post_object(self, app):
        req = Request.blank(self.object_path, method='POST',
                            headers={'Content-Type': 'application/test',
                                     'X-Object-Meta-Fruit': 'Kiwi'})
        resp = req.get_response(app)
        self.assertEqual('202 Accepted', resp.status)
        return resp

    def _check_GET_and_HEAD(self, app):
        req = Request.blank(self.object_path, method='GET')
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual(self.plaintext, resp.body)
        self.assertEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

        req = Request.blank(self.object_path, method='HEAD')
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual('', resp.body)
        self.assertEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

    def _check_match_requests(self, method, app):
        # verify conditional match requests
        expected_body = self.plaintext if method == 'GET' else ''

        # If-Match matches
        req = Request.blank(self.object_path, method=method,
                            headers={'If-Match': '"%s"' % self.plaintext_etag})
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual(expected_body, resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        self.assertEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

        # If-Match wildcard
        req = Request.blank(self.object_path, method=method,
                            headers={'If-Match': '*'})
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual(expected_body, resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        self.assertEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

        # If-Match does not match
        req = Request.blank(self.object_path, method=method,
                            headers={'If-Match': '"not the etag"'})
        resp = req.get_response(app)
        self.assertEqual('412 Precondition Failed', resp.status)
        self.assertEqual('', resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])

        # If-None-Match matches
        req = Request.blank(
            self.object_path, method=method,
            headers={'If-None-Match': '"%s"' % self.plaintext_etag})
        resp = req.get_response(app)
        self.assertEqual('304 Not Modified', resp.status)
        self.assertEqual('', resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])

        # If-None-Match wildcard
        req = Request.blank(self.object_path, method=method,
                            headers={'If-None-Match': '*'})
        resp = req.get_response(app)
        self.assertEqual('304 Not Modified', resp.status)
        self.assertEqual('', resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])

        # If-None-Match does not match
        req = Request.blank(self.object_path, method=method,
                            headers={'If-None-Match': '"not the etag"'})
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual(expected_body, resp.body)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        self.assertEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

    def _check_listing(self, app, expect_mismatch=False):
        req = Request.blank(
            self.container_path, method='GET', query_string='format=json')
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        listing = json.loads(resp.body)
        self.assertEqual(1, len(listing))
        self.assertEqual('o', listing[0]['name'])
        self.assertEqual(len(self.plaintext), listing[0]['bytes'])
        if expect_mismatch:
            self.assertNotEqual(self.plaintext_etag, listing[0]['hash'])
        else:
            self.assertEqual(self.plaintext_etag, listing[0]['hash'])

    def test_write_with_crypto_and_override_headers(self):
        self._create_container(self.proxy_app, policy_name='one')

        def verify_overrides():
            # verify object sysmeta
            req = Request.blank(
                self.object_path, method='GET')
            resp = req.get_response(self.crypto_app)
            for k, v in overrides.items():
                self.assertIn(k, resp.headers)
                self.assertEqual(overrides[k], resp.headers[k])

            # check container listing
            req = Request.blank(
                self.container_path, method='GET', query_string='format=json')
            resp = req.get_response(self.crypto_app)
            self.assertEqual('200 OK', resp.status)
            listing = json.loads(resp.body)
            self.assertEqual(1, len(listing))
            self.assertEqual('o', listing[0]['name'])
            self.assertEqual(
                overrides['x-object-sysmeta-container-update-override-size'],
                str(listing[0]['bytes']))
            self.assertEqual(
                overrides['x-object-sysmeta-container-update-override-etag'],
                listing[0]['hash'])

        # include overrides in headers
        overrides = {'x-object-sysmeta-container-update-override-etag': 'foo',
                     'x-object-sysmeta-container-update-override-size':
                         str(len(self.plaintext) + 1)}
        req = Request.blank(self.object_path, method='PUT',
                            body=self.plaintext, headers=overrides.copy())
        resp = req.get_response(self.crypto_app)
        self.assertEqual('201 Created', resp.status)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        verify_overrides()

        # include overrides in footers
        overrides = {'x-object-sysmeta-container-update-override-etag': 'bar',
                     'x-object-sysmeta-container-update-override-size':
                         str(len(self.plaintext) + 2)}

        def callback(footers):
            footers.update(overrides)

        req = Request.blank(
            self.object_path, method='PUT', body=self.plaintext)
        req.environ['swift.callback.update_footers'] = callback
        resp = req.get_response(self.crypto_app)
        self.assertEqual('201 Created', resp.status)
        self.assertEqual(self.plaintext_etag, resp.headers['Etag'])
        verify_overrides()

    def test_write_with_crypto_read_with_crypto(self):
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)
        self._check_match_requests('GET', self.crypto_app)
        self._check_match_requests('HEAD', self.crypto_app)
        self._check_listing(self.crypto_app)

    def test_write_with_crypto_read_with_crypto_ec(self):
        self._create_container(self.proxy_app, policy_name='ec')
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)
        self._check_match_requests('GET', self.crypto_app)
        self._check_match_requests('HEAD', self.crypto_app)
        self._check_listing(self.crypto_app)

    def test_put_without_crypto_post_with_crypto_read_with_crypto(self):
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(self.proxy_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)
        self._check_match_requests('GET', self.crypto_app)
        self._check_match_requests('HEAD', self.crypto_app)
        self._check_listing(self.crypto_app)

    def test_write_without_crypto_read_with_crypto(self):
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(self.proxy_app, self.plaintext)
        self._post_object(self.proxy_app)
        self._check_GET_and_HEAD(self.proxy_app)  # sanity check
        self._check_GET_and_HEAD(self.crypto_app)
        self._check_match_requests('GET', self.proxy_app)  # sanity check
        self._check_match_requests('GET', self.crypto_app)
        self._check_match_requests('HEAD', self.proxy_app)  # sanity check
        self._check_match_requests('HEAD', self.crypto_app)
        self._check_listing(self.crypto_app)

    def test_write_without_crypto_read_with_crypto_ec(self):
        self._create_container(self.proxy_app, policy_name='ec')
        self._put_object(self.proxy_app, self.plaintext)
        self._post_object(self.proxy_app)
        self._check_GET_and_HEAD(self.proxy_app)  # sanity check
        self._check_GET_and_HEAD(self.crypto_app)
        self._check_match_requests('GET', self.proxy_app)  # sanity check
        self._check_match_requests('GET', self.crypto_app)
        self._check_match_requests('HEAD', self.proxy_app)  # sanity check
        self._check_match_requests('HEAD', self.crypto_app)
        self._check_listing(self.crypto_app)

    def _check_GET_and_HEAD_not_decrypted(self, app):
        req = Request.blank(self.object_path, method='GET')
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertNotEqual(self.plaintext, resp.body)
        self.assertEqual('%s' % len(self.plaintext),
                         resp.headers['Content-Length'])
        self.assertNotEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

        req = Request.blank(self.object_path, method='HEAD')
        resp = req.get_response(app)
        self.assertEqual('200 OK', resp.status)
        self.assertEqual('', resp.body)
        self.assertNotEqual('Kiwi', resp.headers['X-Object-Meta-Fruit'])

    def test_write_with_crypto_read_without_crypto(self):
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)  # sanity check
        # without crypto middleware, GET and HEAD returns ciphertext
        self._check_GET_and_HEAD_not_decrypted(self.proxy_app)
        self._check_listing(self.proxy_app, expect_mismatch=True)

    def test_write_with_crypto_read_without_crypto_ec(self):
        self._create_container(self.proxy_app, policy_name='ec')
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)  # sanity check
        # without crypto middleware, GET and HEAD returns ciphertext
        self._check_GET_and_HEAD_not_decrypted(self.proxy_app)
        self._check_listing(self.proxy_app, expect_mismatch=True)

    def test_disable_encryption_config_option(self):
        # check that on disable_encryption = true, object is not encrypted
        enc = encrypter.Encrypter(
            self.proxy_app, {'disable_encryption': 'true'})
        km = keymaster.KeyMaster(enc, TEST_KEYMASTER_CONF)
        crypto_app = decrypter.Decrypter(km, {})
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(crypto_app, self.plaintext)
        self._post_object(crypto_app)
        self._check_GET_and_HEAD(crypto_app)
        # check as if no crypto middleware exists
        self._check_GET_and_HEAD(self.proxy_app)
        self._check_match_requests('GET', crypto_app)
        self._check_match_requests('HEAD', crypto_app)
        self._check_match_requests('GET', self.proxy_app)
        self._check_match_requests('HEAD', self.proxy_app)

    def test_write_with_crypto_read_with_disable_encryption_conf(self):
        self._create_container(self.proxy_app, policy_name='one')
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)
        self._check_GET_and_HEAD(self.crypto_app)  # sanity check
        # turn on disable_encryption config option
        enc = encrypter.Encrypter(
            self.proxy_app, {'disable_encryption': 'true'})
        km = keymaster.KeyMaster(enc, TEST_KEYMASTER_CONF)
        crypto_app = decrypter.Decrypter(km, {})
        # GET and HEAD of encrypted objects should still work
        self._check_GET_and_HEAD(crypto_app)
        self._check_listing(crypto_app, expect_mismatch=False)
        self._check_match_requests('GET', crypto_app)
        self._check_match_requests('HEAD', crypto_app)

    def _test_ondisk_data_after_write_with_crypto(self, policy_name):
        policy = storage_policy.POLICIES.get_by_name(policy_name)
        self._create_container(self.proxy_app, policy_name=policy_name)
        self._put_object(self.crypto_app, self.plaintext)
        self._post_object(self.crypto_app)

        # Verify container listing etag is encrypted by direct GET to container
        # server. We can use any server for all nodes since they all share same
        # devices dir.
        cont_server = self._test_context['test_servers'][3]
        cont_ring = Ring(self._test_context['testdir'], ring_name='container')
        part, nodes = cont_ring.get_nodes('a', self.container_name)
        for node in nodes:
            req = Request.blank('/%s/%s/a/%s'
                                % (node['device'], part, self.container_name),
                                method='GET', query_string='format=json')
            resp = req.get_response(cont_server)
            listing = json.loads(resp.body)
            # sanity checks...
            self.assertEqual(1, len(listing))
            self.assertEqual('o', listing[0]['name'])
            self.assertEqual('application/test', listing[0]['content_type'])
            # verify encrypted etag value
            parts = listing[0]['hash'].rsplit(';', 1)
            crypto_meta_param = parts[1].strip()
            crypto_meta = crypto_meta_param[len('swift_meta='):]
            listing_etag_iv = load_crypto_meta(crypto_meta)['iv']
            exp_enc_listing_etag = base64.b64encode(
                encrypt(self.plaintext_etag,
                        self.km.create_key('/a/%s' % self.container_name),
                        listing_etag_iv))
            self.assertEqual(exp_enc_listing_etag, parts[0])

        # Verify diskfile data and metadata is encrypted
        ring_object = self.proxy_app.get_object_ring(int(policy))
        partition, nodes = ring_object.get_nodes('a', self.container_name, 'o')
        conf = {'devices': self._test_context["testdir"],
                'mount_check': 'false'}
        df_mgr = diskfile.DiskFileRouter(conf, FakeLogger())[policy]
        ondisk_data = []
        exp_enc_body = None
        for node_index, node in enumerate(nodes):
            df = df_mgr.get_diskfile(node['device'], partition,
                                     'a', self.container_name, 'o',
                                     policy=policy)
            with df.open():
                meta = df.get_metadata()
                contents = ''.join(df.reader())
                metadata = dict((k.lower(), v) for k, v in meta.items())
                # verify on disk data - body
                body_iv = load_crypto_meta(
                    metadata['x-object-sysmeta-crypto-meta'])['iv']
                body_key_meta = load_crypto_meta(
                    metadata['x-object-sysmeta-crypto-meta'])['body_key']
                obj_key = self.km.create_key('/a/%s/o' % self.container_name)
                body_key = Crypto().unwrap_key(obj_key, body_key_meta)
                exp_enc_body = encrypt(self.plaintext, body_key, body_iv)
                ondisk_data.append((node, contents))
                # verify on disk user metadata
                metadata_iv = load_crypto_meta(
                    metadata['x-object-transient-sysmeta-crypto-meta-fruit']
                )['iv']
                exp_enc_meta = base64.b64encode(encrypt('Kiwi', obj_key,
                                                        metadata_iv))
                self.assertEqual(exp_enc_meta, metadata['x-object-meta-fruit'])
                # verify etag
                etag_iv = load_crypto_meta(
                    metadata['x-object-sysmeta-crypto-meta-etag'])['iv']
                etag_key = self.km.create_key('/a/%s' % self.container_name)
                exp_enc_etag = base64.b64encode(encrypt(self.plaintext_etag,
                                                        etag_key, etag_iv))
                self.assertEqual(exp_enc_etag,
                                 metadata['x-object-sysmeta-crypto-etag'])
                # verify etag override for container updates
                override = 'x-object-sysmeta-container-update-override-etag'
                parts = metadata[override].rsplit(';', 1)
                crypto_meta_param = parts[1].strip()
                crypto_meta = crypto_meta_param[len('swift_meta='):]
                listing_etag_iv = load_crypto_meta(crypto_meta)['iv']
                exp_enc_listing_etag = base64.b64encode(
                    encrypt(self.plaintext_etag, etag_key,
                            listing_etag_iv))
                self.assertEqual(exp_enc_listing_etag, parts[0])

        self._check_GET_and_HEAD(self.crypto_app)
        return exp_enc_body, ondisk_data

    def test_ondisk_data_after_write_with_crypto(self):
        exp_body, ondisk_data = self._test_ondisk_data_after_write_with_crypto(
            policy_name='one')
        for node, body in ondisk_data:
            self.assertEqual(exp_body, body)

    def test_ondisk_data_after_write_with_crypto_ec(self):
        exp_body, ondisk_data = self._test_ondisk_data_after_write_with_crypto(
            policy_name='ec')
        policy = storage_policy.POLICIES.get_by_name('ec')
        for frag_selection in (ondisk_data[:2], ondisk_data[1:]):
            frags = [frag for node, frag in frag_selection]
            self.assertEqual(exp_body, policy.pyeclib_driver.decode(frags))


class TestCryptoPipelineChangesFastPost(TestCryptoPipelineChanges):
    @classmethod
    def setUpClass(cls):
        # set proxy config to use fast post
        extra_conf = {'object_post_as_copy': 'False'}
        cls._test_context = setup_servers(extra_conf=extra_conf)
        cls.proxy_app = cls._test_context["test_servers"][0]


if __name__ == '__main__':
    unittest.main()