1 /*
2 * (C) 2018 Jack Lloyd
3 *
4 * Botan is released under the Simplified BSD License (see license.txt)
5 */
6 
7 #include <botan/ffi.h>
8 #include <botan/internal/ffi_util.h>
9 
10 #if defined(BOTAN_HAS_TOTP)
11    #include <botan/otp.h>
12 #endif
13 
14 extern "C" {
15 
16 using namespace Botan_FFI;
17 
18 #if defined(BOTAN_HAS_TOTP)
19 
20 BOTAN_FFI_DECLARE_STRUCT(botan_totp_struct, Botan::TOTP, 0x3D9D2CD1);
21 
22 #endif
23 
botan_totp_init(botan_totp_t * totp,const uint8_t key[],size_t key_len,const char * hash_algo,size_t digits,size_t time_step)24 int botan_totp_init(botan_totp_t* totp,
25                     const uint8_t key[], size_t key_len,
26                     const char* hash_algo,
27                     size_t digits,
28                     size_t time_step)
29    {
30    if(totp == nullptr || key == nullptr || hash_algo == nullptr)
31       return BOTAN_FFI_ERROR_NULL_POINTER;
32 
33    *totp = nullptr;
34 
35 #if defined(BOTAN_HAS_TOTP)
36    return ffi_guard_thunk(__func__, [=]() -> int {
37 
38       *totp = new botan_totp_struct(
39          new Botan::TOTP(key, key_len, hash_algo, digits, time_step));
40 
41       return BOTAN_FFI_SUCCESS;
42       });
43 #else
44    BOTAN_UNUSED(totp, key, key_len, hash_algo, digits, time_step);
45    return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
46 #endif
47    }
48 
botan_totp_destroy(botan_totp_t totp)49 int botan_totp_destroy(botan_totp_t totp)
50    {
51 #if defined(BOTAN_HAS_TOTP)
52    return BOTAN_FFI_CHECKED_DELETE(totp);
53 #else
54    BOTAN_UNUSED(totp);
55    return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
56 #endif
57    }
58 
botan_totp_generate(botan_totp_t totp,uint32_t * totp_code,uint64_t timestamp)59 int botan_totp_generate(botan_totp_t totp,
60                         uint32_t* totp_code,
61                         uint64_t timestamp)
62    {
63 #if defined(BOTAN_HAS_TOTP)
64    if(totp == nullptr || totp_code == nullptr)
65       return BOTAN_FFI_ERROR_NULL_POINTER;
66 
67    return BOTAN_FFI_DO(Botan::TOTP, totp, t, {
68       *totp_code = t.generate_totp(timestamp);
69       });
70 
71 #else
72    BOTAN_UNUSED(totp, totp_code, timestamp);
73    return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
74 #endif
75    }
76 
botan_totp_check(botan_totp_t totp,uint32_t totp_code,uint64_t timestamp,size_t acceptable_clock_drift)77 int botan_totp_check(botan_totp_t totp,
78                      uint32_t totp_code,
79                      uint64_t timestamp,
80                      size_t acceptable_clock_drift)
81    {
82 #if defined(BOTAN_HAS_TOTP)
83    return BOTAN_FFI_RETURNING(Botan::TOTP, totp, t, {
84       const bool ok = t.verify_totp(totp_code, timestamp, acceptable_clock_drift);
85       return (ok ? BOTAN_FFI_SUCCESS : BOTAN_FFI_INVALID_VERIFIER);
86       });
87 
88 #else
89    BOTAN_UNUSED(totp, totp_code, timestamp, acceptable_clock_drift);
90    return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
91 #endif
92    }
93 
94 }
95