Fix potential buffer overflow error CID: 40674
[platform/core/security/key-manager.git] / tests / test_safe-buffer.cpp
1 #include <vector>
2
3 #include <boost/test/unit_test.hpp>
4 #include <test_common.h>
5
6 #include <ckm/ckm-raw-buffer.h>
7
8 using namespace CKM;
9
10 namespace {
11
12 const size_t LEN = 100;
13
14 struct Item
15 {
16     Item(size_t a) : mA(a) {}
17     ~Item() {}
18
19     bool operator==(const size_t& other) const {
20         return mA == other;
21     }
22
23     size_t mA;
24 };
25
26 template <typename T>
27 size_t buffer_erase_test()
28 {
29     typename T::value_type* data = NULL;
30     typename T::size_type i = 0;
31     {
32         T buffer;
33         for (i=0;i<LEN;++i)
34             buffer.push_back(typename T::value_type(i));
35
36         data = buffer.data();
37
38         for (i=0;i<LEN;++i)
39             BOOST_CHECK(data[i] == i);
40     }
41
42     /*
43      *  operator delete of RawBuffer which is called after buffer memory is erased
44      *  (see erase_on_dealloc::deallocate) sometimes leaves garbage in the beginning of that memory.
45      *  Therefore the test will be marked as failing only if more than 1/10 of the data matches
46      *  original
47      */
48     size_t cnt = 0;
49     for (i=0;i<LEN;++i)
50         cnt += (data[i] == i?1:0);
51
52     return cnt;
53 }
54
55 } // namespace anonymous
56
57 BOOST_AUTO_TEST_SUITE(SAFE_BUFFER_TEST)
58
59 // Tests for SafeBuffer. Checks if memory occupied by the buffer is wiped after it's deleted.
60
61 BOOST_AUTO_TEST_CASE(SafeBufferTest_uc_control_group) {
62     size_t cnt = buffer_erase_test<std::vector<unsigned char> >();
63
64     BOOST_REQUIRE_MESSAGE(cnt > LEN/2, "Less than 1/2 of data matches the original.");
65 }
66
67 BOOST_AUTO_TEST_CASE(SafeBufferTest_item_control_group) {
68     size_t cnt = buffer_erase_test<std::vector<Item> >();
69
70     BOOST_REQUIRE_MESSAGE(cnt > LEN/2, "Less than 1/2 of data matches the original.");
71 }
72
73 BOOST_AUTO_TEST_CASE(SafeBufferTest_uc) {
74     size_t cnt = buffer_erase_test<RawBuffer>();
75
76     BOOST_REQUIRE_MESSAGE(cnt <= LEN/10, "More than 1/10 of data matches the original.");
77 }
78
79 BOOST_AUTO_TEST_CASE(SafeBufferTest_item) {
80     size_t cnt = buffer_erase_test<SafeBuffer<Item>::Type>();
81
82     BOOST_REQUIRE_MESSAGE(cnt <= LEN/10, "More than 1/10 of data matches the original.");
83 }
84
85 BOOST_AUTO_TEST_SUITE_END()