1 // vim: ts=8 sw=2 smarttab
3 * Ceph - scalable distributed file system
5 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
7 * This is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License version 2.1, as published by the Free Software
10 * Foundation. See file COPYING.
17 # include <cryptopp/modes.h>
18 # include <cryptopp/aes.h>
19 # include <cryptopp/filters.h>
20 #elif defined(USE_NSS)
26 #include "include/assert.h"
27 #include "common/Clock.h"
28 #include "common/armor.h"
29 #include "common/ceph_crypto.h"
30 #include "common/hex.h"
31 #include "common/safe_io.h"
32 #include "include/ceph_fs.h"
33 #include "include/compat.h"
34 #include "common/Formatter.h"
35 #include "common/debug.h"
38 int get_random_bytes(char *buf
, int len
)
40 int fd
= TEMP_FAILURE_RETRY(::open("/dev/urandom", O_RDONLY
));
43 int ret
= safe_read_exact(fd
, buf
, len
);
44 VOID_TEMP_FAILURE_RETRY(::close(fd
));
48 static int get_random_bytes(int len
, bufferlist
& bl
)
51 get_random_bytes(buf
, len
);
56 uint64_t get_random(uint64_t min_val
, uint64_t max_val
)
59 get_random_bytes((char *)&r
, sizeof(r
));
60 r
= min_val
+ r
% (max_val
- min_val
+ 1);
65 // ---------------------------------------------------
67 class CryptoNoneKeyHandler
: public CryptoKeyHandler
{
69 int encrypt(const bufferlist
& in
,
70 bufferlist
& out
, std::string
*error
) const override
{
74 int decrypt(const bufferlist
& in
,
75 bufferlist
& out
, std::string
*error
) const override
{
81 class CryptoNone
: public CryptoHandler
{
84 ~CryptoNone() override
{}
85 int get_type() const override
{
86 return CEPH_CRYPTO_NONE
;
88 int create(bufferptr
& secret
) override
{
91 int validate_secret(const bufferptr
& secret
) override
{
94 CryptoKeyHandler
*get_key_handler(const bufferptr
& secret
, string
& error
) override
{
95 return new CryptoNoneKeyHandler
;
100 // ---------------------------------------------------
103 class CryptoAES
: public CryptoHandler
{
106 ~CryptoAES() override
{}
107 int get_type() const override
{
108 return CEPH_CRYPTO_AES
;
110 int create(bufferptr
& secret
) override
;
111 int validate_secret(const bufferptr
& secret
) override
;
112 CryptoKeyHandler
*get_key_handler(const bufferptr
& secret
, string
& error
) override
;
116 # define AES_KEY_LEN ((size_t)CryptoPP::AES::DEFAULT_KEYLENGTH)
117 # define AES_BLOCK_LEN ((size_t)CryptoPP::AES::BLOCKSIZE)
119 class CryptoAESKeyHandler
: public CryptoKeyHandler
{
121 CryptoPP::AES::Encryption
*enc_key
;
122 CryptoPP::AES::Decryption
*dec_key
;
124 CryptoAESKeyHandler()
127 ~CryptoAESKeyHandler() {
132 int init(const bufferptr
& s
, ostringstream
& err
) {
135 enc_key
= new CryptoPP::AES::Encryption(
136 (byte
*)secret
.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH
);
137 dec_key
= new CryptoPP::AES::Decryption(
138 (byte
*)secret
.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH
);
143 int encrypt(const bufferlist
& in
,
144 bufferlist
& out
, std::string
*error
) const {
146 CryptoPP::StringSink
*sink
= new CryptoPP::StringSink(ciphertext
);
147 CryptoPP::CBC_Mode_ExternalCipher::Encryption
cbc(
148 *enc_key
, (const byte
*)CEPH_AES_IV
);
149 CryptoPP::StreamTransformationFilter
stfEncryptor(cbc
, sink
);
151 for (std::list
<bufferptr
>::const_iterator it
= in
.buffers().begin();
152 it
!= in
.buffers().end(); ++it
) {
153 const unsigned char *in_buf
= (const unsigned char *)it
->c_str();
154 stfEncryptor
.Put(in_buf
, it
->length());
157 stfEncryptor
.MessageEnd();
158 } catch (CryptoPP::Exception
& e
) {
161 oss
<< "encryptor.MessageEnd::Exception: " << e
.GetWhat();
166 out
.append((const char *)ciphertext
.c_str(), ciphertext
.length());
170 int decrypt(const bufferlist
& in
,
171 bufferlist
& out
, std::string
*error
) const {
172 string decryptedtext
;
173 CryptoPP::StringSink
*sink
= new CryptoPP::StringSink(decryptedtext
);
174 CryptoPP::CBC_Mode_ExternalCipher::Decryption
cbc(
175 *dec_key
, (const byte
*)CEPH_AES_IV
);
176 CryptoPP::StreamTransformationFilter
stfDecryptor(cbc
, sink
);
177 for (std::list
<bufferptr
>::const_iterator it
= in
.buffers().begin();
178 it
!= in
.buffers().end(); ++it
) {
179 const unsigned char *in_buf
= (const unsigned char *)it
->c_str();
180 stfDecryptor
.Put(in_buf
, it
->length());
184 stfDecryptor
.MessageEnd();
185 } catch (CryptoPP::Exception
& e
) {
188 oss
<< "decryptor.MessageEnd::Exception: " << e
.GetWhat();
194 out
.append((const char *)decryptedtext
.c_str(), decryptedtext
.length());
199 #elif defined(USE_NSS)
200 // when we say AES, we mean AES-128
201 # define AES_KEY_LEN 16
202 # define AES_BLOCK_LEN 16
204 static int nss_aes_operation(CK_ATTRIBUTE_TYPE op
,
205 CK_MECHANISM_TYPE mechanism
,
208 const bufferlist
& in
, bufferlist
& out
,
211 // sample source said this has to be at least size of input + 8,
212 // but i see 15 still fail with SEC_ERROR_OUTPUT_LEN
213 bufferptr
out_tmp(in
.length()+16);
218 unsigned char *in_buf
;
221 ectx
= PK11_CreateContextBySymKey(mechanism
, op
, key
, param
);
224 incopy
= in
; // it's a shallow copy!
225 in_buf
= (unsigned char*)incopy
.c_str();
226 ret
= PK11_CipherOp(ectx
,
227 (unsigned char*)out_tmp
.c_str(), &written
, out_tmp
.length(),
228 in_buf
, in
.length());
229 if (ret
!= SECSuccess
) {
230 PK11_DestroyContext(ectx
, PR_TRUE
);
233 oss
<< "NSS AES failed: " << PR_GetError();
239 unsigned int written2
;
240 ret
= PK11_DigestFinal(ectx
,
241 (unsigned char*)out_tmp
.c_str()+written
, &written2
,
242 out_tmp
.length()-written
);
243 PK11_DestroyContext(ectx
, PR_TRUE
);
244 if (ret
!= SECSuccess
) {
247 oss
<< "NSS AES final round failed: " << PR_GetError();
253 out_tmp
.set_length(written
+ written2
);
258 class CryptoAESKeyHandler
: public CryptoKeyHandler
{
259 CK_MECHANISM_TYPE mechanism
;
265 CryptoAESKeyHandler()
266 : mechanism(CKM_AES_CBC_PAD
),
270 ~CryptoAESKeyHandler() override
{
271 SECITEM_FreeItem(param
, PR_TRUE
);
273 PK11_FreeSymKey(key
);
278 int init(const bufferptr
& s
, ostringstream
& err
) {
281 slot
= PK11_GetBestSlot(mechanism
, NULL
);
283 err
<< "cannot find NSS slot to use: " << PR_GetError();
288 keyItem
.type
= siBuffer
;
289 keyItem
.data
= (unsigned char*)secret
.c_str();
290 keyItem
.len
= secret
.length();
291 key
= PK11_ImportSymKey(slot
, mechanism
, PK11_OriginUnwrap
, CKA_ENCRYPT
,
294 err
<< "cannot convert AES key for NSS: " << PR_GetError();
299 ivItem
.type
= siBuffer
;
300 // losing constness due to SECItem.data; IV should never be
301 // modified, regardless
302 ivItem
.data
= (unsigned char*)CEPH_AES_IV
;
303 ivItem
.len
= sizeof(CEPH_AES_IV
);
305 param
= PK11_ParamFromIV(mechanism
, &ivItem
);
307 err
<< "cannot set NSS IV param: " << PR_GetError();
314 int encrypt(const bufferlist
& in
,
315 bufferlist
& out
, std::string
*error
) const override
{
316 return nss_aes_operation(CKA_ENCRYPT
, mechanism
, key
, param
, in
, out
, error
);
318 int decrypt(const bufferlist
& in
,
319 bufferlist
& out
, std::string
*error
) const override
{
320 return nss_aes_operation(CKA_DECRYPT
, mechanism
, key
, param
, in
, out
, error
);
325 # error "No supported crypto implementation found."
330 // ------------------------------------------------------------
332 int CryptoAES::create(bufferptr
& secret
)
335 int r
= get_random_bytes(AES_KEY_LEN
, bl
);
338 secret
= buffer::ptr(bl
.c_str(), bl
.length());
342 int CryptoAES::validate_secret(const bufferptr
& secret
)
344 if (secret
.length() < (size_t)AES_KEY_LEN
) {
351 CryptoKeyHandler
*CryptoAES::get_key_handler(const bufferptr
& secret
,
354 CryptoAESKeyHandler
*ckh
= new CryptoAESKeyHandler
;
356 if (ckh
->init(secret
, oss
) < 0) {
370 // ---------------------------------------------------
373 void CryptoKey::encode(bufferlist
& bl
) const
376 ::encode(created
, bl
);
377 __u16 len
= secret
.length();
382 void CryptoKey::decode(bufferlist::iterator
& bl
)
385 ::decode(created
, bl
);
389 bl
.copy_deep(len
, tmp
);
390 if (_set_secret(type
, tmp
) < 0)
391 throw buffer::malformed_input("malformed secret");
394 int CryptoKey::set_secret(int type
, const bufferptr
& s
, utime_t c
)
396 int r
= _set_secret(type
, s
);
403 int CryptoKey::_set_secret(int t
, const bufferptr
& s
)
405 if (s
.length() == 0) {
411 CryptoHandler
*ch
= CryptoHandler::create(t
);
413 int ret
= ch
->validate_secret(s
);
419 ckh
.reset(ch
->get_key_handler(s
, error
));
421 if (error
.length()) {
432 int CryptoKey::create(CephContext
*cct
, int t
)
434 CryptoHandler
*ch
= CryptoHandler::create(t
);
437 lderr(cct
) << "ERROR: cct->get_crypto_handler(type=" << t
<< ") returned NULL" << dendl
;
441 int r
= ch
->create(s
);
446 r
= _set_secret(t
, s
);
449 created
= ceph_clock_now();
453 void CryptoKey::print(std::ostream
&out
) const
455 out
<< encode_base64();
458 void CryptoKey::to_str(std::string
& s
) const
460 int len
= secret
.length() * 4;
462 hex2str(secret
.c_str(), secret
.length(), buf
, len
);
466 void CryptoKey::encode_formatted(string label
, Formatter
*f
, bufferlist
&bl
)
468 f
->open_object_section(label
.c_str());
469 f
->dump_string("key", encode_base64());
474 void CryptoKey::encode_plaintext(bufferlist
&bl
)
476 bl
.append(encode_base64());
480 // ------------------
482 CryptoHandler
*CryptoHandler::create(int type
)
485 case CEPH_CRYPTO_NONE
:
486 return new CryptoNone
;
487 case CEPH_CRYPTO_AES
:
488 return new CryptoAES
;