Debian Codegraph @

include/jwt/impl/algorithm.ipp

raw
1 /*
2 Copyright (c) 2017 Arun Muralidharan
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #ifndef CPP_JWT_ALGORITHM_IPP
24 #define CPP_JWT_ALGORITHM_IPP
25
26 namespace jwt {
27
28 inline verify_result_t is_secret_a_public_key(const jwt::string_view secret)
29 {
30 std::error_code ec{};
31
32 BIO_uptr bufkey{
33 BIO_new_mem_buf((void*)secret.data(), static_cast<int>(secret.length())),
34 bio_deletor
35 };
36 if (!bufkey) {
37 throw MemoryAllocationException("BIO_new_mem_buf failed");
38 }
39
40 EC_PKEY_uptr pkey{
41 PEM_read_bio_PUBKEY(bufkey.get(), nullptr, nullptr, nullptr),
42 ev_pkey_deletor
43 };
44
45 if (!pkey) {
46 ec = AlgorithmErrc::InvalidKeyErr;
47 return { false, ec };
48 }
49
50 return {true, ec};
51 }
52
53 template <typename Hasher>
54 verify_result_t HMACSign<Hasher>::verify(
55 const jwt::string_view key,
56 const jwt::string_view head,
57 const jwt::string_view jwt_sign)
58 {
59 std::error_code ec{};
60
61 unsigned char enc_buf[EVP_MAX_MD_SIZE];
62 uint32_t enc_buf_len = 0;
63
64 unsigned char* res = HMAC(Hasher{}(),
65 key.data(),
66 static_cast<int>(key.length()),
67 reinterpret_cast<const unsigned char*>(head.data()),
68 head.length(),
69 enc_buf,
70 &enc_buf_len);
71 if (!res) {
72 ec = AlgorithmErrc::VerificationErr;
73 return {false, ec};
74 }
75 if (enc_buf_len == 0) {
76 ec = AlgorithmErrc::VerificationErr;
77 return {false, ec};
78 }
79
80 std::string b64_enc_str = jwt::base64_encode((const char*)&enc_buf[0], enc_buf_len);
81
82 if (!b64_enc_str.length()) {
83 ec = AlgorithmErrc::VerificationErr;
84 return {false, ec};
85 }
86
87 // Make the base64 string url safe
88 auto new_len = jwt::base64_uri_encode(&b64_enc_str[0], b64_enc_str.length());
89 b64_enc_str.resize(new_len);
90
91 bool ret = (new_len == jwt_sign.size()) && (CRYPTO_memcmp(b64_enc_str.data(), jwt_sign.data(), new_len) == 0);
92
93 return { ret, ec };
94 }
95
96
97 template <typename Hasher>
98 verify_result_t PEMSign<Hasher>::verify(
99 const jwt::string_view key,
100 const jwt::string_view head,
101 const jwt::string_view jwt_sign)
102 {
103 std::error_code ec{};
104 std::string dec_sig = base64_uri_decode(jwt_sign.data(), jwt_sign.length());
105
106 BIO_uptr bufkey{
107 BIO_new_mem_buf((void*)key.data(), static_cast<int>(key.length())),
108 bio_deletor};
109
110 if (!bufkey) {
111 throw MemoryAllocationException("BIO_new_mem_buf failed");
112 }
113
114 EC_PKEY_uptr pkey{
115 PEM_read_bio_PUBKEY(bufkey.get(), nullptr, nullptr, nullptr),
116 ev_pkey_deletor};
117
118 if (!pkey) {
119 ec = AlgorithmErrc::InvalidKeyErr;
120 return { false, ec };
121 }
122
123 int pkey_type = EVP_PKEY_id(pkey.get());
124
125 if (pkey_type != Hasher::type) {
126 ec = AlgorithmErrc::VerificationErr;
127 return { false, ec };
128 }
129
130 //Convert EC signature back to ASN1
131 if (Hasher::type == EVP_PKEY_EC) {
132 EC_SIG_uptr ec_sig{ECDSA_SIG_new(), ec_sig_deletor};
133 if (!ec_sig) {
134 throw MemoryAllocationException("ECDSA_SIG_new failed");
135 }
136
137 //Get the actual ec_key
138 EC_KEY_uptr ec_key{EVP_PKEY_get1_EC_KEY(pkey.get()), ec_key_deletor};
139 if (!ec_key) {
140 throw MemoryAllocationException("EVP_PKEY_get1_EC_KEY failed");
141 }
142
143 unsigned int degree = EC_GROUP_get_degree(
144 EC_KEY_get0_group(ec_key.get()));
145
146 unsigned int bn_len = (degree + 7) / 8;
147
148 if ((bn_len * 2) != dec_sig.length()) {
149 ec = AlgorithmErrc::VerificationErr;
150 return { false, ec };
151 }
152
153 BIGNUM* ec_sig_r = BN_bin2bn((unsigned char*)dec_sig.data(), bn_len, nullptr);
154 BIGNUM* ec_sig_s = BN_bin2bn((unsigned char*)dec_sig.data() + bn_len, bn_len, nullptr);
155
156 if (!ec_sig_r || !ec_sig_s) {
157 ec = AlgorithmErrc::VerificationErr;
158 return { false, ec };
159 }
160
161 ECDSA_SIG_set0(ec_sig.get(), ec_sig_r, ec_sig_s);
162
163 size_t nlen = i2d_ECDSA_SIG(ec_sig.get(), nullptr);
164 dec_sig.resize(nlen);
165
166 auto data = reinterpret_cast<unsigned char*>(&dec_sig[0]);
167 nlen = i2d_ECDSA_SIG(ec_sig.get(), &data);
168
169 if (nlen == 0) {
170 ec = AlgorithmErrc::VerificationErr;
171 return { false, ec };
172 }
173 }
174
175 EVP_MDCTX_uptr mdctx_ptr{EVP_MD_CTX_create(), evp_md_ctx_deletor};
176 if (!mdctx_ptr) {
177 throw MemoryAllocationException("EVP_MD_CTX_create failed");
178 }
179
180 if (EVP_DigestVerifyInit(
181 mdctx_ptr.get(), nullptr, Hasher{}(), nullptr, pkey.get()) != 1) {
182 ec = AlgorithmErrc::VerificationErr;
183 return { false, ec };
184 }
185
186 if (EVP_DigestVerifyUpdate(mdctx_ptr.get(), head.data(), head.length()) != 1) {
187 ec = AlgorithmErrc::VerificationErr;
188 return { false, ec };
189 }
190
191 if (EVP_DigestVerifyFinal(
192 mdctx_ptr.get(), (unsigned char*)&dec_sig[0], dec_sig.length()) != 1) {
193 ec = AlgorithmErrc::VerificationErr;
194 return { false, ec };
195 }
196
197 return { true, ec };
198 }
199
200 template <typename Hasher>
201 EVP_PKEY* PEMSign<Hasher>::load_key(
202 const jwt::string_view key,
203 std::error_code& ec)
204 {
205 ec.clear();
206
207 BIO_uptr bio_ptr{
208 BIO_new_mem_buf((void*)key.data(), static_cast<int>(key.length())),
209 bio_deletor};
210
211 if (!bio_ptr) {
212 throw MemoryAllocationException("BIO_new_mem_buf failed");
213 }
214
215 EVP_PKEY* pkey = PEM_read_bio_PrivateKey(
216 bio_ptr.get(), nullptr, nullptr, nullptr);
217
218 if (!pkey) {
219 ec = AlgorithmErrc::SigningErr;
220 return nullptr;
221 }
222
223 auto pkey_type = EVP_PKEY_id(pkey);
224 if (pkey_type != Hasher::type) {
225 ec = AlgorithmErrc::SigningErr;
226 return nullptr;
227 }
228
229 return pkey;
230 }
231
232 template <typename Hasher>
233 std::string PEMSign<Hasher>::evp_digest(
234 EVP_PKEY* pkey,
235 const jwt::string_view data,
236 std::error_code& ec)
237 {
238 ec.clear();
239
240 EVP_MDCTX_uptr mdctx_ptr{EVP_MD_CTX_create(), evp_md_ctx_deletor};
241
242 if (!mdctx_ptr) {
243 throw MemoryAllocationException("EVP_MD_CTX_create failed");
244 }
245
246 //Initialiaze the digest algorithm
247 if (EVP_DigestSignInit(
248 mdctx_ptr.get(), nullptr, Hasher{}(), nullptr, pkey) != 1) {
249 ec = AlgorithmErrc::SigningErr;
250 return {};
251 }
252
253 //Update the digest with the input data
254 if (EVP_DigestSignUpdate(mdctx_ptr.get(), data.data(), data.length()) != 1) {
255 ec = AlgorithmErrc::SigningErr;
256 return {};
257 }
258
259 size_t len = 0;
260
261 if (EVP_DigestSignFinal(mdctx_ptr.get(), nullptr, &len) != 1) {
262 ec = AlgorithmErrc::SigningErr;
263 return {};
264 }
265
266 std::string sign;
267 sign.resize(len);
268
269 //Get the signature
270 if (EVP_DigestSignFinal(mdctx_ptr.get(), (unsigned char*)&sign[0], &len) != 1) {
271 ec = AlgorithmErrc::SigningErr;
272 return {};
273 }
274
275 return sign;
276 }
277
278 template <typename Hasher>
279 std::string PEMSign<Hasher>::public_key_ser(
280 EVP_PKEY* pkey,
281 jwt::string_view sign,
282 std::error_code& ec)
283 {
284 // Get the EC_KEY representing a public key and
285 // (optionaly) an associated private key
286 std::string new_sign;
287 ec.clear();
288
289 EC_KEY_uptr ec_key{EVP_PKEY_get1_EC_KEY(pkey), ec_key_deletor};
290
291 if (!ec_key) {
292 ec = AlgorithmErrc::SigningErr;
293 return {};
294 }
295
296 uint32_t degree = EC_GROUP_get_degree(EC_KEY_get0_group(ec_key.get()));
297
298 ec_key.reset(nullptr);
299
300 auto char_ptr = &sign[0];
301
302 EC_SIG_uptr ec_sig{d2i_ECDSA_SIG(nullptr,
303 (const unsigned char**)&char_ptr,
304 static_cast<long>(sign.length())),
305 ec_sig_deletor};
306
307 if (!ec_sig) {
308 ec = AlgorithmErrc::SigningErr;
309 return {};
310 }
311
312 const BIGNUM* ec_sig_r = nullptr;
313 const BIGNUM* ec_sig_s = nullptr;
314
315 ECDSA_SIG_get0(ec_sig.get(), &ec_sig_r, &ec_sig_s);
316
317 int r_len = BN_num_bytes(ec_sig_r);
318 int s_len = BN_num_bytes(ec_sig_s);
319 int bn_len = static_cast<int>((degree + 7) / 8);
320
321 if ((r_len > bn_len) || (s_len > bn_len)) {
322 ec = AlgorithmErrc::SigningErr;
323 return {};
324 }
325
326 auto buf_len = 2 * bn_len;
327 new_sign.resize(buf_len);
328
329 BN_bn2bin(ec_sig_r, (unsigned char*)&new_sign[0] + bn_len - r_len);
330 BN_bn2bin(ec_sig_s, (unsigned char*)&new_sign[0] + buf_len - s_len);
331
332 return new_sign;
333 }
334
335 } // END namespace jwt
336
337 #endif