proxygen
fizz::detail Namespace Reference

Classes

struct  bits24
 
class  OpenSSLECKeyDecoder
 
class  OpenSSLECKeyEncoder
 
class  OpenSSLECKeyExchange
 
struct  Reader
 
struct  Reader< CertificateEntry >
 
struct  Reader< DistinguishedName >
 
struct  Reader< Extension >
 
struct  Reader< KeyShareEntry >
 
struct  Reader< ProtocolName >
 
struct  Reader< PskBinder >
 
struct  Reader< PskIdentity >
 
struct  Reader< Random >
 
struct  Reader< ServerName >
 
struct  ReadVector
 
struct  ReadVector< bits24, T >
 
struct  Sizer
 
struct  Sizer< CertificateEntry >
 
struct  Sizer< DistinguishedName >
 
struct  Sizer< Extension >
 
struct  Sizer< KeyShareEntry >
 
struct  Sizer< ProtocolName >
 
struct  Sizer< PskBinder >
 
struct  Sizer< PskIdentity >
 
struct  Sizer< ServerName >
 
struct  Writer
 
struct  Writer< DistinguishedName >
 
struct  Writer< KeyShareEntry >
 
struct  Writer< ProtocolName >
 
struct  Writer< PskBinder >
 
struct  Writer< PskIdentity >
 
struct  Writer< Random >
 
struct  Writer< ServerName >
 
struct  WriterVector
 
struct  WriterVector< bits24, T >
 

Functions

folly::Optional< std::unique_ptr< folly::IOBuf > > evpDecrypt (std::unique_ptr< folly::IOBuf > &&ciphertext, const folly::IOBuf *associatedData, folly::ByteRange iv, folly::MutableByteRange tag, bool useBlockOps, EVP_CIPHER_CTX *decryptCtx)
 
std::unique_ptr< folly::IOBufevpEncrypt (std::unique_ptr< folly::IOBuf > &&plaintext, const folly::IOBuf *associatedData, folly::ByteRange iv, size_t tagLen, bool useBlockOps, size_t headroom, EVP_CIPHER_CTX *encryptCtx)
 
void encFunc (EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &)
 
void encFuncBlocks (EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &)
 
bool decFunc (EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &, folly::MutableByteRange)
 
bool decFuncBlocks (EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &, folly::MutableByteRange)
 
void validateECKey (const folly::ssl::EvpPkeyUniquePtr &key, int curveNid)
 
std::unique_ptr< folly::IOBufgenerateEvpSharedSecret (const folly::ssl::EvpPkeyUniquePtr &key, const folly::ssl::EvpPkeyUniquePtr &peerKey)
 
folly::ssl::EvpPkeyUniquePtr generateECKeyPair (int curveNid)
 
folly::ssl::EvpPkeyUniquePtr decodeECPublicKey (folly::ByteRange range, int curveNid)
 
std::unique_ptr< folly::IOBufencodeECPublicKey (const folly::ssl::EvpPkeyUniquePtr &key)
 
std::unique_ptr< folly::IOBufencodeECPublicKey (const folly::ssl::EcKeyUniquePtr &ecKey)
 
std::string getOpenSSLError ()
 
std::unique_ptr< folly::IOBufecSign (folly::ByteRange data, const folly::ssl::EvpPkeyUniquePtr &pkey, int hashNid)
 
void ecVerify (folly::ByteRange data, folly::ByteRange signature, const folly::ssl::EvpPkeyUniquePtr &pkey, int hashNid)
 
std::unique_ptr< folly::IOBufrsaPssSign (folly::ByteRange data, const folly::ssl::EvpPkeyUniquePtr &pkey, int hashNid)
 
void rsaPssVerify (folly::ByteRange data, folly::ByteRange signature, const folly::ssl::EvpPkeyUniquePtr &pkey, int hashNid)
 
static const EVP_MD * getHash (int hashNid)
 
std::tuple< Buf, std::vector< fizz::Extension > > decodeAuthRequest (const Buf &authRequest)
 
Buf computeTranscriptHash (std::unique_ptr< KeyDerivation > &deriver, const Buf &toBeHashed)
 
void writeBuf (const Buf &buf, folly::io::Appender &out)
 
Buf computeTranscript (const Buf &handshakeContext, const Buf &authenticatorRequest, const Buf &certificate)
 
Buf computeFinishedTranscript (const Buf &crTranscript, const Buf &certVerify)
 
Buf getFinishedData (std::unique_ptr< KeyDerivation > &deriver, Buf &finishedMacKey, const Buf &finishedTranscript)
 
folly::Optional< std::vector< SignatureScheme > > getRequestedSchemes (const std::vector< fizz::Extension > &authRequestExtensions)
 
folly::Optional< SignatureSchemegetSignatureScheme (const std::vector< SignatureScheme > &supportedSchemes, const SelfCert &cert, const std::vector< fizz::Extension > &authRequestExtensions)
 
Buf getEmptyAuthenticator (std::unique_ptr< KeyDerivation > &kderiver, Buf authRequest, Buf handshakeContext, Buf finishedMacKey)
 
template<>
size_t read< TokenBindingID > (TokenBindingID &id, folly::io::Cursor &cursor)
 
template<>
void write< TokenBindingID > (const TokenBindingID &id, folly::io::Appender &out)
 
template<>
size_t getSize< TokenBindingID > (const TokenBindingID &id)
 
template<>
size_t read< TokenBinding > (TokenBinding &tokenBinding, folly::io::Cursor &cursor)
 
template<>
void write< TokenBinding > (const TokenBinding &tokenBinding, folly::io::Appender &out)
 
template<>
size_t getSize< TokenBinding > (const TokenBinding &tokenBinding)
 
template<typename ActionsType >
void addAction (ActionsType &)
 
template<typename ActionsType , typename ActionType , typename... Args>
void addAction (ActionsType &acts, ActionType &&thisAct, Args &&...act)
 
template<class N >
size_t getBufSize (const Buf &buf)
 
template<>
size_t getBufSize< bits24 > (const Buf &buf)
 
template<class T >
size_t getSize (const T &t)
 
template<class T >
void checkWithin24bits (const typename std::enable_if< std::is_integral< T >::value &&!std::is_signed< T >::value, T >::type &value)
 
template<class T >
void writeBits24 (T len, folly::io::Appender &out)
 
template<class T >
void write (const T &in, folly::io::Appender &appender)
 
template<class N , class T >
void writeVector (const std::vector< T > &data, folly::io::Appender &out)
 
template<>
void writeBuf< bits24 > (const Buf &buf, folly::io::Appender &out)
 
template<>
void write< Extension > (const Extension &extension, folly::io::Appender &out)
 
template<>
void write< CertificateEntry > (const CertificateEntry &entry, folly::io::Appender &out)
 
uint32_t readBits24 (folly::io::Cursor &cursor)
 
template<class N >
size_t readBuf (Buf &buf, folly::io::Cursor &cursor)
 
template<>
size_t readBuf< bits24 > (Buf &buf, folly::io::Cursor &cursor)
 
template<class T >
size_t read (T &out, folly::io::Cursor &cursor)
 
template<class N , class T >
size_t readVector (std::vector< T > &out, folly::io::Cursor &cursor)
 

Function Documentation

template<typename ActionsType >
void fizz::detail::addAction ( ActionsType &  )

Definition at line 67 of file Actions.h.

References testing::Args().

Referenced by fizz::server::detail::actions(), and fizz::client::detail::actions().

67 {}
template<typename ActionsType , typename ActionType , typename... Args>
void fizz::detail::addAction ( ActionsType &  acts,
ActionType &&  thisAct,
Args &&...  act 
)

Definition at line 70 of file Actions.h.

70  {
71  acts.emplace_back(std::forward<ActionType>(thisAct));
72  addAction(acts, std::forward<Args>(act)...);
73 }
void addAction(ActionsType &acts, ActionType &&thisAct, Args &&...act)
Definition: Actions.h:70
template<class T >
void fizz::detail::checkWithin24bits ( const typename std::enable_if< std::is_integral< T >::value &&!std::is_signed< T >::value, T >::type value)

Definition at line 92 of file Types-inl.h.

References uint32_t.

94  {
95  const uint32_t UINT24_MAX = 0xFFFFFF;
96  if (value > UINT24_MAX) {
97  throw std::runtime_error("Overflow 24 bit type");
98  }
99 }
static const char *const value
Definition: Conv.cpp:50
Buf fizz::detail::computeFinishedTranscript ( const Buf crTranscript,
const Buf certVerify 
)

Definition at line 290 of file ExportedAuthenticator.cpp.

References folly::IOBuf::create(), uint16_t, and writeBuf().

Referenced by fizz::ExportedAuthenticator::makeAuthenticator(), and fizz::ExportedAuthenticator::validate().

290  {
291  constexpr uint16_t capacity = 256;
292  auto out = folly::IOBuf::create(capacity);
293  folly::io::Appender appender(out.get(), capacity);
294  detail::writeBuf(crTranscript, appender);
295  detail::writeBuf(certVerify, appender);
296  return out;
297 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
void writeBuf(const Buf &buf, folly::io::Appender &out)
Buf fizz::detail::computeTranscript ( const Buf handshakeContext,
const Buf authenticatorRequest,
const Buf certificate 
)

Definition at line 277 of file ExportedAuthenticator.cpp.

References folly::IOBuf::create(), uint16_t, and writeBuf().

Referenced by getEmptyAuthenticator(), fizz::ExportedAuthenticator::makeAuthenticator(), and fizz::ExportedAuthenticator::validate().

280  {
281  constexpr uint16_t capacity = 256;
282  auto out = folly::IOBuf::create(capacity);
283  folly::io::Appender appender(out.get(), capacity);
284  detail::writeBuf(handshakeContext, appender);
285  detail::writeBuf(authenticatorRequest, appender);
286  detail::writeBuf(certificate, appender);
287  return out;
288 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
void writeBuf(const Buf &buf, folly::io::Appender &out)
Buf fizz::detail::computeTranscriptHash ( std::unique_ptr< KeyDerivation > &  deriver,
const Buf toBeHashed 
)

Definition at line 254 of file ExportedAuthenticator.cpp.

References folly::IOBuf::create(), and folly::data().

Referenced by getEmptyAuthenticator(), fizz::ExportedAuthenticator::makeAuthenticator(), and fizz::ExportedAuthenticator::validate().

256  {
257  auto hashLength = deriver->hashLength();
258  auto data = folly::IOBuf::create(hashLength);
259  data->append(hashLength);
260  auto transcriptHash =
261  folly::MutableByteRange(data->writableData(), data->length());
262  deriver->hash(*toBeHashed, transcriptHash);
263  return data;
264 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
Range< unsigned char * > MutableByteRange
Definition: Range.h:1164
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
bool fizz::detail::decFunc ( EVP_CIPHER_CTX *  decryptCtx,
const folly::IOBuf ciphertext,
folly::IOBuf output,
folly::MutableByteRange  tagOut 
)

Definition at line 152 of file OpenSSLEVPCipher.cpp.

References folly::Range< Iter >::begin(), cipher, max, folly::Range< Iter >::size(), fizz::transformBuffer(), uint8_t, and folly::IOBuf::writableData().

Referenced by evpDecrypt().

156  {
157  int numWritten = 0;
158  int outLen = 0;
160  ciphertext,
161  output,
162  [&](uint8_t* plain, const uint8_t* cipher, size_t len) {
163  if (len > std::numeric_limits<int>::max()) {
164  throw std::runtime_error("Decryption error: too much cipher text");
165  }
166  if (EVP_DecryptUpdate(
167  decryptCtx, plain, &outLen, cipher, static_cast<int>(len)) !=
168  1) {
169  throw std::runtime_error("Decryption error");
170  }
171  numWritten += outLen;
172  });
173 
174  auto tagLen = tagOut.size();
175  if (EVP_CIPHER_CTX_ctrl(
176  decryptCtx,
177  EVP_CTRL_GCM_SET_TAG,
178  tagLen,
179  static_cast<void*>(tagOut.begin())) != 1) {
180  throw std::runtime_error("Decryption error");
181  }
182  return EVP_DecryptFinal_ex(
183  decryptCtx, output.writableData() + numWritten, &outLen) == 1;
184 }
LogLevel max
Definition: LogLevel.cpp:31
constexpr size_type size() const
Definition: Range.h:431
CipherSuite cipher
uint8_t * writableData()
Definition: IOBuf.h:509
void transformBuffer(const folly::IOBuf &in, folly::IOBuf &out, Func func)
Definition: IOBufUtil.h:38
constexpr Iter begin() const
Definition: Range.h:452
bool fizz::detail::decFuncBlocks ( EVP_CIPHER_CTX *  decryptCtx,
const folly::IOBuf ciphertext,
folly::IOBuf output,
folly::MutableByteRange  tagOut 
)

Definition at line 100 of file OpenSSLEVPCipher.cpp.

References folly::Range< Iter >::begin(), cipher, max, gmock_output_test::output, folly::Range< Iter >::size(), and uint8_t.

Referenced by evpDecrypt().

104  {
105  if (EVP_CIPHER_CTX_ctrl(
106  decryptCtx,
107  EVP_CTRL_GCM_SET_TAG,
108  tagOut.size(),
109  static_cast<void*>(tagOut.begin())) != 1) {
110  throw std::runtime_error("Decryption error");
111  }
112 
113  size_t totalWritten = 0;
114  size_t totalInput = 0;
115  int outLen = 0;
116  auto outputCursor = transformBufferBlocks<16>(
117  ciphertext,
118  output,
119  [&](uint8_t* plain, const uint8_t* cipher, size_t len) {
120  if (len > std::numeric_limits<int>::max()) {
121  throw std::runtime_error("Decryption error: too much cipher text");
122  }
123  if (EVP_DecryptUpdate(
124  decryptCtx, plain, &outLen, cipher, static_cast<int>(len)) !=
125  1) {
126  throw std::runtime_error("Decryption error");
127  }
128  totalWritten += outLen;
129  totalInput += len;
130  return static_cast<size_t>(outLen);
131  });
132 
133  // We might end up needing to write more in the final encrypt stage
134  auto numBuffered = totalInput - totalWritten;
135  auto numLeftInOutput = outputCursor.length();
136  if (numBuffered <= numLeftInOutput) {
137  auto res =
138  EVP_DecryptFinal_ex(decryptCtx, outputCursor.writableData(), &outLen);
139  return res == 1;
140  } else {
141  // we need to copy nicely - this should be at most one block
142  std::array<uint8_t, 16> block = {};
143  auto res = EVP_DecryptFinal_ex(decryptCtx, block.data(), &outLen);
144  if (res != 1) {
145  return false;
146  }
147  outputCursor.push(block.data(), outLen);
148  return true;
149  }
150 }
LogLevel max
Definition: LogLevel.cpp:31
constexpr size_type size() const
Definition: Range.h:431
CipherSuite cipher
constexpr Iter begin() const
Definition: Range.h:452
std::tuple<Buf, std::vector<fizz::Extension> > fizz::detail::decodeAuthRequest ( const Buf authRequest)

Definition at line 238 of file ExportedAuthenticator.cpp.

References folly::IOBuf::copyBuffer(), std::tr1::make_tuple(), and folly::gen::move.

Referenced by getEmptyAuthenticator(), and fizz::ExportedAuthenticator::makeAuthenticator().

239  {
240  Buf certRequestContext;
241  std::vector<fizz::Extension> exts;
242  if (authRequest && !(authRequest->empty())) {
243  folly::io::Cursor cursor(authRequest.get());
244  CertificateRequest decodedCertRequest = decode<CertificateRequest>(cursor);
245  certRequestContext =
246  std::move(decodedCertRequest.certificate_request_context);
247  exts = std::move(decodedCertRequest.extensions);
248  } else {
249  certRequestContext = folly::IOBuf::copyBuffer("");
250  }
251  return std::make_tuple(std::move(certRequestContext), std::move(exts));
252 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
tuple make_tuple()
Definition: gtest-tuple.h:675
std::unique_ptr< folly::IOBuf > Buf
Definition: Types.h:22
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587
folly::ssl::EvpPkeyUniquePtr fizz::detail::decodeECPublicKey ( folly::ByteRange  range,
int  curveNid 
)

Decodes a EC public key specified as a member of the curve curveNid.

Definition at line 84 of file OpenSSLKeyUtils.cpp.

References folly::Range< Iter >::data(), and folly::Range< Iter >::size().

Referenced by fizz::extensions::Validator::constructEcKeyFromBuf(), and fizz::detail::OpenSSLECKeyDecoder< T >::decode().

86  {
87  // Get the peer key.
88  folly::ssl::EcGroupUniquePtr curve(EC_GROUP_new_by_curve_name(curveNid));
89  folly::ssl::EcKeyUniquePtr peerKey(EC_KEY_new_by_curve_name(curveNid));
90  if (!curve || !peerKey) {
91  throw std::runtime_error("Error initializing peer key");
92  }
93  folly::ssl::EcPointUniquePtr point(EC_POINT_new(curve.get()));
94  if (!point) {
95  throw std::runtime_error("Error initializing point");
96  }
97  if (EC_POINT_oct2point(
98  curve.get(), point.get(), range.data(), range.size(), nullptr) != 1) {
99  throw std::runtime_error("Error decoding peer key");
100  }
101  if (EC_POINT_is_on_curve(curve.get(), point.get(), nullptr) != 1) {
102  throw std::runtime_error("Peer key is not on curve");
103  }
104  if (!EC_KEY_set_public_key(peerKey.get(), point.get())) {
105  throw std::runtime_error("Error setting public key");
106  }
107  folly::ssl::EvpPkeyUniquePtr peerPkey(EVP_PKEY_new());
108  if (EVP_PKEY_assign_EC_KEY(peerPkey.get(), peerKey.release()) != 1) {
109  throw std::runtime_error("Error assigning EC key");
110  }
111  return peerPkey;
112 }
std::unique_ptr< EC_POINT, EcPointDeleter > EcPointUniquePtr
constexpr size_type size() const
Definition: Range.h:431
std::unique_ptr< EVP_PKEY, EvpPkeyDeleter > EvpPkeyUniquePtr
std::unique_ptr< EC_KEY, EcKeyDeleter > EcKeyUniquePtr
std::unique_ptr< EC_GROUP, EcGroupDeleter > EcGroupUniquePtr
constexpr Iter data() const
Definition: Range.h:446
std::unique_ptr< folly::IOBuf > fizz::detail::ecSign ( folly::ByteRange  data,
const folly::ssl::EvpPkeyUniquePtr pkey,
int  hashNid 
)

Definition at line 30 of file Signature.cpp.

References folly::IOBuf::create(), folly::Range< Iter >::data(), folly::portability::ssl::EVP_MD_CTX_new(), getHash(), getOpenSSLError(), and folly::Range< Iter >::size().

Referenced by fizz::OpenSSLSignature< T >::sign().

33  {
35  if (!mdCtx) {
36  throw std::runtime_error(
37  to<std::string>("Could not allocate EVP_MD_CTX", getOpenSSLError()));
38  }
39 
40  auto hash = getHash(hashNid);
41 
42  if (EVP_SignInit(mdCtx.get(), hash) != 1) {
43  throw std::runtime_error("Could not initialize signature");
44  }
45  if (EVP_SignUpdate(mdCtx.get(), data.data(), data.size()) != 1) {
46  throw std::runtime_error(
47  to<std::string>("Could not sign data ", getOpenSSLError()));
48  }
49  auto out = folly::IOBuf::create(EVP_PKEY_size(pkey.get()));
50  unsigned int bytesWritten = 0;
51  if (EVP_SignFinal(
52  mdCtx.get(), out->writableData(), &bytesWritten, pkey.get()) != 1) {
53  throw std::runtime_error("Failed to sign");
54  }
55  out->append(bytesWritten);
56  return out;
57 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
static const EVP_MD * getHash(int hashNid)
Definition: Signature.cpp:22
constexpr size_type size() const
Definition: Range.h:431
constexpr Iter data() const
Definition: Range.h:446
std::string getOpenSSLError()
EVP_MD_CTX * EVP_MD_CTX_new()
Definition: OpenSSL.cpp:321
std::unique_ptr< EVP_MD_CTX, EvpMdCtxDeleter > EvpMdCtxUniquePtr
void fizz::detail::ecVerify ( folly::ByteRange  data,
folly::ByteRange  signature,
const folly::ssl::EvpPkeyUniquePtr pkey,
int  hashNid 
)

Definition at line 59 of file Signature.cpp.

References folly::Range< Iter >::data(), folly::portability::ssl::EVP_MD_CTX_new(), getHash(), getOpenSSLError(), and folly::Range< Iter >::size().

Referenced by fizz::OpenSSLSignature< T >::verify().

63  {
64  auto hash = getHash(hashNid);
66  if (!mdCtx) {
67  throw std::runtime_error(
68  to<std::string>("Could not allocate EVP_MD_CTX", getOpenSSLError()));
69  }
70 
71  if (EVP_VerifyInit(mdCtx.get(), hash) != 1) {
72  throw std::runtime_error("Could not initialize verification");
73  }
74 
75  if (EVP_VerifyUpdate(mdCtx.get(), data.data(), data.size()) != 1) {
76  throw std::runtime_error("Could not update verification");
77  }
78 
79  if (EVP_VerifyFinal(
80  mdCtx.get(), signature.data(), signature.size(), pkey.get()) != 1) {
81  throw std::runtime_error("Signature verification failed");
82  }
83 }
static const EVP_MD * getHash(int hashNid)
Definition: Signature.cpp:22
constexpr size_type size() const
Definition: Range.h:431
constexpr Iter data() const
Definition: Range.h:446
std::string getOpenSSLError()
EVP_MD_CTX * EVP_MD_CTX_new()
Definition: OpenSSL.cpp:321
std::unique_ptr< EVP_MD_CTX, EvpMdCtxDeleter > EvpMdCtxUniquePtr
void fizz::detail::encFunc ( EVP_CIPHER_CTX *  encryptCtx,
const folly::IOBuf plaintext,
folly::IOBuf output 
)

Definition at line 73 of file OpenSSLEVPCipher.cpp.

References cipher, max, fizz::transformBuffer(), uint8_t, and folly::IOBuf::writableData().

Referenced by evpEncrypt().

76  {
77  int numWritten = 0;
78  int outLen = 0;
80  plaintext,
81  output,
82  [&](uint8_t* cipher, const uint8_t* plain, size_t len) {
83  if (len > std::numeric_limits<int>::max()) {
84  throw std::runtime_error("Encryption error: too much plain text");
85  }
86  if (EVP_EncryptUpdate(
87  encryptCtx, cipher, &outLen, plain, static_cast<int>(len)) !=
88  1) {
89  throw std::runtime_error("Encryption error");
90  }
91  numWritten += outLen;
92  });
93  // We don't expect any writes at the end
94  if (EVP_EncryptFinal_ex(
95  encryptCtx, output.writableData() + numWritten, &outLen) != 1) {
96  throw std::runtime_error("Encryption error");
97  }
98 }
LogLevel max
Definition: LogLevel.cpp:31
CipherSuite cipher
uint8_t * writableData()
Definition: IOBuf.h:509
void transformBuffer(const folly::IOBuf &in, folly::IOBuf &out, Func func)
Definition: IOBufUtil.h:38
void fizz::detail::encFuncBlocks ( EVP_CIPHER_CTX *  encryptCtx,
const folly::IOBuf plaintext,
folly::IOBuf output 
)

Definition at line 30 of file OpenSSLEVPCipher.cpp.

References cipher, max, gmock_output_test::output, and uint8_t.

Referenced by evpEncrypt().

33  {
34  size_t totalWritten = 0;
35  size_t totalInput = 0;
36  int outLen = 0;
37  auto outputCursor = transformBufferBlocks<16>(
38  plaintext,
39  output,
40  [&](uint8_t* cipher, const uint8_t* plain, size_t len) {
41  if (len > std::numeric_limits<int>::max()) {
42  throw std::runtime_error("Encryption error: too much plain text");
43  }
44  if (EVP_EncryptUpdate(
45  encryptCtx, cipher, &outLen, plain, static_cast<int>(len)) !=
46  1 ||
47  outLen < 0) {
48  throw std::runtime_error("Encryption error");
49  }
50  totalWritten += outLen;
51  totalInput += len;
52  return static_cast<size_t>(outLen);
53  });
54 
55  // We might end up needing to write more in the final encrypt stage
56  auto numBuffered = totalInput - totalWritten;
57  auto numLeftInOutput = outputCursor.length();
58  if (numBuffered <= numLeftInOutput) {
59  if (EVP_EncryptFinal_ex(encryptCtx, outputCursor.writableData(), &outLen) !=
60  1) {
61  throw std::runtime_error("Encryption error");
62  }
63  } else {
64  // we need to copy nicely - this should be at most one block
65  std::array<uint8_t, 16> block = {};
66  if (EVP_EncryptFinal_ex(encryptCtx, block.data(), &outLen) != 1) {
67  throw std::runtime_error("Encryption error");
68  }
69  outputCursor.push(block.data(), outLen);
70  }
71 }
LogLevel max
Definition: LogLevel.cpp:31
CipherSuite cipher
std::unique_ptr< folly::IOBuf > fizz::detail::encodeECPublicKey ( const folly::ssl::EvpPkeyUniquePtr key)

Encodes the public key and returns a buffer.

Definition at line 114 of file OpenSSLKeyUtils.cpp.

Referenced by fizz::detail::OpenSSLECKeyEncoder::encode(), and fizz::extensions::TokenBindingConstructor::encodeEcKey().

115  {
116  folly::ssl::EcKeyUniquePtr ecKey(EVP_PKEY_get1_EC_KEY(key.get()));
117  if (!ecKey) {
118  throw std::runtime_error("Wrong key type");
119  }
120  return encodeECPublicKey(ecKey);
121 }
std::unique_ptr< folly::IOBuf > encodeECPublicKey(const folly::ssl::EcKeyUniquePtr &ecKey)
std::unique_ptr< EC_KEY, EcKeyDeleter > EcKeyUniquePtr
std::unique_ptr< folly::IOBuf > fizz::detail::encodeECPublicKey ( const folly::ssl::EcKeyUniquePtr ecKey)

Definition at line 123 of file OpenSSLKeyUtils.cpp.

References folly::IOBuf::create(), and group.

124  {
125  auto point = EC_KEY_get0_public_key(ecKey.get());
126  auto group = EC_KEY_get0_group(ecKey.get());
127 
128  size_t len = EC_POINT_point2oct(
129  group, point, POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
130  auto buf = folly::IOBuf::create(len);
131  // TLS 1.3 only allows uncompressed point formats, so we only support that
132  // for now.
133  len = EC_POINT_point2oct(
134  group,
135  point,
136  POINT_CONVERSION_UNCOMPRESSED,
137  buf->writableData(),
138  len,
139  nullptr);
140  if (len == 0) {
141  throw std::runtime_error("Failed to encode key");
142  }
143  buf->append(len);
144  return buf;
145 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
Optional< NamedGroup > group
folly::Optional< std::unique_ptr< folly::IOBuf > > fizz::detail::evpDecrypt ( std::unique_ptr< folly::IOBuf > &&  ciphertext,
const folly::IOBuf associatedData,
folly::ByteRange  iv,
folly::MutableByteRange  tag,
bool  useBlockOps,
EVP_CIPHER_CTX *  decryptCtx 
)

Definition at line 264 of file OpenSSLEVPCipher.cpp.

References folly::IOBuf::append(), folly::IOBuf::create(), current, folly::Range< Iter >::data(), decFunc(), decFuncBlocks(), max, folly::gen::move, folly::none, gmock_output_test::output, folly::Range< Iter >::size(), and fizz::trimBytes().

Referenced by fizz::OpenSSLEVPCipher< EVPImpl >::tryDecrypt().

270  {
271  auto tagLen = tagOut.size();
272  auto inputLength = ciphertext->computeChainDataLength();
273  if (inputLength < tagLen) {
274  return folly::none;
275  }
276  inputLength -= tagLen;
277 
278  folly::IOBuf* input;
279  std::unique_ptr<folly::IOBuf> output;
280  trimBytes(*ciphertext, tagOut);
281  if (ciphertext->isShared()) {
282  // If in is shared, then we have to make a copy of it.
283  output = folly::IOBuf::create(inputLength);
284  output->append(inputLength);
285  input = ciphertext.get();
286  } else {
287  // If in is not shared we can do decryption in-place.
288  output = std::move(ciphertext);
289  input = output.get();
290  }
291 
292  if (EVP_DecryptInit_ex(decryptCtx, nullptr, nullptr, nullptr, iv.data()) !=
293  1) {
294  throw std::runtime_error("Decryption error");
295  }
296 
297  if (associatedData) {
298  for (auto current : *associatedData) {
299  if (current.size() > std::numeric_limits<int>::max()) {
300  throw std::runtime_error("too much associated data");
301  }
302  int len;
303  if (EVP_DecryptUpdate(
304  decryptCtx,
305  nullptr,
306  &len,
307  current.data(),
308  static_cast<int>(current.size())) != 1) {
309  throw std::runtime_error("Decryption error");
310  }
311  }
312  }
313 
314  auto decrypted = useBlockOps
315  ? decFuncBlocks(decryptCtx, *input, *output, tagOut)
316  : decFunc(decryptCtx, *input, *output, tagOut);
317  if (!decrypted) {
318  return folly::none;
319  }
320  return std::move(output);
321 }
bool decFuncBlocks(EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &, folly::MutableByteRange)
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
LogLevel max
Definition: LogLevel.cpp:31
void trimBytes(IOBuf &buf, folly::MutableByteRange trimmed)
Definition: IOBufUtil.cpp:15
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
int current
constexpr Iter data() const
Definition: Range.h:446
bool isShared() const
Definition: IOBuf.h:902
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
bool decFunc(EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &, folly::MutableByteRange)
void append(std::size_t amount)
Definition: IOBuf.h:689
constexpr None none
Definition: Optional.h:87
std::unique_ptr< folly::IOBuf > fizz::detail::evpEncrypt ( std::unique_ptr< folly::IOBuf > &&  plaintext,
const folly::IOBuf associatedData,
folly::ByteRange  iv,
size_t  tagLen,
bool  useBlockOps,
size_t  headroom,
EVP_CIPHER_CTX *  encryptCtx 
)

Definition at line 186 of file OpenSSLEVPCipher.cpp.

References folly::IOBuf::advance(), folly::IOBuf::append(), folly::IOBuf::create(), current, folly::Range< Iter >::data(), encFunc(), encFuncBlocks(), max, folly::gen::move, gmock_output_test::output, folly::IOBuf::prependChain(), folly::IOBuf::prev(), folly::IOBuf::tailroom(), and folly::IOBuf::writableData().

Referenced by fizz::OpenSSLEVPCipher< EVPImpl >::encrypt().

193  {
194  auto inputLength = plaintext->computeChainDataLength();
195  // Setup input and output buffers.
196  std::unique_ptr<folly::IOBuf> output;
197  folly::IOBuf* input;
198 
199  if (plaintext->isShared()) {
200  // create enough to also fit the tag and headroom
201  output = folly::IOBuf::create(headroom + inputLength + tagLen);
202  output->advance(headroom);
203  output->append(inputLength);
204  input = plaintext.get();
205  } else {
206  output = std::move(plaintext);
207  input = output.get();
208  }
209 
210  if (EVP_EncryptInit_ex(encryptCtx, nullptr, nullptr, nullptr, iv.data()) !=
211  1) {
212  throw std::runtime_error("Encryption error");
213  }
214 
215  if (associatedData) {
216  for (auto current : *associatedData) {
217  if (current.size() > std::numeric_limits<int>::max()) {
218  throw std::runtime_error("too much associated data");
219  }
220  int len;
221  if (EVP_EncryptUpdate(
222  encryptCtx,
223  nullptr,
224  &len,
225  current.data(),
226  static_cast<int>(current.size())) != 1) {
227  throw std::runtime_error("Encryption error");
228  }
229  }
230  }
231 
232  if (useBlockOps) {
233  encFuncBlocks(encryptCtx, *input, *output);
234  } else {
235  encFunc(encryptCtx, *input, *output);
236  }
237 
238  // output is always something we can modify
239  auto tailRoom = output->prev()->tailroom();
240  if (tailRoom < tagLen) {
241  std::unique_ptr<folly::IOBuf> tag = folly::IOBuf::create(tagLen);
242  tag->append(tagLen);
243  if (EVP_CIPHER_CTX_ctrl(
244  encryptCtx, EVP_CTRL_GCM_GET_TAG, tagLen, tag->writableData()) !=
245  1) {
246  throw std::runtime_error("Encryption error");
247  }
248  output->prependChain(std::move(tag));
249  } else {
250  auto lastBuf = output->prev();
251  lastBuf->append(tagLen);
252  // we can copy into output directly
253  if (EVP_CIPHER_CTX_ctrl(
254  encryptCtx,
255  EVP_CTRL_GCM_GET_TAG,
256  tagLen,
257  lastBuf->writableTail() - tagLen) != 1) {
258  throw std::runtime_error("Encryption error");
259  }
260  }
261  return output;
262 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
LogLevel max
Definition: LogLevel.cpp:31
void encFunc(EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void advance(std::size_t amount)
Definition: IOBuf.h:632
std::size_t tailroom() const
Definition: IOBuf.h:551
int current
uint8_t * writableData()
Definition: IOBuf.h:509
constexpr Iter data() const
Definition: Range.h:446
bool isShared() const
Definition: IOBuf.h:902
void prependChain(std::unique_ptr< IOBuf > &&iobuf)
Definition: IOBuf.cpp:509
IOBuf * prev()
Definition: IOBuf.h:610
std::size_t computeChainDataLength() const
Definition: IOBuf.cpp:501
void append(std::size_t amount)
Definition: IOBuf.h:689
void encFuncBlocks(EVP_CIPHER_CTX *, const folly::IOBuf &, folly::IOBuf &)
folly::ssl::EvpPkeyUniquePtr fizz::detail::generateECKeyPair ( int  curveNid)

Generates an new EVP_PKEY on the curve. Throws an exception on error.

Definition at line 58 of file OpenSSLKeyUtils.cpp.

References params, and validateECKey().

Referenced by fizz::detail::OpenSSLECKeyExchange< T >::generateKeyPair().

58  {
59  folly::ssl::EcKeyUniquePtr ecParamKey(EC_KEY_new_by_curve_name(curveNid));
60  folly::ssl::EvpPkeyUniquePtr params(EVP_PKEY_new());
61  if (!ecParamKey || !params) {
62  throw std::runtime_error("Error initializing params");
63  }
64  if (EVP_PKEY_set1_EC_KEY(params.get(), ecParamKey.get()) != 1) {
65  throw std::runtime_error("Error setting ec key for params");
66  }
67  folly::ssl::EvpPkeyCtxUniquePtr kctx(EVP_PKEY_CTX_new(params.get(), nullptr));
68  if (!kctx) {
69  throw std::runtime_error("Error creating kctx");
70  }
71  if (EVP_PKEY_keygen_init(kctx.get()) != 1) {
72  throw std::runtime_error("Error initializing ctx");
73  }
74  EVP_PKEY* pkey = nullptr;
75  if (EVP_PKEY_keygen(kctx.get(), &pkey) != 1) {
76  throw std::runtime_error("Error generating key");
77  }
78  folly::ssl::EvpPkeyUniquePtr evpKey(pkey);
79  folly::ssl::EcKeyUniquePtr ecKey(EVP_PKEY_get1_EC_KEY(evpKey.get()));
80  validateECKey(evpKey, curveNid);
81  return evpKey;
82 }
std::unique_ptr< EVP_PKEY, EvpPkeyDeleter > EvpPkeyUniquePtr
std::unique_ptr< EC_KEY, EcKeyDeleter > EcKeyUniquePtr
constexpr Params params[]
void validateECKey(const folly::ssl::EvpPkeyUniquePtr &key, int curveNid)
std::unique_ptr< folly::IOBuf > fizz::detail::generateEvpSharedSecret ( const folly::ssl::EvpPkeyUniquePtr key,
const folly::ssl::EvpPkeyUniquePtr peerKey 
)

Generates a shared secred from a private key, key and the peerKey public key.

Definition at line 34 of file OpenSSLKeyUtils.cpp.

References folly::IOBuf::create().

Referenced by fizz::detail::OpenSSLECKeyExchange< T >::generateSharedSecret().

36  {
37  folly::ssl::EvpPkeyCtxUniquePtr ctx(EVP_PKEY_CTX_new(key.get(), nullptr));
38  if (EVP_PKEY_derive_init(ctx.get()) != 1) {
39  throw std::runtime_error("Initializing derive context failed");
40  }
41  // Start deriving the key.
42  if (EVP_PKEY_derive_set_peer(ctx.get(), peerKey.get()) != 1) {
43  throw std::runtime_error("Error setting peer key");
44  }
45  size_t secretLen = 0;
46  if (EVP_PKEY_derive(ctx.get(), nullptr, &secretLen) != 1) {
47  throw std::runtime_error("Error deriving key");
48  }
49  // secretLen is now the maximum secret length.
50  auto buf = folly::IOBuf::create(secretLen);
51  if (EVP_PKEY_derive(ctx.get(), buf->writableData(), &secretLen) != 1) {
52  throw std::runtime_error("Error deriving key");
53  }
54  buf->append(secretLen);
55  return buf;
56 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
template<class N >
size_t fizz::detail::getBufSize ( const Buf buf)

Definition at line 33 of file Types-inl.h.

33  {
34  return sizeof(N) + buf->computeChainDataLength();
35 }
template<>
size_t fizz::detail::getBufSize< bits24 > ( const Buf buf)
inline

Definition at line 38 of file Types-inl.h.

References fizz::detail::bits24::size.

Referenced by fizz::detail::Sizer< CertificateEntry >::getSize().

38  {
39  return bits24::size + buf->computeChainDataLength();
40 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
Buf fizz::detail::getEmptyAuthenticator ( std::unique_ptr< KeyDerivation > &  kderiver,
Buf  authRequest,
Buf  handshakeContext,
Buf  finishedMacKey 
)

Definition at line 361 of file ExportedAuthenticator.cpp.

References fizz::CertificateMsg::certificate_request_context, computeTranscript(), computeTranscriptHash(), decodeAuthRequest(), fizz::encodeHandshake(), getFinishedData(), folly::gen::move, and fizz::Finished::verify_data.

Referenced by fizz::ExportedAuthenticator::makeAuthenticator(), and fizz::ExportedAuthenticator::validate().

365  {
366  CertificateMsg emptyCertMsg;
367  emptyCertMsg.certificate_request_context =
368  std::get<0>(detail::decodeAuthRequest(authRequest));
369  auto encodedEmptyCertMsg = encodeHandshake(std::move(emptyCertMsg));
370  auto emptyAuthTranscript = detail::computeTranscript(
371  handshakeContext, authRequest, encodedEmptyCertMsg);
372  auto emptyAuthTranscriptHash =
373  detail::computeTranscriptHash(kderiver, emptyAuthTranscript);
374  auto finVerify = detail::getFinishedData(
375  kderiver, finishedMacKey, emptyAuthTranscriptHash);
376  Finished emptyAuth;
377  emptyAuth.verify_data = std::move(finVerify);
378  auto encodedEmptyAuth = encodeHandshake(std::move(emptyAuth));
379  return encodedEmptyAuth;
380 }
Buf encodeHandshake(T &&handshakeMsg)
Definition: Types-inl.h:515
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Buf computeTranscript(const Buf &handshakeContext, const Buf &authenticatorRequest, const Buf &certificate)
Buf getFinishedData(std::unique_ptr< KeyDerivation > &deriver, Buf &finishedMacKey, const Buf &finishedTranscript)
std::tuple< Buf, std::vector< fizz::Extension > > decodeAuthRequest(const Buf &authRequest)
Buf computeTranscriptHash(std::unique_ptr< KeyDerivation > &deriver, const Buf &toBeHashed)
Buf fizz::detail::getFinishedData ( std::unique_ptr< KeyDerivation > &  deriver,
Buf finishedMacKey,
const Buf finishedTranscript 
)

Definition at line 299 of file ExportedAuthenticator.cpp.

References folly::IOBuf::create(), and folly::data().

Referenced by fizz::client::test::ClientProtocolTest::doFinishedFlow(), getEmptyAuthenticator(), fizz::ExportedAuthenticator::makeAuthenticator(), fizz::test::MockHandshakeContext::setDefaults(), fizz::client::test::TEST_F(), fizz::server::test::TEST_F(), and fizz::ExportedAuthenticator::validate().

302  {
303  auto hashLength = deriver->hashLength();
304  auto data = folly::IOBuf::create(hashLength);
305  data->append(hashLength);
306  auto outRange = folly::MutableByteRange(data->writableData(), data->length());
307  deriver->hmac(finishedMacKey->coalesce(), *finishedTranscript, outRange);
308  return data;
309 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
Range< unsigned char * > MutableByteRange
Definition: Range.h:1164
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
static const EVP_MD* fizz::detail::getHash ( int  hashNid)
static

Definition at line 22 of file Signature.cpp.

Referenced by ecSign(), ecVerify(), rsaPssSign(), and rsaPssVerify().

22  {
23  const auto hash = EVP_get_digestbynid(hashNid);
24  if (!hash) {
25  throw std::runtime_error("Invalid hash. Have you initialized openssl?");
26  }
27  return hash;
28 }
std::string fizz::detail::getOpenSSLError ( )

Returns the current error in the thread queue as a string.

Definition at line 147 of file OpenSSLKeyUtils.cpp.

References string.

Referenced by ecSign(), ecVerify(), rsaPssSign(), rsaPssVerify(), and fizz::extensions::Validator::verify().

147  {
148  auto err = ERR_get_error();
149  if (err == 0) {
150  return "";
151  }
152  char errMsg[256];
153  ERR_error_string_n(ERR_get_error(), errMsg, sizeof(errMsg));
154  return std::string(errMsg);
155 }
const char * string
Definition: Conv.cpp:212
folly::Optional< std::vector< SignatureScheme > > fizz::detail::getRequestedSchemes ( const std::vector< fizz::Extension > &  authRequestExtensions)

Definition at line 311 of file ExportedAuthenticator.cpp.

References folly::none.

Referenced by getSignatureScheme().

312  {
313  if (!(authRequestExtensions.empty())) {
314  auto sigAlgsExtension =
315  getExtension<SignatureAlgorithms>(authRequestExtensions);
316  if (sigAlgsExtension) {
317  auto requestedSchemes = sigAlgsExtension->supported_signature_algorithms;
318  return requestedSchemes;
319  } else {
320  return folly::none;
321  }
322  } else {
323  return folly::none;
324  }
325 }
constexpr None none
Definition: Optional.h:87
folly::Optional< SignatureScheme > fizz::detail::getSignatureScheme ( const std::vector< SignatureScheme > &  supportedSchemes,
const SelfCert cert,
const std::vector< fizz::Extension > &  authRequestExtensions 
)

Definition at line 327 of file ExportedAuthenticator.cpp.

References getRequestedSchemes(), and fizz::SelfCert::getSigSchemes().

Referenced by fizz::ExportedAuthenticator::makeAuthenticator().

330  {
331  folly::Optional<SignatureScheme> selectedScheme;
332  const auto certSchemes = cert.getSigSchemes();
334  getRequestedSchemes(authRequestExtensions);
335  if (requestedSchemes) {
336  for (const auto& scheme : supportedSchemes) {
337  if (std::find(certSchemes.begin(), certSchemes.end(), scheme) !=
338  certSchemes.end() &&
339  std::find(
340  (*requestedSchemes).begin(), (*requestedSchemes).end(), scheme) !=
341  (*requestedSchemes).end()) {
342  selectedScheme = scheme;
343  break;
344  }
345  }
346  }
347 
348  if (!selectedScheme) {
349  VLOG(1) << "authenticator request without proper signature algorithms";
350  for (const auto& scheme : supportedSchemes) {
351  if (std::find(certSchemes.begin(), certSchemes.end(), scheme) !=
352  certSchemes.end()) {
353  selectedScheme = scheme;
354  break;
355  }
356  }
357  }
358  return selectedScheme;
359 }
folly::Optional< std::vector< SignatureScheme > > getRequestedSchemes(const std::vector< fizz::Extension > &authRequestExtensions)
template<class T >
size_t fizz::detail::getSize ( const T t)

Definition at line 43 of file Types-inl.h.

Referenced by fizz::detail::Sizer< CertificateEntry >::getSize(), and getSize< TokenBinding >().

43  {
44  return Sizer<T>().template getSize<T>(t);
45 }
template<>
size_t fizz::detail::getSize< TokenBinding > ( const TokenBinding tokenBinding)

Definition at line 60 of file Types.cpp.

References getSize().

60  {
61  return sizeof(TokenBindingType) + getSize(tokenBinding.tokenbindingid) +
62  getBufSize<uint16_t>(tokenBinding.signature) +
63  getBufSize<uint16_t>(tokenBinding.extensions);
64 }
size_t getSize(const T &t)
Definition: Types-inl.h:43
TokenBindingID tokenbindingid
Definition: Types.h:58
template<>
size_t fizz::detail::getSize< TokenBindingID > ( const TokenBindingID id)

Definition at line 34 of file Types.cpp.

34  {
35  return sizeof(TokenBindingKeyParameters) + getBufSize<uint16_t>(id.key);
36 }
TokenBindingKeyParameters
Definition: Types.h:33
template<class T >
size_t fizz::detail::read ( T out,
folly::io::Cursor cursor 
)

Definition at line 258 of file Types-inl.h.

Referenced by folly::gen::detail::FileReader::apply(), BENCHMARK(), folly::portability::ssl::BIO_meth_set_read(), wangle::Pipeline< int >::create(), fizz::server::TicketCodec< Storage >::decode(), fizz::decode(), fizz::decode< KeyUpdate >(), fizz::decode< NewSessionTicket >(), fizz::server::detail::decodeCookie(), EventHandlerTest::efd_read(), upload.MercurialVCS::GetBaseFile(), fizz::getBinderLength(), fizz::getExtension(), fizz::test::ExtensionsTest::getExtensions(), folly::getSchedTimeWaiting(), fizz::tool::TerminalInputHandler::handlerReady(), folly::symbolizer::ElfFile::init(), folly::ssl::detail::isSSLLockDisabled(), fizz::MockEncryptedReadRecordLayer::MockEncryptedReadRecordLayer(), folly::AsyncIO::pollCompleted(), pwritev(), fizz::detail::Reader< KeyShareEntry >::read(), fizz::detail::Reader< PskIdentity >::read(), fizz::detail::Reader< ServerName >::read(), testing::internal::posix::Read(), read< TokenBinding >(), read< TokenBindingID >(), read_all(), fizz::server::readClientCertificate(), readFromFD(), folly::readFull(), folly::readNoInt(), readUntilEmpty(), fizz::detail::ReadVector< N, T >::readVector(), fizz::detail::ReadVector< bits24, T >::readVector(), folly::test::runCloseTest(), folly::test::runKillTest(), folly::symbolizer::Dwarf::Section::Section(), BroadcastHandlerTest::SetUp(), TEST(), folly::test::TEST(), fizz::test::TEST_F(), TEST_F(), test_message(), test_message_count_body(), test_multiple3(), and test_scan().

258  {
259  return Reader<T>().template read<T>(out, cursor);
260 }
template<>
size_t fizz::detail::read< TokenBinding > ( TokenBinding tokenBinding,
folly::io::Cursor cursor 
)

Definition at line 39 of file Types.cpp.

References read().

41  {
42  auto len = read(tokenBinding.tokenbinding_type, cursor);
43  len += read(tokenBinding.tokenbindingid, cursor);
44  len += readBuf<uint16_t>(tokenBinding.signature, cursor);
45  len += readBuf<uint16_t>(tokenBinding.extensions, cursor);
46  return len;
47 }
TokenBindingType tokenbinding_type
Definition: Types.h:57
size_t read(T &out, folly::io::Cursor &cursor)
Definition: Types-inl.h:258
TokenBindingID tokenbindingid
Definition: Types.h:58
template<>
size_t fizz::detail::read< TokenBindingID > ( TokenBindingID id,
folly::io::Cursor cursor 
)

Definition at line 21 of file Types.cpp.

References read().

21  {
22  auto len = read(id.key_parameters, cursor);
23  len += readBuf<uint16_t>(id.key, cursor);
24  return len;
25 }
size_t read(T &out, folly::io::Cursor &cursor)
Definition: Types-inl.h:258
uint32_t fizz::detail::readBits24 ( folly::io::Cursor cursor)
inline

Definition at line 210 of file Types-inl.h.

References addr, folly::Endian::big(), data, folly::io::detail::CursorBase< Derived, BufType >::pull(), uint32_t, and uint8_t.

Referenced by fizz::decode(), fizz::ReadRecordLayer::decodeHandshakeMessage(), readBuf< bits24 >(), fizz::detail::ReadVector< bits24, T >::readVector(), and fizz::test::TEST().

210  {
211  uint32_t data = 0;
212  uint8_t offset = sizeof(data) - 3;
213  uint8_t* addr = reinterpret_cast<uint8_t*>(&data);
214  cursor.pull(addr + offset, 3);
215  uint32_t length = folly::Endian::big(data);
216  return length;
217 }
void pull(void *buf, size_t len)
Definition: Cursor.h:418
static T big(T x)
Definition: Bits.h:259
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
ThreadPoolListHook * addr
template<class N >
size_t fizz::detail::readBuf ( Buf buf,
folly::io::Cursor cursor 
)
template<>
size_t fizz::detail::readBuf< bits24 > ( Buf buf,
folly::io::Cursor cursor 
)
inline

Definition at line 227 of file Types-inl.h.

References readBits24(), and fizz::detail::bits24::size.

Referenced by fizz::detail::Reader< CertificateEntry >::read().

227  {
228  auto len = readBits24(cursor);
229  cursor.clone(buf, len);
230  return bits24::size + len;
231 }
void clone(std::unique_ptr< folly::IOBuf > &buf, size_t len)
Definition: Cursor.h:456
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
uint32_t readBits24(folly::io::Cursor &cursor)
Definition: Types-inl.h:210
template<class N , class T >
size_t fizz::detail::readVector ( std::vector< T > &  out,
folly::io::Cursor cursor 
)

Definition at line 303 of file Types-inl.h.

303  {
304  return ReadVector<N, T>().readVector(out, cursor);
305 }
size_t readVector(std::vector< T > &out, folly::io::Cursor &cursor)
Definition: Types-inl.h:303
std::unique_ptr< folly::IOBuf > fizz::detail::rsaPssSign ( folly::ByteRange  data,
const folly::ssl::EvpPkeyUniquePtr pkey,
int  hashNid 
)

Definition at line 85 of file Signature.cpp.

References folly::IOBuf::create(), folly::Range< Iter >::data(), folly::portability::ssl::EVP_MD_CTX_new(), getHash(), getOpenSSLError(), and folly::Range< Iter >::size().

Referenced by fizz::OpenSSLSignature< T >::sign().

88  {
89  auto hash = getHash(hashNid);
91  if (!mdCtx) {
92  throw std::runtime_error(
93  to<std::string>("Could not allocate EVP_MD_CTX", getOpenSSLError()));
94  }
95 
96  EVP_PKEY_CTX* ctx;
97  if (EVP_DigestSignInit(mdCtx.get(), &ctx, hash, nullptr, pkey.get()) != 1) {
98  throw std::runtime_error("Could not initialize signature");
99  }
100 
101  if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
102  throw std::runtime_error("Could not set pss padding");
103  }
104 
105  if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
106  throw std::runtime_error("Could not set pss salt length");
107  }
108 
109  if (EVP_DigestSignUpdate(mdCtx.get(), data.data(), data.size()) != 1) {
110  throw std::runtime_error("Could not update signature");
111  }
112 
113  size_t bytesWritten = EVP_PKEY_size(pkey.get());
114  auto out = folly::IOBuf::create(bytesWritten);
115  if (EVP_DigestSignFinal(mdCtx.get(), out->writableData(), &bytesWritten) !=
116  1) {
117  throw std::runtime_error("Failed to sign");
118  }
119  out->append(bytesWritten);
120  return out;
121 }
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
static const EVP_MD * getHash(int hashNid)
Definition: Signature.cpp:22
constexpr size_type size() const
Definition: Range.h:431
constexpr Iter data() const
Definition: Range.h:446
std::string getOpenSSLError()
EVP_MD_CTX * EVP_MD_CTX_new()
Definition: OpenSSL.cpp:321
std::unique_ptr< EVP_MD_CTX, EvpMdCtxDeleter > EvpMdCtxUniquePtr
void fizz::detail::rsaPssVerify ( folly::ByteRange  data,
folly::ByteRange  signature,
const folly::ssl::EvpPkeyUniquePtr pkey,
int  hashNid 
)

Definition at line 123 of file Signature.cpp.

References folly::Range< Iter >::data(), folly::portability::ssl::EVP_MD_CTX_new(), getHash(), getOpenSSLError(), and folly::Range< Iter >::size().

Referenced by fizz::OpenSSLSignature< T >::verify().

127  {
128  auto hash = getHash(hashNid);
130  if (!mdCtx) {
131  throw std::runtime_error(
132  to<std::string>("Could not allocate EVP_MD_CTX", getOpenSSLError()));
133  }
134 
135  EVP_PKEY_CTX* ctx;
136  if (EVP_DigestVerifyInit(mdCtx.get(), &ctx, hash, nullptr, pkey.get()) != 1) {
137  throw std::runtime_error("Could not initialize verification");
138  }
139 
140  if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
141  throw std::runtime_error("Could not set pss padding");
142  }
143 
144  if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
145  throw std::runtime_error("Could not set pss salt length");
146  }
147 
148  if (EVP_DigestVerifyUpdate(mdCtx.get(), data.data(), data.size()) != 1) {
149  throw std::runtime_error("Could not update verification");
150  }
151 
152  if (EVP_DigestVerifyFinal(mdCtx.get(), signature.data(), signature.size()) !=
153  1) {
154  throw std::runtime_error("Signature verification failed");
155  }
156 }
static const EVP_MD * getHash(int hashNid)
Definition: Signature.cpp:22
constexpr size_type size() const
Definition: Range.h:431
constexpr Iter data() const
Definition: Range.h:446
std::string getOpenSSLError()
EVP_MD_CTX * EVP_MD_CTX_new()
Definition: OpenSSL.cpp:321
std::unique_ptr< EVP_MD_CTX, EvpMdCtxDeleter > EvpMdCtxUniquePtr
void fizz::detail::validateECKey ( const folly::ssl::EvpPkeyUniquePtr key,
int  curveNid 
)

Validates whether or not the EVP_PKEY belongs to the curve. If not, this throws an exception.

Definition at line 16 of file OpenSSLKeyUtils.cpp.

Referenced by generateECKeyPair(), fizz::OpenSSLSignature< T >::setKey(), fizz::detail::OpenSSLECKeyExchange< T >::setPrivateKey(), and fizz::test::TEST().

16  {
17  folly::ssl::EcKeyUniquePtr ecKey(EVP_PKEY_get1_EC_KEY(key.get()));
18  if (!ecKey) {
19  throw std::runtime_error("Wrong key type");
20  }
21  if (EC_KEY_check_key(ecKey.get()) != 1) {
22  throw std::runtime_error("Private key not valid");
23  }
24  folly::ssl::EcGroupUniquePtr curve(EC_GROUP_new_by_curve_name(curveNid));
25  if (!curve) {
26  throw std::runtime_error("Failed to create curve");
27  }
28  auto keyGroup = EC_KEY_get0_group(ecKey.get());
29  if (EC_GROUP_cmp(keyGroup, curve.get(), nullptr) != 0) {
30  throw std::runtime_error("Invalid group");
31  }
32 }
std::unique_ptr< EC_KEY, EcKeyDeleter > EcKeyUniquePtr
std::unique_ptr< EC_GROUP, EcGroupDeleter > EcGroupUniquePtr
template<class T >
void fizz::detail::write ( const T in,
folly::io::Appender appender 
)

Definition at line 112 of file Types-inl.h.

Referenced by folly::PriorityLifoSemMPMCQueue< T, kBehavior >::addWithPriority(), fizz::server::appendClientCertificate(), fizz::test::appWrite(), folly::AsyncPipeWriter::AsyncPipeWriter(), BENCHMARK(), folly::portability::ssl::BIO_meth_set_write(), fizz::test::ExtensionsTest::checkEncode(), folly::gen::detail::FileWriter::compose(), fizz::extensions::TokenBindingUtils::constructMessage(), wangle::Pipeline< int >::create(), fizz::client::test::ClientProtocolTest::doFinishedFlow(), EventHandlerTest::efd_write(), fizz::server::TicketCodec< Storage >::encode(), fizz::encode< Alert >(), fizz::encode< CertificateVerify >(), fizz::encode< CompressedCertificate & >(), fizz::encode< const ClientHello & >(), fizz::encode< HelloRetryRequest >(), fizz::encode< KeyUpdate >(), fizz::encode< NewSessionTicket >(), fizz::encode< ServerHello >(), fizz::server::detail::encodeCookie(), fizz::encodeExtension(), fizz::encodeHandshake(), fizz::encodeHkdfLabel(), encryptGCM(), folly::NotificationQueue< folly::AsyncServerSocket::QueueMessage >::ensureSignalLocked(), fizz::server::test::AsyncFizzServerTest::expectAppClose(), fizz::client::test::AsyncFizzClientTest::expectAppClose(), fizz::test::ProtocolTest< ClientTypes, Actions >::expectError(), folly::gen::detail::FileWriter::flushBuffer(), fizz::sm::generateTicket(), fizz::sm::getCertificateRequest(), fizz::sm::getEarlyDataParams(), fizz::sm::getMaxEarlyDataSize(), fizz::server::detail::handleAppClose(), fizz::client::detail::handleAppClose(), fizz::sm::handleEarlyAppWrite(), fizz::server::detail::handleError(), fizz::client::detail::handleError(), fizz::FizzBase< Derived, ActionMoveVisitor, StateMachine >::moveToErrorState(), fizz::test::TestStateMachine::processAppWrite(), fizz::test::TestStateMachine::processEarlyAppWrite(), fizz::FizzBase< Derived, ActionMoveVisitor, StateMachine >::processPendingEvents(), pwritev(), TelnetHandler::read(), FileServerHandler::read(), EchoHandler::read(), BogoTestServer::readBufferAvailable(), BogoTestClient::readBufferAvailable(), FileServerHandler::readException(), folly::TEST(), TEST(), folly::test::TEST(), fizz::test::TEST_F(), fizz::server::test::TEST_F(), fizz::client::test::TEST_F(), testing::internal::TestResultAccessor::test_part_results(), gtest_output_test.GTestOutputTest::testOutput(), TelnetHandler::transportActive(), ThreadPrintingHandler::transportActive(), FileServerHandler::transportActive(), wangle::Handler< Resp, Resp, folly::Req, folly::Req >::transportInactive(), release_docs.WikiBrancher::UpdateLinksInBranchedFiles(), fizz::PlaintextWriteRecordLayer::write(), folly::gen::detail::FileWriter::write(), fizz::detail::Writer< KeyShareEntry >::write(), fizz::detail::Writer< PskIdentity >::write(), fizz::detail::Writer< ServerName >::write(), testing::internal::posix::Write(), write< TokenBinding >(), write< TokenBindingID >(), fizz::WriteRecordLayer::writeAlert(), fizz::WriteRecordLayer::writeAppData(), folly::AsyncPipeWriter::writeChain(), folly::writeFull(), fizz::WriteRecordLayer::writeHandshake(), fizz::PlaintextWriteRecordLayer::writeInitialClientHello(), fizz::test::writeNewSessionTicket(), folly::writeNoInt(), writeToFD(), writeUntilFull(), fizz::detail::WriterVector< N, T >::writeVector(), and fizz::detail::WriterVector< bits24, T >::writeVector().

112  {
113  Writer<T>().template write<T>(in, appender);
114 }
template<>
void fizz::detail::write< CertificateEntry > ( const CertificateEntry entry,
folly::io::Appender out 
)
inline

Definition at line 203 of file Types-inl.h.

205  {
206  writeBuf<detail::bits24>(entry.cert_data, out);
207  writeVector<uint16_t>(entry.extensions, out);
208 }
template<>
void fizz::detail::write< Extension > ( const Extension extension,
folly::io::Appender out 
)
inline

Definition at line 194 of file Types-inl.h.

References type, and folly::io::detail::Writable< Derived >::writeBE().

196  {
197  out.writeBE(static_cast<typename std::underlying_type<ExtensionType>::type>(
198  extension.extension_type));
199  writeBuf<uint16_t>(extension.extension_data, out);
200 }
PskType type
void writeBE(T value)
Definition: Cursor.h:744
template<>
void fizz::detail::write< TokenBinding > ( const TokenBinding tokenBinding,
folly::io::Appender out 
)

Definition at line 50 of file Types.cpp.

References write().

52  {
53  write(tokenBinding.tokenbinding_type, out);
54  write(tokenBinding.tokenbindingid, out);
55  writeBuf<uint16_t>(tokenBinding.signature, out);
56  writeBuf<uint16_t>(tokenBinding.extensions, out);
57 }
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
TokenBindingType tokenbinding_type
Definition: Types.h:57
TokenBindingID tokenbindingid
Definition: Types.h:58
template<>
void fizz::detail::write< TokenBindingID > ( const TokenBindingID id,
folly::io::Appender out 
)

Definition at line 28 of file Types.cpp.

References write().

28  {
29  write(id.key_parameters, out);
30  writeBuf<uint16_t>(id.key, out);
31 }
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
template<class T >
void fizz::detail::writeBits24 ( T  len,
folly::io::Appender out 
)

Definition at line 102 of file Types-inl.h.

References addr, folly::Endian::big(), folly::io::detail::Writable< Derived >::push(), fizz::detail::bits24::size, T, and uint8_t.

Referenced by fizz::encode< CompressedCertificate & >(), fizz::encodeHandshake(), fizz::test::TEST(), writeBuf< bits24 >(), and fizz::detail::WriterVector< bits24, T >::writeVector().

102  {
103  static_assert(sizeof(T) > 3, "Type is too short");
104  checkWithin24bits<T>(len);
105  T lenBE = folly::Endian::big(len);
106  uint8_t* addr = reinterpret_cast<uint8_t*>(&lenBE);
107  uint8_t offset = sizeof(T) - 3;
108  out.push(addr + offset, bits24::size);
109 }
#define T(v)
Definition: http_parser.c:233
void push(const uint8_t *buf, size_t len)
Definition: Cursor.h:755
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
static T big(T x)
Definition: Bits.h:259
ThreadPoolListHook * addr
template<>
void fizz::detail::writeBuf< bits24 > ( const Buf buf,
folly::io::Appender out 
)
inline

Definition at line 179 of file Types-inl.h.

References current, i, folly::io::detail::Writable< Derived >::push(), and writeBits24().

179  {
180  if (!buf) {
181  writeBits24(static_cast<size_t>(0), out);
182  return;
183  }
184  writeBits24(buf->computeChainDataLength(), out);
185  auto current = buf.get();
186  size_t chainElements = buf->countChainElements();
187  for (size_t i = 0; i < chainElements; ++i) {
188  out.push(current->data(), current->length());
189  current = current->next();
190  }
191 }
void push(const uint8_t *buf, size_t len)
Definition: Cursor.h:755
int current
void writeBits24(T len, folly::io::Appender &out)
Definition: Types-inl.h:102
template<class N , class T >
void fizz::detail::writeVector ( const std::vector< T > &  data,
folly::io::Appender out 
)

Definition at line 149 of file Types-inl.h.

References current, i, folly::io::detail::Writable< Derived >::push(), folly::io::detail::Writable< Derived >::writeBE(), and writeBuf().

149  {
150  return WriterVector<N, T>().writeVector(data, out);
151 }
void writeVector(const std::vector< T > &data, folly::io::Appender &out)
Definition: Types-inl.h:149