Crypto++ 8.2 Free C++ class library of cryptographic schemes

secblock.h
Go to the documentation of this file.
1 // secblock.h - originally written and placed in the public domain by Wei Dai
2
3 /// \file secblock.h
4 /// \brief Classes and functions for secure memory allocations.
5
6 #ifndef CRYPTOPP_SECBLOCK_H
7 #define CRYPTOPP_SECBLOCK_H
8
9 #include "config.h"
10 #include "allocate.h"
11 #include "misc.h"
12 #include "stdcpp.h"
13
14 #if CRYPTOPP_MSC_VERSION
15 # pragma warning(push)
16 # pragma warning(disable: 4231 4275 4700)
17 # if (CRYPTOPP_MSC_VERSION >= 1400)
18 # pragma warning(disable: 6011 6386 28193)
19 # endif
20 #endif
21
22 NAMESPACE_BEGIN(CryptoPP)
23
24 // ************** secure memory allocation ***************
25
26 /// \brief Base class for all allocators used by SecBlock
27 /// \tparam T the class or type
28 template<class T>
29 class AllocatorBase
30 {
31 public:
32 typedef T value_type;
33 typedef size_t size_type;
34 typedef std::ptrdiff_t difference_type;
35 typedef T * pointer;
36 typedef const T * const_pointer;
37 typedef T & reference;
38 typedef const T & const_reference;
39
40 pointer address(reference r) const {return (&r);}
41 const_pointer address(const_reference r) const {return (&r); }
42 void construct(pointer p, const T& val) {new (p) T(val);}
43 void destroy(pointer p) {CRYPTOPP_UNUSED(p); p->~T();}
44
45 /// \brief Returns the maximum number of elements the allocator can provide
46 /// \details <tt>ELEMS_MAX</tt> is the maximum number of elements the
47 /// <tt>Allocator</tt> can provide. The value of <tt>ELEMS_MAX</tt> is
48 /// <tt>SIZE_MAX/sizeof(T)</tt>. <tt>std::numeric_limits</tt> was avoided
49 /// due to lack of <tt>constexpr</tt>-ness in C++03 and below.
50 /// \note In C++03 and below <tt>ELEMS_MAX</tt> is a static data member of type
51 /// <tt>size_type</tt>. In C++11 and above <tt>ELEMS_MAX</tt> is an <tt>enum</tt>
52 /// inheriting from <tt>size_type</tt>. In both cases <tt>ELEMS_MAX</tt> can be
53 /// used before objects are fully constructed, and it does not suffer the
54 /// limitations of class methods like <tt>max_size</tt>.
55 /// \sa <A HREF="http://github.com/weidai11/cryptopp/issues/346">Issue 346/CVE-2016-9939</A>
56 /// \since Crypto++ 6.0
57 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
58 static const size_type ELEMS_MAX = ...;
59 #elif defined(_MSC_VER) && (_MSC_VER <= 1400)
60 static const size_type ELEMS_MAX = (~(size_type)0)/sizeof(T);
61 #elif defined(CRYPTOPP_CXX11_STRONG_ENUM)
62 enum : size_type {ELEMS_MAX = SIZE_MAX/sizeof(T)};
63 #else
64 static const size_type ELEMS_MAX = SIZE_MAX/sizeof(T);
65 #endif
66
67 /// \brief Returns the maximum number of elements the allocator can provide
68 /// \return the maximum number of elements the allocator can provide
69 /// \details Internally, preprocessor macros are used rather than std::numeric_limits
70 /// because the latter is not a constexpr. Some compilers, like Clang, do not
71 /// optimize it well under all circumstances. Compilers like GCC, ICC and MSVC appear
72 /// to optimize it well in either form.
73 CRYPTOPP_CONSTEXPR size_type max_size() const {return ELEMS_MAX;}
74
75 #if defined(__SUNPRO_CC)
76 // https://github.com/weidai11/cryptopp/issues/770
77 // and https://stackoverflow.com/q/53999461/608639
78 CRYPTOPP_CONSTEXPR size_type max_size(size_type n) const {return SIZE_MAX/n;}
79 #endif
80
81 #if defined(CRYPTOPP_CXX11_VARIADIC_TEMPLATES) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
82
83 /// \brief Constructs a new V using variadic arguments
84 /// \tparam V the type to be forwarded
85 /// \tparam Args the arguments to be forwarded
86 /// \param ptr pointer to type V
87 /// \param args variadic arguments
88 /// \details This is a C++11 feature. It is available when CRYPTOPP_CXX11_VARIADIC_TEMPLATES
89 /// is defined. The define is controlled by compiler versions detected in config.h.
90 template<typename V, typename... Args>
91 void construct(V* ptr, Args&&... args) {::new ((void*)ptr) V(std::forward<Args>(args)...);}
92
93 /// \brief Destroys an V constructed with variadic arguments
94 /// \tparam V the type to be forwarded
95 /// \details This is a C++11 feature. It is available when CRYPTOPP_CXX11_VARIADIC_TEMPLATES
96 /// is defined. The define is controlled by compiler versions detected in config.h.
97 template<typename V>
98 void destroy(V* ptr) {if (ptr) ptr->~V();}
99
100 #endif
101
102 protected:
103
104 /// \brief Verifies the allocator can satisfy a request based on size
105 /// \param size the size of the allocation, in elements
106 /// \throw InvalidArgument
107 /// \details CheckSize verifies the number of elements requested is valid.
108 /// \details If size is greater than max_size(), then InvalidArgument is thrown.
109 /// The library throws InvalidArgument if the size is too large to satisfy.
110 /// \details Internally, preprocessor macros are used rather than std::numeric_limits
111 /// because the latter is not a constexpr. Some compilers, like Clang, do not
112 /// optimize it well under all circumstances. Compilers like GCC, ICC and MSVC appear
113 /// to optimize it well in either form.
114 /// \details The <tt>sizeof(T) != 1</tt> in the condition attempts to help the
115 /// compiler optimize the check for byte types. Coverity findings for
116 /// CONSTANT_EXPRESSION_RESULT were generated without it. For byte types,
117 /// size never exceeded ELEMS_MAX but the code was not removed.
118 /// \note size is the count of elements, and not the number of bytes
119 static void CheckSize(size_t size)
120 {
121 // Squash MSC C4100 warning for size. Also see commit 42b7c4ea5673.
122 CRYPTOPP_UNUSED(size);
123 // C++ throws std::bad_alloc (C++03) or std::bad_array_new_length (C++11) here.
124 if (sizeof(T) != 1 && size > ELEMS_MAX)
125 throw InvalidArgument("AllocatorBase: requested size would cause integer overflow");
126 }
127 };
128
129 #define CRYPTOPP_INHERIT_ALLOCATOR_TYPES \
130 typedef typename AllocatorBase<T>::value_type value_type;\
131 typedef typename AllocatorBase<T>::size_type size_type;\
132 typedef typename AllocatorBase<T>::difference_type difference_type;\
133 typedef typename AllocatorBase<T>::pointer pointer;\
134 typedef typename AllocatorBase<T>::const_pointer const_pointer;\
135 typedef typename AllocatorBase<T>::reference reference;\
136 typedef typename AllocatorBase<T>::const_reference const_reference;
137
138 /// \brief Reallocation function
139 /// \tparam T the class or type
140 /// \tparam A the class or type's allocator
141 /// \param alloc the allocator
142 /// \param oldPtr the previous allocation
143 /// \param oldSize the size of the previous allocation
144 /// \param newSize the new, requested size
145 /// \param preserve flag that indicates if the old allocation should be preserved
146 /// \note oldSize and newSize are the count of elements, and not the
147 /// number of bytes.
148 template <class T, class A>
149 typename A::pointer StandardReallocate(A& alloc, T *oldPtr, typename A::size_type oldSize, typename A::size_type newSize, bool preserve)
150 {
151 // Avoid assert on pointer in reallocate. SecBlock regularly uses NULL
152 // pointers rather returning non-NULL 0-sized pointers.
153 if (oldSize == newSize)
154 return oldPtr;
155
156 if (preserve)
157 {
158 typename A::pointer newPointer = alloc.allocate(newSize, NULLPTR);
159 const typename A::size_type copySize = STDMIN(oldSize, newSize) * sizeof(T);
160
161 if (oldPtr && newPointer)
162 memcpy_s(newPointer, copySize, oldPtr, copySize);
163
164 if (oldPtr)
165 alloc.deallocate(oldPtr, oldSize);
166
167 return newPointer;
168 }
169 else
170 {
171 if (oldPtr)
172 alloc.deallocate(oldPtr, oldSize);
173
174 return alloc.allocate(newSize, NULLPTR);
175 }
176 }
177
178 /// \brief Allocates a block of memory with cleanup
179 /// \tparam T class or type
180 /// \tparam T_Align16 boolean that determines whether allocations should be aligned on a 16-byte boundary
181 /// \details If T_Align16 is true, then AllocatorWithCleanup calls AlignedAllocate()
182 /// for memory allocations. If T_Align16 is false, then AllocatorWithCleanup() calls
183 /// UnalignedAllocate() for memory allocations.
184 /// \details Template parameter T_Align16 is effectively controlled by cryptlib.h and mirrors
185 /// CRYPTOPP_BOOL_ALIGN16. CRYPTOPP_BOOL_ALIGN16 is often used as the template parameter.
186 template <class T, bool T_Align16 = false>
187 class AllocatorWithCleanup : public AllocatorBase<T>
188 {
189 public:
190 CRYPTOPP_INHERIT_ALLOCATOR_TYPES
191
192 /// \brief Allocates a block of memory
193 /// \param ptr the size of the allocation
194 /// \param size the size of the allocation, in elements
195 /// \return a memory block
196 /// \throw InvalidArgument
197 /// \details allocate() first checks the size of the request. If it is non-0
198 /// and less than max_size(), then an attempt is made to fulfill the request
199 /// using either AlignedAllocate() or UnalignedAllocate(). AlignedAllocate() is
200 /// used if T_Align16 is true. UnalignedAllocate() used if T_Align16 is false.
201 /// \details This is the C++ *Placement New* operator. ptr is not used, and the
202 /// function asserts in Debug builds if ptr is non-NULL.
203 /// \sa CallNewHandler() for the methods used to recover from a failed
204 /// allocation attempt.
205 /// \note size is the count of elements, and not the number of bytes
206 pointer allocate(size_type size, const void *ptr = NULLPTR)
207 {
208 CRYPTOPP_UNUSED(ptr); CRYPTOPP_ASSERT(ptr == NULLPTR);
209 this->CheckSize(size);
210 if (size == 0)
211 return NULLPTR;
212
213 #if CRYPTOPP_BOOL_ALIGN16
214 if (T_Align16)
215 return reinterpret_cast<pointer>(AlignedAllocate(size*sizeof(T)));
216 #endif
217
218 return reinterpret_cast<pointer>(UnalignedAllocate(size*sizeof(T)));
219 }
220
221 /// \brief Deallocates a block of memory
222 /// \param ptr the pointer for the allocation
223 /// \param size the size of the allocation, in elements
224 /// \details Internally, SecureWipeArray() is called before deallocating the
225 /// memory. Once the memory block is wiped or zeroized, AlignedDeallocate()
226 /// or UnalignedDeallocate() is called.
227 /// \details AlignedDeallocate() is used if T_Align16 is true.
228 /// UnalignedDeallocate() used if T_Align16 is false.
229 void deallocate(void *ptr, size_type size)
230 {
231 // Avoid assert on pointer in deallocate. SecBlock regularly uses NULL
232 // pointers rather returning non-NULL 0-sized pointers.
233 if (ptr)
234 {
235 SecureWipeArray(reinterpret_cast<pointer>(ptr), size);
236
237 #if CRYPTOPP_BOOL_ALIGN16
238 if (T_Align16)
239 return AlignedDeallocate(ptr);
240 #endif
241
242 UnalignedDeallocate(ptr);
243 }
244 }
245
246 /// \brief Reallocates a block of memory
247 /// \param oldPtr the previous allocation
248 /// \param oldSize the size of the previous allocation
249 /// \param newSize the new, requested size
250 /// \param preserve flag that indicates if the old allocation should be preserved
251 /// \return pointer to the new memory block
252 /// \details Internally, reallocate() calls StandardReallocate().
253 /// \details If preserve is true, then index 0 is used to begin copying the
254 /// old memory block to the new one. If the block grows, then the old array
255 /// is copied in its entirety. If the block shrinks, then only newSize
256 /// elements are copied from the old block to the new one.
257 /// \note oldSize and newSize are the count of elements, and not the
258 /// number of bytes.
259 pointer reallocate(T *oldPtr, size_type oldSize, size_type newSize, bool preserve)
260 {
261 CRYPTOPP_ASSERT((oldPtr && oldSize) || !(oldPtr || oldSize));
262 return StandardReallocate(*this, oldPtr, oldSize, newSize, preserve);
263 }
264
265 /// \brief Template class member Rebind
266 /// \tparam V bound class or type
267 /// \details Rebind allows a container class to allocate a different type of object
268 /// to store elements. For example, a std::list will allocate std::list_node to
269 /// store elements in the list.
270 /// \details VS.NET STL enforces the policy of "All STL-compliant allocators
271 /// have to provide a template class member called rebind".
272 template <class V> struct rebind { typedef AllocatorWithCleanup<V, T_Align16> other; };
273 #if _MSC_VER >= 1500
274 AllocatorWithCleanup() {}
275 template <class V, bool A> AllocatorWithCleanup(const AllocatorWithCleanup<V, A> &) {}
276 #endif
277 };
278
279 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<byte>;
280 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word16>;
281 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word32>;
282 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word64>;
283 #if defined(CRYPTOPP_WORD128_AVAILABLE)
284 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word128, true>; // for Integer
285 #endif
286 #if CRYPTOPP_BOOL_X86
287 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word, true>; // for Integer
288 #endif
289
290 /// \brief NULL allocator
291 /// \tparam T class or type
292 /// \details A NullAllocator is useful for fixed-size, stack based allocations
293 /// (i.e., static arrays used by FixedSizeAllocatorWithCleanup).
294 /// \details A NullAllocator always returns 0 for max_size(), and always returns
295 /// NULL for allocation requests. Though the allocator does not allocate at
296 /// runtime, it does perform a secure wipe or zeroization during cleanup.
297 template <class T>
298 class NullAllocator : public AllocatorBase<T>
299 {
300 public:
301 //LCOV_EXCL_START
302 CRYPTOPP_INHERIT_ALLOCATOR_TYPES
303
304 // TODO: should this return NULL or throw bad_alloc? Non-Windows C++ standard
305 // libraries always throw. And late mode Windows throws. Early model Windows
306 // (circa VC++ 6.0) returned NULL.
307 pointer allocate(size_type n, const void* unused = NULLPTR)
308 {
309 CRYPTOPP_UNUSED(n); CRYPTOPP_UNUSED(unused);
310 CRYPTOPP_ASSERT(false); return NULLPTR;
311 }
312
313 void deallocate(void *p, size_type n)
314 {
315 CRYPTOPP_UNUSED(p); CRYPTOPP_UNUSED(n);
316 CRYPTOPP_ASSERT(false);
317 }
318
319 CRYPTOPP_CONSTEXPR size_type max_size() const {return 0;}
320 //LCOV_EXCL_STOP
321 };
322
323 /// \brief Static secure memory block with cleanup
324 /// \tparam T class or type
325 /// \tparam S fixed-size of the stack-based memory block, in elements
326 /// \tparam T_Align16 boolean that determines whether allocations should
327 /// be aligned on a 16-byte boundary
328 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
329 /// based allocation at compile time. The class can grow its memory
330 /// block at runtime if a suitable allocator is available. If size
331 /// grows beyond S and a suitable allocator is available, then the
332 /// statically allocated array is obsoleted.
333 /// \note This allocator can't be used with standard collections because
334 /// they require that all objects of the same allocator type are equivalent.
335 template <class T, size_t S, class A = NullAllocator<T>, bool T_Align16 = false>
336 class FixedSizeAllocatorWithCleanup : public AllocatorBase<T>
337 {
338 // The body of FixedSizeAllocatorWithCleanup is provided in the two
339 // partial specializations that follow. The two specialiations
340 // pivot on the boolean template parameter T_Align16. AIX, Solaris,
341 // IBM XLC and SunCC receive a little extra help. We managed to
342 // clear most of the warnings.
343 };
344
345 /// \brief Static secure memory block with cleanup
346 /// \tparam T class or type
347 /// \tparam S fixed-size of the stack-based memory block, in elements
348 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
349 /// based allocation at compile time. The class can grow its memory
350 /// block at runtime if a suitable allocator is available. If size
351 /// grows beyond S and a suitable allocator is available, then the
352 /// statically allocated array is obsoleted.
353 /// \note This allocator can't be used with standard collections because
354 /// they require that all objects of the same allocator type are equivalent.
355 template <class T, size_t S, class A>
356 class FixedSizeAllocatorWithCleanup<T, S, A, true> : public AllocatorBase<T>
357 {
358 public:
359 CRYPTOPP_INHERIT_ALLOCATOR_TYPES
360
361 /// \brief Constructs a FixedSizeAllocatorWithCleanup
362 FixedSizeAllocatorWithCleanup() : m_allocated(false) {}
363
364 /// \brief Allocates a block of memory
365 /// \param size the count elements in the memory block
366 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-based
367 /// allocation at compile time. If size is less than or equal to
368 /// <tt>S</tt>, then a pointer to the static array is returned.
369 /// \details The class can grow its memory block at runtime if a suitable
370 /// allocator is available. If size grows beyond S and a suitable
371 /// allocator is available, then the statically allocated array is
372 /// obsoleted. If a suitable allocator is not available, as with a
373 /// NullAllocator, then the function returns NULL and a runtime error
374 /// eventually occurs.
375 /// \sa reallocate(), SecBlockWithHint
376 pointer allocate(size_type size)
377 {
378 CRYPTOPP_ASSERT(IsAlignedOn(m_array, 8));
379
380 if (size <= S && !m_allocated)
381 {
382 m_allocated = true;
383 return GetAlignedArray();
384 }
385 else
386 return m_fallbackAllocator.allocate(size);
387 }
388
389 /// \brief Allocates a block of memory
390 /// \param size the count elements in the memory block
391 /// \param hint an unused hint
392 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
393 /// based allocation at compile time. If size is less than or equal to
394 /// S, then a pointer to the static array is returned.
395 /// \details The class can grow its memory block at runtime if a suitable
396 /// allocator is available. If size grows beyond S and a suitable
397 /// allocator is available, then the statically allocated array is
398 /// obsoleted. If a suitable allocator is not available, as with a
399 /// NullAllocator, then the function returns NULL and a runtime error
400 /// eventually occurs.
401 /// \sa reallocate(), SecBlockWithHint
402 pointer allocate(size_type size, const void *hint)
403 {
404 if (size <= S && !m_allocated)
405 {
406 m_allocated = true;
407 return GetAlignedArray();
408 }
409 else
410 return m_fallbackAllocator.allocate(size, hint);
411 }
412
413 /// \brief Deallocates a block of memory
414 /// \param ptr a pointer to the memory block to deallocate
415 /// \param size the count elements in the memory block
416 /// \details The memory block is wiped or zeroized before deallocation.
417 /// If the statically allocated memory block is active, then no
418 /// additional actions are taken after the wipe.
419 /// \details If a dynamic memory block is active, then the pointer and
420 /// size are passed to the allocator for deallocation.
421 void deallocate(void *ptr, size_type size)
422 {
423 // Avoid assert on pointer in deallocate. SecBlock regularly uses NULL
424 // pointers rather returning non-NULL 0-sized pointers.
425 if (ptr == GetAlignedArray())
426 {
427 // If the m_allocated assert fires then the bit twiddling for
428 // GetAlignedArray() is probably incorrect for the platform.
429 // Be sure to check CRYPTOPP_ALIGN_DATA(8). The platform may
430 // not have a way to declaritively align data to 8.
431 CRYPTOPP_ASSERT(size <= S);
432 CRYPTOPP_ASSERT(m_allocated);
433 m_allocated = false;
434 SecureWipeArray(reinterpret_cast<pointer>(ptr), size);
435 }
436 else
437 {
438 if (ptr)
439 m_fallbackAllocator.deallocate(ptr, size);
440 }
441 }
442
443 /// \brief Reallocates a block of memory
444 /// \param oldPtr the previous allocation
445 /// \param oldSize the size of the previous allocation
446 /// \param newSize the new, requested size
447 /// \param preserve flag that indicates if the old allocation should
448 /// be preserved
449 /// \return pointer to the new memory block
450 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
451 /// based allocation at compile time. If size is less than or equal to
452 /// S, then a pointer to the static array is returned.
453 /// \details The class can grow its memory block at runtime if a suitable
454 /// allocator is available. If size grows beyond S and a suitable
455 /// allocator is available, then the statically allocated array is
456 /// obsoleted. If a suitable allocator is not available, as with a
457 /// NullAllocator, then the function returns NULL and a runtime error
458 /// eventually occurs.
459 /// \note size is the count of elements, and not the number of bytes.
460 /// \sa reallocate(), SecBlockWithHint
461 pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
462 {
463 if (oldPtr == GetAlignedArray() && newSize <= S)
464 {
465 CRYPTOPP_ASSERT(oldSize <= S);
466 if (oldSize > newSize)
467 SecureWipeArray(oldPtr+newSize, oldSize-newSize);
468 return oldPtr;
469 }
470
471 pointer newPointer = allocate(newSize, NULLPTR);
472 if (preserve && newSize)
473 {
474 const size_type copySize = STDMIN(oldSize, newSize);
475 if (newPointer && oldPtr) // GCC analyzer warning
476 memcpy_s(newPointer, sizeof(T)*newSize, oldPtr, sizeof(T)*copySize);
477 }
478 deallocate(oldPtr, oldSize);
479 return newPointer;
480 }
481
482 CRYPTOPP_CONSTEXPR size_type max_size() const
483 {
484 return STDMAX(m_fallbackAllocator.max_size(), S);
485 }
486
487 private:
488
489 #if defined(CRYPTOPP_BOOL_ALIGN16) && (defined(_M_X64) || defined(__x86_64__))
490 // Before we can add additional platforms we need to check the
491 // linker documentation for alignment behavior for stack variables.
492 // CRYPTOPP_ALIGN_DATA(16) is known OK on Linux, OS X, Solaris.
493 // Also see http://stackoverflow.com/a/1468656/608639.
494 T* GetAlignedArray() {
495 CRYPTOPP_ASSERT(IsAlignedOn(m_array, 16));
496 return m_array;
497 }
498 CRYPTOPP_ALIGN_DATA(16) T m_array[S];
499
500 #elif defined(CRYPTOPP_BOOL_ALIGN16)
501
502 // There be demons here... We cannot use CRYPTOPP_ALIGN_DATA(16)
503 // because linkers on 32-bit machines (and some 64-bit machines)
504 // align the stack to 8-bytes or less by default, not 16-bytes as
505 // requested. Additionally, the AIX linker seems to use 4-bytes
506 // by default. However, all linkers tested appear to honor
507 // CRYPTOPP_ALIGN_DATA(8). Also see
508 // http://stackoverflow.com/a/1468656/608639.
509 //
510 // The 16-byte alignment is achieved by padding the requested
511 // size with extra elements so we have at least 16-bytes of slack
512 // to work with. Then the pointer is moved down to achieve a
513 // 16-byte alignment (stacks grow down).
514 //
515 // The additional 16-bytes introduces a small secondary issue.
516 // The secondary issue is, a large T results in 0 = 8/sizeof(T).
517 // The library is OK but users may hit it. So we need to guard
518 // for a large T, and that is what PAD achieves.
519 T* GetAlignedArray() {
520 T* p_array = reinterpret_cast<T*>(static_cast<void*>((reinterpret_cast<byte*>(m_array)) + (0-reinterpret_cast<size_t>(m_array))%16));
521 // Verify the 16-byte alignment
522 CRYPTOPP_ASSERT(IsAlignedOn(p_array, 16));
523 // Verify allocated array with pad is large enough.
524 CRYPTOPP_ASSERT(p_array+S <= m_array+(S+PAD));
525 return p_array;
526 }
527
528 # if defined(_AIX)
529 // PAD is elements, not bytes, and rounded up to ensure no overflow.
530 enum { Q = sizeof(T), PAD = (Q >= 16) ? 1 : (Q >= 8) ? 2 : (Q >= 4) ? 4 : (Q >= 2) ? 8 : 16 };
531 CRYPTOPP_ALIGN_DATA(8) T m_array[S+PAD];
532 # else
533 // PAD is elements, not bytes, and rounded up to ensure no overflow.
534 enum { Q = sizeof(T), PAD = (Q >= 8) ? 1 : (Q >= 4) ? 2 : (Q >= 2) ? 4 : 8 };
535 CRYPTOPP_ALIGN_DATA(8) T m_array[S+PAD];
536 # endif
537
538 #else
539
540 // CRYPTOPP_BOOL_ALIGN16 is 0. Use natural alignment of T.
541 T* GetAlignedArray() {return m_array;}
542 CRYPTOPP_ALIGN_DATA(4) T m_array[S];
543
544 #endif
545
546 A m_fallbackAllocator;
547 bool m_allocated;
548 };
549
550 /// \brief Static secure memory block with cleanup
551 /// \tparam T class or type
552 /// \tparam S fixed-size of the stack-based memory block, in elements
553 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
554 /// based allocation at compile time. The class can grow its memory
555 /// block at runtime if a suitable allocator is available. If size
556 /// grows beyond S and a suitable allocator is available, then the
557 /// statically allocated array is obsoleted.
558 /// \note This allocator can't be used with standard collections because
559 /// they require that all objects of the same allocator type are equivalent.
560 template <class T, size_t S, class A>
561 class FixedSizeAllocatorWithCleanup<T, S, A, false> : public AllocatorBase<T>
562 {
563 public:
564 CRYPTOPP_INHERIT_ALLOCATOR_TYPES
565
566 /// \brief Constructs a FixedSizeAllocatorWithCleanup
567 FixedSizeAllocatorWithCleanup() : m_allocated(false) {}
568
569 /// \brief Allocates a block of memory
570 /// \param size the count elements in the memory block
571 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-based
572 /// allocation at compile time. If size is less than or equal to
573 /// <tt>S</tt>, then a pointer to the static array is returned.
574 /// \details The class can grow its memory block at runtime if a suitable
575 /// allocator is available. If size grows beyond S and a suitable
576 /// allocator is available, then the statically allocated array is
577 /// obsoleted. If a suitable allocator is not available, as with a
578 /// NullAllocator, then the function returns NULL and a runtime error
579 /// eventually occurs.
580 /// \sa reallocate(), SecBlockWithHint
581 pointer allocate(size_type size)
582 {
583 CRYPTOPP_ASSERT(IsAlignedOn(m_array, 8));
584
585 if (size <= S && !m_allocated)
586 {
587 m_allocated = true;
588 return GetAlignedArray();
589 }
590 else
591 return m_fallbackAllocator.allocate(size);
592 }
593
594 /// \brief Allocates a block of memory
595 /// \param size the count elements in the memory block
596 /// \param hint an unused hint
597 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
598 /// based allocation at compile time. If size is less than or equal to
599 /// S, then a pointer to the static array is returned.
600 /// \details The class can grow its memory block at runtime if a suitable
601 /// allocator is available. If size grows beyond S and a suitable
602 /// allocator is available, then the statically allocated array is
603 /// obsoleted. If a suitable allocator is not available, as with a
604 /// NullAllocator, then the function returns NULL and a runtime error
605 /// eventually occurs.
606 /// \sa reallocate(), SecBlockWithHint
607 pointer allocate(size_type size, const void *hint)
608 {
609 if (size <= S && !m_allocated)
610 {
611 m_allocated = true;
612 return GetAlignedArray();
613 }
614 else
615 return m_fallbackAllocator.allocate(size, hint);
616 }
617
618 /// \brief Deallocates a block of memory
619 /// \param ptr a pointer to the memory block to deallocate
620 /// \param size the count elements in the memory block
621 /// \details The memory block is wiped or zeroized before deallocation.
622 /// If the statically allocated memory block is active, then no
623 /// additional actions are taken after the wipe.
624 /// \details If a dynamic memory block is active, then the pointer and
625 /// size are passed to the allocator for deallocation.
626 void deallocate(void *ptr, size_type size)
627 {
628 // Avoid assert on pointer in deallocate. SecBlock regularly uses NULL
629 // pointers rather returning non-NULL 0-sized pointers.
630 if (ptr == GetAlignedArray())
631 {
632 // If the m_allocated assert fires then
633 // something overwrote the flag.
634 CRYPTOPP_ASSERT(size <= S);
635 CRYPTOPP_ASSERT(m_allocated);
636 m_allocated = false;
637 SecureWipeArray((pointer)ptr, size);
638 }
639 else
640 {
641 if (ptr)
642 m_fallbackAllocator.deallocate(ptr, size);
643 m_allocated = false;
644 }
645 }
646
647 /// \brief Reallocates a block of memory
648 /// \param oldPtr the previous allocation
649 /// \param oldSize the size of the previous allocation
650 /// \param newSize the new, requested size
651 /// \param preserve flag that indicates if the old allocation should
652 /// be preserved
653 /// \return pointer to the new memory block
654 /// \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
655 /// based allocation at compile time. If size is less than or equal to
656 /// S, then a pointer to the static array is returned.
657 /// \details The class can grow its memory block at runtime if a suitable
658 /// allocator is available. If size grows beyond S and a suitable
659 /// allocator is available, then the statically allocated array is
660 /// obsoleted. If a suitable allocator is not available, as with a
661 /// NullAllocator, then the function returns NULL and a runtime error
662 /// eventually occurs.
663 /// \note size is the count of elements, and not the number of bytes.
664 /// \sa reallocate(), SecBlockWithHint
665 pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
666 {
667 if (oldPtr == GetAlignedArray() && newSize <= S)
668 {
669 CRYPTOPP_ASSERT(oldSize <= S);
670 if (oldSize > newSize)
671 SecureWipeArray(oldPtr+newSize, oldSize-newSize);
672 return oldPtr;
673 }
674
675 pointer newPointer = allocate(newSize, NULLPTR);
676 if (preserve && newSize)
677 {
678 const size_type copySize = STDMIN(oldSize, newSize);
679 if (newPointer && oldPtr) // GCC analyzer warning
680 memcpy_s(newPointer, sizeof(T)*newSize, oldPtr, sizeof(T)*copySize);
681 }
682 deallocate(oldPtr, oldSize);
683 return newPointer;
684 }
685
686 CRYPTOPP_CONSTEXPR size_type max_size() const
687 {
688 return STDMAX(m_fallbackAllocator.max_size(), S);
689 }
690
691 private:
692
693 // The 8-byte alignments follows convention of Linux and Windows.
694 // Linux and Windows receives most testing. Duplicate it here for
695 // other platforms like AIX and Solaris. AIX and Solaris often use
696 // alignments smaller than expected. In fact AIX caught us by
697 // surprise with word16 and word32.
698 T* GetAlignedArray() {return m_array;}
699 CRYPTOPP_ALIGN_DATA(8) T m_array[S];
700
701 A m_fallbackAllocator;
702 bool m_allocated;
703 };
704
705 /// \brief Secure memory block with allocator and cleanup
706 /// \tparam T a class or type
707 /// \tparam A AllocatorWithCleanup derived class for allocation and cleanup
708 template <class T, class A = AllocatorWithCleanup<T> >
709 class SecBlock
710 {
711 public:
712 typedef typename A::value_type value_type;
713 typedef typename A::pointer iterator;
714 typedef typename A::const_pointer const_iterator;
715 typedef typename A::size_type size_type;
716
717 /// \brief Returns the maximum number of elements the block can hold
718 /// \details <tt>ELEMS_MAX</tt> is the maximum number of elements the
719 /// <tt>SecBlock</tt> can hold. The value of <tt>ELEMS_MAX</tt> is
720 /// <tt>SIZE_MAX/sizeof(T)</tt>. <tt>std::numeric_limits</tt> was avoided
721 /// due to lack of <tt>constexpr</tt>-ness in C++03 and below.
722 /// \note In C++03 and below <tt>ELEMS_MAX</tt> is a static data member of type
723 /// <tt>size_type</tt>. In C++11 and above <tt>ELEMS_MAX</tt> is an <tt>enum</tt>
724 /// inheriting from <tt>size_type</tt>. In both cases <tt>ELEMS_MAX</tt> can be
725 /// used before objects are fully constructed, and it does not suffer the
726 /// limitations of class methods like <tt>max_size</tt>.
727 /// \sa <A HREF="http://github.com/weidai11/cryptopp/issues/346">Issue 346/CVE-2016-9939</A>
728 /// \since Crypto++ 6.0
729 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
730 static const size_type ELEMS_MAX = ...;
731 #elif defined(_MSC_VER) && (_MSC_VER <= 1400)
732 static const size_type ELEMS_MAX = (~(size_type)0)/sizeof(T);
733 #elif defined(CRYPTOPP_CXX11_STRONG_ENUM)
734 enum : size_type {ELEMS_MAX = A::ELEMS_MAX};
735 #else
736 static const size_type ELEMS_MAX = SIZE_MAX/sizeof(T);
737 #endif
738
739 /// \brief Construct a SecBlock with space for size elements.
740 /// \param size the size of the allocation, in elements
741 /// \throw std::bad_alloc
742 /// \details The elements are not initialized.
743 /// \note size is the count of elements, and not the number of bytes
744 explicit SecBlock(size_type size=0)
745 : m_mark(ELEMS_MAX), m_size(size), m_ptr(m_alloc.allocate(size, NULLPTR)) { }
746
747 /// \brief Copy construct a SecBlock from another SecBlock
748 /// \param t the other SecBlock
749 /// \throw std::bad_alloc
750 SecBlock(const SecBlock<T, A> &t)
751 : m_mark(t.m_mark), m_size(t.m_size), m_ptr(m_alloc.allocate(t.m_size, NULLPTR)) {
752 CRYPTOPP_ASSERT((!t.m_ptr && !m_size) || (t.m_ptr && m_size));
753 if (m_ptr && t.m_ptr)
754 memcpy_s(m_ptr, m_size*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
755 }
756
757 /// \brief Construct a SecBlock from an array of elements.
758 /// \param ptr a pointer to an array of T
759 /// \param len the number of elements in the memory block
760 /// \throw std::bad_alloc
761 /// \details If <tt>ptr!=NULL</tt> and <tt>len!=0</tt>, then the block is initialized from the pointer
762 /// <tt>ptr</tt>. If <tt>ptr==NULL</tt> and <tt>len!=0</tt>, then the block is initialized to 0.
763 /// Otherwise, the block is empty and not initialized.
764 /// \note size is the count of elements, and not the number of bytes
765 SecBlock(const T *ptr, size_type len)
766 : m_mark(ELEMS_MAX), m_size(len), m_ptr(m_alloc.allocate(len, NULLPTR)) {
767 CRYPTOPP_ASSERT((!m_ptr && !m_size) || (m_ptr && m_size));
768 if (m_ptr && ptr)
769 memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));
770 else if (m_ptr && m_size)
771 memset(m_ptr, 0, m_size*sizeof(T));
772 }
773
774 ~SecBlock()
775 {m_alloc.deallocate(m_ptr, STDMIN(m_size, m_mark));}
776
777 #ifdef __BORLANDC__
778 /// \brief Cast operator
779 /// \return block pointer cast to non-const <tt>T *</tt>
780 operator T *() const
781 {return (T*)m_ptr;}
782 #else
783 /// \brief Cast operator
784 /// \return block pointer cast to <tt>const void *</tt>
785 operator const void *() const
786 {return m_ptr;}
787
788 /// \brief Cast operator
789 /// \return block pointer cast to non-const <tt>void *</tt>
790 operator void *()
791 {return m_ptr;}
792
793 /// \brief Cast operator
794 /// \return block pointer cast to <tt>const T *</tt>
795 operator const T *() const
796 {return m_ptr;}
797
798 /// \brief Cast operator
799 /// \return block pointer cast to non-const <tt>T *</tt>
800 operator T *()
801 {return m_ptr;}
802 #endif
803
804 /// \brief Provides an iterator pointing to the first element in the memory block
805 /// \return iterator pointing to the first element in the memory block
806 iterator begin()
807 {return m_ptr;}
808 /// \brief Provides a constant iterator pointing to the first element in the memory block
809 /// \return constant iterator pointing to the first element in the memory block
810 const_iterator begin() const
811 {return m_ptr;}
812 /// \brief Provides an iterator pointing beyond the last element in the memory block
813 /// \return iterator pointing beyond the last element in the memory block
814 iterator end()
815 {return m_ptr+m_size;}
816 /// \brief Provides a constant iterator pointing beyond the last element in the memory block
817 /// \return constant iterator pointing beyond the last element in the memory block
818 const_iterator end() const
819 {return m_ptr+m_size;}
820
821 /// \brief Provides a pointer to the first element in the memory block
822 /// \return pointer to the first element in the memory block
823 typename A::pointer data() {return m_ptr;}
824 /// \brief Provides a pointer to the first element in the memory block
825 /// \return constant pointer to the first element in the memory block
826 typename A::const_pointer data() const {return m_ptr;}
827
828 /// \brief Provides the count of elements in the SecBlock
829 /// \return number of elements in the memory block
830 /// \note the return value is the count of elements, and not the number of bytes
831 size_type size() const {return m_size;}
832 /// \brief Determines if the SecBlock is empty
833 /// \return true if number of elements in the memory block is 0, false otherwise
834 bool empty() const {return m_size == 0;}
835
836 /// \brief Provides a byte pointer to the first element in the memory block
837 /// \return byte pointer to the first element in the memory block
838 byte * BytePtr() {return (byte *)m_ptr;}
839 /// \brief Return a byte pointer to the first element in the memory block
840 /// \return constant byte pointer to the first element in the memory block
841 const byte * BytePtr() const {return (const byte *)m_ptr;}
842 /// \brief Provides the number of bytes in the SecBlock
843 /// \return the number of bytes in the memory block
844 /// \note the return value is the number of bytes, and not count of elements.
845 size_type SizeInBytes() const {return m_size*sizeof(T);}
846
847 /// \brief Sets the number of elements to zeroize
848 /// \param count the number of elements
849 /// \details SetMark is a remediation for Issue 346/CVE-2016-9939 while
850 /// preserving the streaming interface. The <tt>count</tt> controls the number of
851 /// elements zeroized, which can be less than <tt>size</tt> or 0.
852 /// \details An internal variable, <tt>m_mark</tt>, is initialized to the maximum number
853 /// of elements. The maximum number of elements is <tt>ELEMS_MAX</tt>. Deallocation
854 /// triggers a zeroization, and the number of elements zeroized is
855 /// <tt>STDMIN(m_size, m_mark)</tt>. After zeroization, the memory is returned to the
856 /// system.
857 /// \details The ASN.1 decoder uses SetMark() to set the element count to 0
858 /// before throwing an exception. In this case, the attacker provides a large
859 /// BER encoded length (say 64MB) but only a small number of content octets
860 /// (say 16). If the allocator zeroized all 64MB, then a transient DoS could
861 /// occur as CPU cycles are spent zeroizing unintialized memory.
862 /// \details Generally speaking, any operation which changes the size of the SecBlock
863 /// results in the mark being reset to <tt>ELEMS_MAX</tt>. In particular, if Assign(),
864 /// New(), Grow(), CleanNew(), CleanGrow() are called, then the count is reset to
865 /// <tt>ELEMS_MAX</tt>. The list is not exhaustive.
866 /// \since Crypto++ 6.0
867 /// \sa <A HREF="http://github.com/weidai11/cryptopp/issues/346">Issue 346/CVE-2016-9939</A>
868 void SetMark(size_t count) {m_mark = count;}
869
870 /// \brief Set contents and size from an array
871 /// \param ptr a pointer to an array of T
872 /// \param len the number of elements in the memory block
873 /// \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
874 /// Assign() resets the element count after the previous block is zeroized.
875 void Assign(const T *ptr, size_type len)
876 {
877 New(len);
878 if (m_ptr && ptr) // GCC analyzer warning
879 memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));
880 m_mark = ELEMS_MAX;
881 }
882
883 /// \brief Set contents from a value
884 /// \param count the number of values to copy
885 /// \param value the value, repeated count times
886 /// \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
887 /// Assign() resets the element count after the previous block is zeroized.
888 void Assign(size_type count, T value)
889 {
890 New(count);
891 for (size_t i=0; i<count; ++i)
892 m_ptr[i] = value;
893
894 m_mark = ELEMS_MAX;
895 }
896
897 /// \brief Copy contents from another SecBlock
898 /// \param t the other SecBlock
899 /// \details Assign checks for self assignment.
900 /// \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
901 /// If an assignment occurs, then Assign() resets the element count after the previous block
902 /// is zeroized.
903 void Assign(const SecBlock<T, A> &t)
904 {
905 if (this != &t)
906 {
907 New(t.m_size);
908 if (m_ptr && t.m_ptr) // GCC analyzer warning
909 memcpy_s(m_ptr, m_size*sizeof(T), t, t.m_size*sizeof(T));
910 }
911 m_mark = ELEMS_MAX;
912 }
913
914 /// \brief Assign contents from another SecBlock
915 /// \param t the other SecBlock
916 /// \details Internally, operator=() calls Assign().
917 /// \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
918 /// If an assignment occurs, then Assign() resets the element count after the previous block
919 /// is zeroized.
920 SecBlock<T, A>& operator=(const SecBlock<T, A> &t)
921 {
922 // Assign guards for self-assignment
923 Assign(t);
924 return *this;
925 }
926
927 /// \brief Append contents from another SecBlock
928 /// \param t the other SecBlock
929 /// \details Internally, this SecBlock calls Grow and then appends t.
930 SecBlock<T, A>& operator+=(const SecBlock<T, A> &t)
931 {
932 CRYPTOPP_ASSERT((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
933 if (t.m_size)
934 {
935 const size_type oldSize = m_size;
936 if (this != &t) // s += t
937 {
938 Grow(m_size+t.m_size);
939 if (m_ptr && t.m_ptr) // GCC analyzer warning
940 memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
941 }
942 else // t += t
943 {
944 Grow(m_size*2);
945 if (m_ptr && t.m_ptr) // GCC analyzer warning
946 memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), m_ptr, oldSize*sizeof(T));
947 }
948 }
949 m_mark = ELEMS_MAX;
950 return *this;
951 }
952
953 /// \brief Construct a SecBlock from this and another SecBlock
954 /// \param t the other SecBlock
955 /// \return a newly constructed SecBlock that is a conacentation of this and t
956 /// \details Internally, a new SecBlock is created from this and a concatenation of t.
957 SecBlock<T, A> operator+(const SecBlock<T, A> &t)
958 {
959 CRYPTOPP_ASSERT((!m_ptr && !m_size) || (m_ptr && m_size));
960 CRYPTOPP_ASSERT((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
961 if(!t.m_size) return SecBlock(*this);
962
963 SecBlock<T, A> result(m_size+t.m_size);
964 if (m_size)
965 memcpy_s(result.m_ptr, result.m_size*sizeof(T), m_ptr, m_size*sizeof(T));
966 if (result.m_ptr && t.m_ptr) // GCC analyzer warning
967 memcpy_s(result.m_ptr+m_size, (result.m_size-m_size)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
968 return result;
969 }
970
971 /// \brief Bitwise compare two SecBlocks
972 /// \param t the other SecBlock
973 /// \return true if the size and bits are equal, false otherwise
974 /// \details Uses a constant time compare if the arrays are equal size. The constant time
975 /// compare is VerifyBufsEqual() found in misc.h.
976 /// \sa operator!=()
977 bool operator==(const SecBlock<T, A> &t) const
978 {
979 return m_size == t.m_size && VerifyBufsEqual(
980 reinterpret_cast<const byte*>(m_ptr),
981 reinterpret_cast<const byte*>(t.m_ptr), m_size*sizeof(T));
982 }
983
984 /// \brief Bitwise compare two SecBlocks
985 /// \param t the other SecBlock
986 /// \return true if the size and bits are equal, false otherwise
987 /// \details Uses a constant time compare if the arrays are equal size. The constant time
988 /// compare is VerifyBufsEqual() found in misc.h.
989 /// \details Internally, operator!=() returns the inverse of operator==().
990 /// \sa operator==()
991 bool operator!=(const SecBlock<T, A> &t) const
992 {
993 return !operator==(t);
994 }
995
996 /// \brief Change size without preserving contents
997 /// \param newSize the new size of the memory block
998 /// \details Old content is not preserved. If the memory block is reduced in size,
999 /// then the reclaimed memory is set to 0. If the memory block grows in size, then
1000 /// the new memory is not initialized. New() resets the element count after the
1001 /// previous block is zeroized.
1002 /// \details Internally, this SecBlock calls reallocate().
1003 /// \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
1004 void New(size_type newSize)
1005 {
1006 m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, false);
1007 m_size = newSize;
1008 m_mark = ELEMS_MAX;
1009 }
1010
1011 /// \brief Change size without preserving contents
1012 /// \param newSize the new size of the memory block
1013 /// \details Old content is not preserved. If the memory block is reduced in size,
1014 /// then the reclaimed content is set to 0. If the memory block grows in size, then
1015 /// the new memory is initialized to 0. CleanNew() resets the element count after the
1016 /// previous block is zeroized.
1017 /// \details Internally, this SecBlock calls New().
1018 /// \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
1019 void CleanNew(size_type newSize)
1020 {
1021 New(newSize);
1022 if (m_ptr) {memset_z(m_ptr, 0, m_size*sizeof(T));}
1023 m_mark = ELEMS_MAX;
1024 }
1025
1026 /// \brief Change size and preserve contents
1027 /// \param newSize the new size of the memory block
1028 /// \details Old content is preserved. New content is not initialized.
1029 /// \details Internally, this SecBlock calls reallocate() when size must increase. If the
1030 /// size does not increase, then Grow() does not take action. If the size must
1031 /// change, then use resize(). Grow() resets the element count after the
1032 /// previous block is zeroized.
1033 /// \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
1034 void Grow(size_type newSize)
1035 {
1036 if (newSize > m_size)
1037 {
1038 m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
1039 m_size = newSize;
1040 }
1041 m_mark = ELEMS_MAX;
1042 }
1043
1044 /// \brief Change size and preserve contents
1045 /// \param newSize the new size of the memory block
1046 /// \details Old content is preserved. New content is initialized to 0.
1047 /// \details Internally, this SecBlock calls reallocate() when size must increase. If the
1048 /// size does not increase, then CleanGrow() does not take action. If the size must
1049 /// change, then use resize(). CleanGrow() resets the element count after the
1050 /// previous block is zeroized.
1051 /// \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
1052 void CleanGrow(size_type newSize)
1053 {
1054 if (newSize > m_size)
1055 {
1056 m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
1057 memset_z(m_ptr+m_size, 0, (newSize-m_size)*sizeof(T));
1058 m_size = newSize;
1059 }
1060 m_mark = ELEMS_MAX;
1061 }
1062
1063 /// \brief Change size and preserve contents
1064 /// \param newSize the new size of the memory block
1065 /// \details Old content is preserved. If the memory block grows in size, then
1066 /// new memory is not initialized. resize() resets the element count after
1067 /// the previous block is zeroized.
1068 /// \details Internally, this SecBlock calls reallocate().
1069 /// \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
1070 void resize(size_type newSize)
1071 {
1072 m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
1073 m_size = newSize;
1074 m_mark = ELEMS_MAX;
1075 }
1076
1077 /// \brief Swap contents with another SecBlock
1078 /// \param b the other SecBlock
1079 /// \details Internally, std::swap() is called on m_alloc, m_size and m_ptr.
1080 void swap(SecBlock<T, A> &b)
1081 {
1082 // Swap must occur on the allocator in case its FixedSize that spilled into the heap.
1083 std::swap(m_alloc, b.m_alloc);
1084 std::swap(m_mark, b.m_mark);
1085 std::swap(m_size, b.m_size);
1086 std::swap(m_ptr, b.m_ptr);
1087 }
1088
1089 protected:
1090 A m_alloc;
1091 size_type m_mark, m_size;
1092 T *m_ptr;
1093 };
1094
1095 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
1096 /// \brief \ref SecBlock "SecBlock<byte>" typedef.
1097 class SecByteBlock : public SecBlock<byte> {};
1098 /// \brief \ref SecBlock "SecBlock<word>" typedef.
1099 class SecWordBlock : public SecBlock<word> {};
1100 /// \brief SecBlock using \ref AllocatorWithCleanup "AllocatorWithCleanup<byte, true>" typedef
1101 class AlignedSecByteBlock : public SecBlock<byte, AllocatorWithCleanup<byte, true> > {};
1102 #else
1103 typedef SecBlock<byte> SecByteBlock;
1104 typedef SecBlock<word> SecWordBlock;
1105 typedef SecBlock<byte, AllocatorWithCleanup<byte, true> > AlignedSecByteBlock;
1106 #endif
1107
1108 // No need for move semantics on derived class *if* the class does not add any
1109 // data members; see http://stackoverflow.com/q/31755703, and Rule of {0|3|5}.
1110
1111 /// \brief Fixed size stack-based SecBlock
1112 /// \tparam T class or type
1113 /// \tparam S fixed-size of the stack-based memory block, in elements
1114 /// \tparam A AllocatorBase derived class for allocation and cleanup
1115 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S> >
1116 class FixedSizeSecBlock : public SecBlock<T, A>
1117 {
1118 public:
1119 /// \brief Construct a FixedSizeSecBlock
1120 explicit FixedSizeSecBlock() : SecBlock<T, A>(S) {}
1121 };
1122
1123 /// \brief Fixed size stack-based SecBlock with 16-byte alignment
1124 /// \tparam T class or type
1125 /// \tparam S fixed-size of the stack-based memory block, in elements
1126 /// \tparam T_Align16 boolean that determines whether allocations should be aligned on a 16-byte boundary
1127 template <class T, unsigned int S, bool T_Align16 = true>
1128 class FixedSizeAlignedSecBlock : public FixedSizeSecBlock<T, S, FixedSizeAllocatorWithCleanup<T, S, NullAllocator<T>, T_Align16> >
1129 {
1130 };
1131
1132 /// \brief Stack-based SecBlock that grows into the heap
1133 /// \tparam T class or type
1134 /// \tparam S fixed-size of the stack-based memory block, in elements
1135 /// \tparam A AllocatorBase derived class for allocation and cleanup
1136 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S, AllocatorWithCleanup<T> > >
1137 class SecBlockWithHint : public SecBlock<T, A>
1138 {
1139 public:
1140 /// construct a SecBlockWithHint with a count of elements
1141 explicit SecBlockWithHint(size_t size) : SecBlock<T, A>(size) {}
1142 };
1143
1144 template<class T, bool A, class V, bool B>
1145 inline bool operator==(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<V, B>&) {return (true);}
1146 template<class T, bool A, class V, bool B>
1147 inline bool operator!=(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<V, B>&) {return (false);}
1148
1149 NAMESPACE_END
1150
1151 NAMESPACE_BEGIN(std)
1152
1153 /// \brief Swap two SecBlocks
1154 /// \tparam T class or type
1155 /// \tparam A AllocatorBase derived class for allocation and cleanup
1156 /// \param a the first SecBlock
1157 /// \param b the second SecBlock
1158 template <class T, class A>
1159 inline void swap(CryptoPP::SecBlock<T, A> &a, CryptoPP::SecBlock<T, A> &b)
1160 {
1161 a.swap(b);
1162 }
1163
1164 #if defined(_STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE) || (defined(_STLPORT_VERSION) && !defined(_STLP_MEMBER_TEMPLATE_CLASSES))
1165 // working for STLport 5.1.3 and MSVC 6 SP5
1166 template <class _Tp1, class _Tp2>
1167 inline CryptoPP::AllocatorWithCleanup<_Tp2>&
1168 __stl_alloc_rebind(CryptoPP::AllocatorWithCleanup<_Tp1>& __a, const _Tp2*)
1169 {
1170 return (CryptoPP::AllocatorWithCleanup<_Tp2>&)(__a);
1171 }
1172 #endif
1173
1174 NAMESPACE_END
1175
1176 #if CRYPTOPP_MSC_VERSION
1177 # pragma warning(pop)
1178 #endif
1179
1180 #endif
SecBlock::end
iterator end()
Provides an iterator pointing beyond the last element in the memory block.
Definition: secblock.h:814
InvalidArgument
An invalid argument was detected.
Definition: cryptlib.h:202
AllocatorBase::construct
void construct(V *ptr, Args &&... args)
Constructs a new V using variadic arguments.
Definition: secblock.h:91
UnalignedDeallocate
CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr)
Frees a buffer allocated with UnalignedAllocate.
Definition: allocate.cpp:100
AllocatorBase
Base class for all allocators used by SecBlock.
Definition: secblock.h:29
SecBlock::swap
void swap(SecBlock< T, A > &b)
Swap contents with another SecBlock.
Definition: secblock.h:1080
SecBlockWithHint
Stack-based SecBlock that grows into the heap.
Definition: secblock.h:1137
misc.h
Utility functions for the Crypto++ library.
FixedSizeSecBlock::FixedSizeSecBlock
FixedSizeSecBlock()
Construct a FixedSizeSecBlock.
Definition: secblock.h:1120
SecBlock::CleanNew
void CleanNew(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:1019
SecBlock::operator=
SecBlock< T, A > & operator=(const SecBlock< T, A > &t)
Assign contents from another SecBlock.
Definition: secblock.h:920
SecBlock::SizeInBytes
size_type SizeInBytes() const
Provides the number of bytes in the SecBlock.
Definition: secblock.h:845
SecBlock::resize
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:1070
SecBlock::operator+=
SecBlock< T, A > & operator+=(const SecBlock< T, A > &t)
Append contents from another SecBlock.
Definition: secblock.h:930
AllocatorBase::ELEMS_MAX
static const size_type ELEMS_MAX
Returns the maximum number of elements the allocator can provide.
Definition: secblock.h:58
SecBlock::CleanGrow
void CleanGrow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:1052
AlignedAllocate
CRYPTOPP_DLL void *CRYPTOPP_API AlignedAllocate(size_t size)
Allocates a buffer on 16-byte boundary.
Definition: allocate.cpp:43
SecBlock::end
const_iterator end() const
Provides a constant iterator pointing beyond the last element in the memory block.
Definition: secblock.h:818
SecBlock::Assign
void Assign(const SecBlock< T, A > &t)
Copy contents from another SecBlock.
Definition: secblock.h:903
SecBlock::operator+
SecBlock< T, A > operator+(const SecBlock< T, A > &t)
Construct a SecBlock from this and another SecBlock.
Definition: secblock.h:957
FixedSizeAllocatorWithCleanup< T, S, A, false >::allocate
pointer allocate(size_type size, const void *hint)
Allocates a block of memory.
Definition: secblock.h:607
SecBlock::SecBlock
SecBlock(size_type size=0)
Construct a SecBlock with space for size elements.
Definition: secblock.h:744
SecBlock
Secure memory block with allocator and cleanup.
Definition: secblock.h:709
memcpy_s
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:506
config.h
Library configuration file.
SecBlock::operator!=
bool operator!=(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:991
std
STL namespace.
stdcpp.h
Common C++ header files.
SecBlock::New
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:1004
SecByteBlock
SecBlock<byte> typedef.
Definition: secblock.h:1097
FixedSizeAllocatorWithCleanup< T, S, A, true >::allocate
pointer allocate(size_type size, const void *hint)
Allocates a block of memory.
Definition: secblock.h:402
AllocatorWithCleanup::reallocate
pointer reallocate(T *oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:259
FixedSizeAllocatorWithCleanup< T, S, A, true >::reallocate
pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:461
operator==
bool operator==(const OID &lhs, const OID &rhs)
Compare two OIDs for equality.
FixedSizeAllocatorWithCleanup
Static secure memory block with cleanup.
Definition: secblock.h:336
AllocatorWithCleanup
Allocates a block of memory with cleanup.
Definition: secblock.h:187
AllocatorBase::max_size
size_type max_size() const
Returns the maximum number of elements the allocator can provide.
Definition: secblock.h:73
allocate.h
Functions for allocating aligned buffers.
FixedSizeAllocatorWithCleanup< T, S, A, false >::allocate
pointer allocate(size_type size)
Allocates a block of memory.
Definition: secblock.h:581
operator!=
bool operator!=(const OID &lhs, const OID &rhs)
Compare two OIDs for inequality.
SecureWipeArray
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1471
IsAlignedOn
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:1207
FixedSizeAllocatorWithCleanup< T, S, A, true >::allocate
pointer allocate(size_type size)
Allocates a block of memory.
Definition: secblock.h:376
VerifyBufsEqual
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:114
memset_z
void * memset_z(void *ptr, int val, size_t num)
Memory block initializer.
Definition: misc.h:618
AllocatorWithCleanup::rebind
Template class member Rebind.
Definition: secblock.h:272
SecBlock::data
A::pointer data()
Provides a pointer to the first element in the memory block.
Definition: secblock.h:823
SecBlock::Assign
void Assign(const T *ptr, size_type len)
Set contents and size from an array.
Definition: secblock.h:875
FixedSizeAllocatorWithCleanup< T, S, A, true >::FixedSizeAllocatorWithCleanup
FixedSizeAllocatorWithCleanup()
Constructs a FixedSizeAllocatorWithCleanup.
Definition: secblock.h:362
SecBlock::data
A::const_pointer data() const
Provides a pointer to the first element in the memory block.
Definition: secblock.h:826
FixedSizeAlignedSecBlock
Fixed size stack-based SecBlock with 16-byte alignment.
Definition: secblock.h:1128
FixedSizeAllocatorWithCleanup< T, S, A, true >::deallocate
void deallocate(void *ptr, size_type size)
Deallocates a block of memory.
Definition: secblock.h:421
FixedSizeAllocatorWithCleanup< T, S, A, false >::reallocate
pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:665
FixedSizeAllocatorWithCleanup< T, S, A, false >::FixedSizeAllocatorWithCleanup
FixedSizeAllocatorWithCleanup()
Constructs a FixedSizeAllocatorWithCleanup.
Definition: secblock.h:567
AlignedSecByteBlock
SecBlock using AllocatorWithCleanup<byte, true> typedef.
Definition: secblock.h:1101
UnalignedAllocate
CRYPTOPP_DLL void *CRYPTOPP_API UnalignedAllocate(size_t size)
Allocates a buffer.
Definition: allocate.cpp:92
AllocatorWithCleanup::allocate
pointer allocate(size_type size, const void *ptr=NULL)
Allocates a block of memory.
Definition: secblock.h:206
FixedSizeSecBlock
Fixed size stack-based SecBlock.
Definition: secblock.h:1116
SecBlock::SecBlock
SecBlock(const SecBlock< T, A > &t)
Copy construct a SecBlock from another SecBlock.
Definition: secblock.h:750
STDMIN
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:635
CRYPTOPP_ASSERT
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68
AllocatorWithCleanup::deallocate
void deallocate(void *ptr, size_type size)
Deallocates a block of memory.
Definition: secblock.h:229
SecBlock::begin
iterator begin()
Provides an iterator pointing to the first element in the memory block.
Definition: secblock.h:806
SecBlock::operator==
bool operator==(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:977
NullAllocator
NULL allocator.
Definition: secblock.h:298
AlignedDeallocate
CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr)
Frees a buffer allocated with AlignedAllocate.
Definition: allocate.cpp:72
SecBlockWithHint::SecBlockWithHint
SecBlockWithHint(size_t size)
construct a SecBlockWithHint with a count of elements
Definition: secblock.h:1141
SecBlock::BytePtr
const byte * BytePtr() const
Return a byte pointer to the first element in the memory block.
Definition: secblock.h:841
StandardReallocate
A::pointer StandardReallocate(A &alloc, T *oldPtr, typename A::size_type oldSize, typename A::size_type newSize, bool preserve)
Reallocation function.
Definition: secblock.h:149
SecBlock::begin
const_iterator begin() const
Provides a constant iterator pointing to the first element in the memory block.
Definition: secblock.h:810
SecBlock::SecBlock
SecBlock(const T *ptr, size_type len)
Construct a SecBlock from an array of elements.
Definition: secblock.h:765
STDMAX
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:646
FixedSizeAllocatorWithCleanup< T, S, A, false >::deallocate
void deallocate(void *ptr, size_type size)
Deallocates a block of memory.
Definition: secblock.h:626
SecBlock::Grow
void Grow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:1034
CryptoPP
Crypto++ library namespace.
AllocatorBase::destroy
void destroy(V *ptr)
Destroys an V constructed with variadic arguments.
Definition: secblock.h:98
SecBlock::Assign
void Assign(size_type count, T value)
Set contents from a value.
Definition: secblock.h:888
SecBlock::SetMark
void SetMark(size_t count)
Sets the number of elements to zeroize.
Definition: secblock.h:868
swap
void swap(::SecBlock< T, A > &a, ::SecBlock< T, A > &b)
Swap two SecBlocks.
Definition: secblock.h:1159
SecBlock::empty
bool empty() const
Determines if the SecBlock is empty.
Definition: secblock.h:834
SecWordBlock
SecBlock<word> typedef.
Definition: secblock.h:1099
SecBlock::size
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:831
SIZE_MAX
#define SIZE_MAX
The maximum value of a machine word.
Definition: misc.h:116
SecBlock::BytePtr
byte * BytePtr()
Provides a byte pointer to the first element in the memory block.
Definition: secblock.h:838