↵ select ↓ ↑ navigate esc close

Una Watch TOTP - MFA on your wrist!

Terence Eden’s Blog ·

Let's get this out of the way first - this is a terrible idea! I want my two-factor authentication codes to be easily accessible to me, so I've built a watch app which will display them. That's really convenient for me - but makes for a terrible security posture. Anyone who steals my watch will be able to see my one-time code. If they're clever, they can decompile the app and find the secret which powers the code generation.

You should absolutely not do this and, if you ignore my warnings, you should only do this for codes which aren't critical to your security.

In my defence, an attacker would still need my username and password to make any use of these codes - but please don't trust your security to my deranged witterings.

What It Looks Like

My wristwatch showing "HSBC MFA Code 751646". Don't worry, this isn't my real code. OR IS IT?!?!

Prior Art

I'm sure many other people have done this. Indeed, three years ago I built An eInk, Wrist-Mounted, TOTP Generator.

A chunky wristwatch showing the time and a selection of 6 digit codes and their corresponding entities.

The Service

This is in my Service.cpp - as you can see, it's pretty simple. This won't let you add in hundreds of codes - you get one and that's it. There's no countdown when a code is about to expire, so I recommend waiting until a new one pops up before you start typing it in.

I'll be candid, I haven't used C++ properly since university - and that was in the last century. I've mostly just cut things out to see what breaks. Feel free to educate me on the correct idiomatic code.

You will need to set your own secret in here.

  1//  Standard includes.
  2#include "Service.hpp"
  3#include "SDK/Messages/CommandMessages.hpp"
  4#include "SDK/Messages/MessageGuard.hpp"
  5
  6//  Needed for PureTOTP.
  7#include <iostream>
  8#include "TOTP.h"
  9
 10#include <string>
 11#include <sstream>
 12
 13//  What this Glance can do.
 14Service::Service(SDK::Kernel &kernel)
 15    : mKernel(kernel)
 16    , mGlanceUI()
 17    , mGlanceTitle()
 18    , mGlanceValue()
 19{}
 20
 21void Service::createGuiControls()
 22{
 23    //  Set the main title in the Glance.
 24    mGlanceTitle = mGlanceUI.createText();
 25    mGlanceTitle.pos({ kTitleX, kTitleY }, { kTitleW, kTitleH })
 26        .font(GlanceFont_t::GLANCE_FONT_POPPINS_SEMIBOLD_20)
 27        .color(GlanceColor_t::GLANCE_COLOR_TEAL)
 28        .setText("HSBC MFA Code")
 29        .alignment(GlanceAlignH_t::GLANCE_ALIGN_H_CENTER);
 30
 31    //  Set the default text for the value.
 32    mGlanceValue = mGlanceUI.createText();
 33    mGlanceValue.pos({ 20, kValueY }, { 200, kValueH })
 34        .font(GlanceFont_t::GLANCE_FONT_POPPINS_SEMIBOLD_20)
 35        .color(GlanceColor_t::GLANCE_COLOR_YELLOW_DARK)
 36        .setText( "Waiting for update" )
 37        .alignment(GlanceAlignH_t::GLANCE_ALIGN_H_CENTER);
 38}
 39
 40void Service::glanceUpdate()
 41{
 42    //  Set the Base32 encoded secret (all uppercase).
 43    std::string secret = "QWERTYUIOP";
 44    //  Generate the code based on the Unix timestamp right now.
 45    const std::time_t t = std::time(0);
 46    std::string code = TOTP::GenerateTOTP( 6, 30, TOTP::HMAC_SHA1, secret, t );
 47
 48    std::ostringstream ss;
 49    ss << t;
 50
 51    //  Convert the string to char* and display it as the value.
 52    mGlanceValue.print( code.c_str() ); 
 53
 54    //  Show the Unix time to check the timezone is correct.
 55    // mGlanceTitle.print( ss.str().c_str() );
 56}
 57
 58//  No service.
 59Service::~Service(){}
 60
 61//  When this glance is opened.
 62void Service::run()
 63{
 64    while (true) {
 65        SDK::MessageBase *msg;
 66        if(!mKernel.comm.getMessage(msg)) {
 67            continue;
 68        }
 69
 70        switch (msg->getType()) {
 71            //  The Glance has started.
 72            case SDK::MessageType::EVENT_GLANCE_START:
 73                if (configGui()) {
 74                    createGuiControls();
 75                } else {
 76                    mKernel.comm.releaseMessage(msg);
 77                    mKernel.sys.exit(0);
 78                }
 79                break;
 80            //  The Glance has been stopped.
 81            case SDK::MessageType::COMMAND_APP_STOP:
 82            case SDK::MessageType::EVENT_GLANCE_STOP:
 83                mKernel.comm.releaseMessage(msg);
 84                return;
 85                break;
 86
 87            //  Every second, perform an action.
 88            case SDK::MessageType::EVENT_GLANCE_TICK:
 89                onGlanceTick();
 90                break;
 91
 92            default:
 93                break;
 94        }
 95
 96        mKernel.comm.releaseMessage(msg);
 97    }
 98}
 99
100void Service::onGlanceTick()
101{
102    if (mGlanceUI.isInvalid()) {
103        if (auto upd = SDK::make_msg<SDK::Message::RequestGlanceUpdate>(mKernel)) {
104            upd->name           = APP_NAME;
105            upd->controls       = mGlanceUI.data();
106            upd->controlsNumber = static_cast<uint32_t>(mGlanceUI.size());
107            upd.send(100);
108        }
109
110        mGlanceUI.setValid();
111    }
112    glanceUpdate();
113}
114
115bool Service::configGui()
116{
117    bool status = false;
118    if (auto gc = SDK::make_msg<SDK::Message::RequestGlanceConfig>(mKernel)) {
119        if (gc.send(100) && gc.ok()) {
120            if (gc->maxControls >= 3) {
121                mGlanceUI.setWidth(gc->width);
122                mGlanceUI.setHeight(gc->height);
123                status = true;
124            }
125        }
126    }
127    return status;
128}

The Library

There are dozens of C++ libraries for RFC 6238 generation. I ended up using PureTOTP as it didn't require any external dependencies and was only two files. As I only needed SHA1 TOTP codes, I stripped out a bunch of functionality which was unnecessary for me. Similarly, I only wanted to generate 6 digit codes with a 30 second period - so took out anything which did more than that.

I've tidied up the code and comments where I can. The original was MIT Licenced - so this is as well.

There are two parts to this. First, the header

// TOTP.h
//
#pragma once
#include <string>
class TOTP
{
public:
    const static int HMAC_SHA1 = 20;    //  Length of HMAC.

    static std::string GenerateTOTP(const std::string& secret);
    static std::string GenerateTOTP(int digit, int refreshSeconds, int algorithm, const std::string& secret, int specTime);

    TOTP(int digit, int refreshSeconds, int algorithm, const std::string& secret): digit(digit), refreshSeconds(refreshSeconds), algorithm(algorithm), secret(secret) {}
    TOTP(const std::string& secret): digit(6), refreshSeconds(30), algorithm(HMAC_SHA1), secret(secret) {}

    std::string currentTOTP();

private:
    int digit, refreshSeconds, algorithm;

    std::string secret;
};

Next is the standalone library which does the TOTP generation, TOTP.cpp

  1// TOTP.cpp
  2//
  3#include "TOTP.h"
  4#include <vector>
  5#include <stack>
  6#include <queue>
  7#include <sstream>
  8#include <iomanip>
  9#include <cstdint>
 10#include <cstring>
 11#include <array>
 12#include <stdexcept>
 13#include <algorithm>
 14using namespace std;
 15
 16struct JEVP_MD
 17{
 18    enum Kind {
 19        SHA1
 20    };
 21
 22    Kind kind;
 23    int  md_size;
 24    int  block_size;
 25};
 26
 27static inline uint32_t rotl32(uint32_t x, uint32_t n) { return (x << n) | (x >> (32 - n)); }
 28static inline uint32_t rotr32(uint32_t x, uint32_t n) { return (x >> n) | (x << (32 - n)); }
 29static inline uint64_t rotr64(uint64_t x, uint64_t n) { return (x >> n) | (x << (64 - n)); }
 30
 31static uint32_t load_be32(const unsigned char* p)
 32{
 33    return (uint32_t(p[0]) << 24) |
 34           (uint32_t(p[1]) << 16) |
 35           (uint32_t(p[2]) <<  8) |
 36            uint32_t(p[3]);
 37}
 38
 39static void store_be32(uint32_t v, unsigned char* p)
 40{
 41    p[0] = static_cast<unsigned char>((v >> 24) & 0xFF);
 42    p[1] = static_cast<unsigned char>((v >> 16) & 0xFF);
 43    p[2] = static_cast<unsigned char>((v >>  8) & 0xFF);
 44    p[3] = static_cast<unsigned char>( v        & 0xFF);
 45}
 46
 47static void store_be64(uint64_t v, unsigned char* p)
 48{
 49    p[0] = static_cast<unsigned char>((v >> 56) & 0xFF);
 50    p[1] = static_cast<unsigned char>((v >> 48) & 0xFF);
 51    p[2] = static_cast<unsigned char>((v >> 40) & 0xFF);
 52    p[3] = static_cast<unsigned char>((v >> 32) & 0xFF);
 53    p[4] = static_cast<unsigned char>((v >> 24) & 0xFF);
 54    p[5] = static_cast<unsigned char>((v >> 16) & 0xFF);
 55    p[6] = static_cast<unsigned char>((v >>  8) & 0xFF);
 56    p[7] = static_cast<unsigned char>( v        & 0xFF);
 57}
 58
 59static vector<unsigned char> sha1_hash(const unsigned char* data, size_t len)
 60{
 61    vector<unsigned char> msg(data, data + len);
 62    uint64_t              bit_len = static_cast<uint64_t>(len) * 8;
 63
 64    msg.push_back(0x80);
 65    while ((msg.size() % 64) != 56) msg.push_back(0x00);
 66
 67    unsigned char lenbuf[8];
 68    store_be64(bit_len, lenbuf);
 69    msg.insert(msg.end(), lenbuf, lenbuf + 8);
 70
 71    uint32_t h0 = 0x67452301;
 72    uint32_t h1 = 0xEFCDAB89;
 73    uint32_t h2 = 0x98BADCFE;
 74    uint32_t h3 = 0x10325476;
 75    uint32_t h4 = 0xC3D2E1F0;
 76
 77    for (size_t chunk = 0; chunk < msg.size(); chunk += 64)
 78    {
 79        uint32_t w[80];
 80        for (int i = 0; i < 16; ++i)
 81            w[i] = load_be32(&msg[chunk + i * 4]);
 82        for (int i = 16; i < 80; ++i)
 83            w[i] = rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
 84
 85        uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
 86
 87        for (int i = 0; i < 80; ++i)
 88        {
 89            uint32_t f, k;
 90            if (i < 20)
 91            {
 92                f = (b & c) | ((~b) & d);
 93                k = 0x5A827999;
 94            }
 95            else if (i < 40)
 96            {
 97                f = b ^ c ^ d;
 98                k = 0x6ED9EBA1;
 99            }
100            else if (i < 60)
101            {
102                f = (b & c) | (b & d) | (c & d);
103                k = 0x8F1BBCDC;
104            }
105            else
106            {
107                f = b ^ c ^ d;
108                k = 0xCA62C1D6;
109            }
110
111            uint32_t temp = rotl32(a, 5) + f + e + k + w[i];
112
113            e = d;
114            d = c;
115            c = rotl32(b, 30);
116            b = a;
117            a = temp;
118        }
119
120        h0 += a;
121        h1 += b;
122        h2 += c;
123        h3 += d;
124        h4 += e;
125    }
126
127    vector<unsigned char> out(20);
128    store_be32(h0, &out[ 0]);
129    store_be32(h1, &out[ 4]);
130    store_be32(h2, &out[ 8]);
131    store_be32(h3, &out[12]);
132    store_be32(h4, &out[16]);
133    return out;
134}
135
136static const JEVP_MD g_sha1   = {JEVP_MD::SHA1, 20, 64};
137
138const JEVP_MD* JEVP_sha1() { return &g_sha1; }
139
140unsigned char* JHMAC(const JEVP_MD* JEVP_MD, const void* key, int key_len, const unsigned char* data, size_t data_len, unsigned char* md, unsigned int* md_len)
141{
142    if (!JEVP_MD || !key || key_len < 0 || !data)
143        return nullptr;
144
145    static thread_local unsigned char static_md[64];
146
147    if (!md)
148        md = static_md;
149
150    vector<unsigned char> key_block(JEVP_MD->block_size, 0);
151    const unsigned char*  key_bytes = static_cast<const unsigned char*>(key);
152
153    vector<unsigned char> real_key;
154    if (key_len > JEVP_MD->block_size)
155    {
156        real_key = sha1_hash(key_bytes, static_cast<size_t>(key_len));
157        std::copy(real_key.begin(), real_key.end(), key_block.begin());
158    }
159    else
160    {
161        std::copy(key_bytes, key_bytes + key_len, key_block.begin());
162    }
163
164    vector<unsigned char> ipad(JEVP_MD->block_size);
165    vector<unsigned char> opad(JEVP_MD->block_size);
166    for (int i = 0; i < JEVP_MD->block_size; ++i)
167    {
168        ipad[i] = static_cast<unsigned char>(key_block[i] ^ 0x36);
169        opad[i] = static_cast<unsigned char>(key_block[i] ^ 0x5C);
170    }
171
172    vector<unsigned char> inner;
173    inner.reserve(JEVP_MD->block_size + data_len);
174    inner.insert(inner.end(), ipad.begin(), ipad.end());
175    inner.insert(inner.end(), data, data + data_len);
176
177    vector<unsigned char> inner_hash = sha1_hash(inner.data(), inner.size());
178
179    vector<unsigned char> outer;
180    outer.reserve(JEVP_MD->block_size + inner_hash.size());
181    outer.insert(outer.end(), opad.begin(), opad.end());
182    outer.insert(outer.end(), inner_hash.begin(), inner_hash.end());
183
184    vector<unsigned char> final_hash = sha1_hash(outer.data(), outer.size());
185
186    std::memcpy(md, final_hash.data(), final_hash.size());
187    if (md_len) *md_len = static_cast<unsigned int>(final_hash.size());
188
189    return md;
190}
191
192//  Base32 decoding table.
193/* clang-format off */
194const int base32_reverse_map[128] =
195{
196    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 15
197    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 31
198    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // 47
199//      (49)   2    3    4    5    6    7  (56)
200    255, 255,  26,  27,  28,  29,  30,  31, 255, 255, 255, 255, 255, 255, 255, 255, // 63
201// (64)   A    B    C    D    E    F    G    H    I    J    K    L    M    N    O
202    255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14, // 79
203//   P    Q    R    S    T    U    V    W    X    Y    Z  (91)
204    15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255, 255, // 95
205// (96)   A    B    C    D    E    F    G    H    I    J    K    L    M    N    O  // lower case instead
206    255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14, // 111
207//   P    Q    R    S    T    U    V    W    X    Y    Z (123)                     // lower case instead
208    15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255, 255  // 127
209};
210/* clang-format on */
211
212//  Base32 decoding function.
213vector<unsigned char> base32_decode(const string& base32)
214{
215    queue<int> q_rev;
216    for (const char& c : base32)
217    {
218        if (c <= 49 || (c >= 56 && c <= 64) || (c >= 91 && c <= 96) || c >= 123)
219        { //    Illegal lower case will be treat as upper case thanks to base32_reverse_map.
220            if (c == '=') break;
221        }
222        else
223        {
224            q_rev.push(base32_reverse_map[(int)c]); //  Get integers of base32.
225        }
226    }
227    queue<bool> q_bin;
228    while (!q_rev.empty()) //   Transform the integers into bits and queue them up.
229    {
230        int now = q_rev.front(); // Get a integer from queue.
231        q_rev.pop();
232        stack<bool> sb;
233        for (int i = 0; i < 5; i++) //  Push the bits of this integer into stack
234        {                           //  5 bits into 1 group
235            sb.push(now & 1);       //  Push the last bit of this integer into stack.
236            now >>= 1;              //  Flush the last bit.
237        }
238        while (!sb.empty()) //  Flush the bits of this integer into binary queue.
239        {
240            q_bin.push(sb.top()); //    Pop bits from stack into binary queue.
241            sb.pop();
242        }
243    }
244    vector<unsigned char> uc;
245    while (!q_bin.empty()) //   Transform the bits into bytes.
246    {
247        int thehex = 0;
248        for (int i = 0; i < 8; i++) //  Read a byte from the bits queue.
249        {
250            if (q_bin.empty())
251            {                     //    If the bits queue is empty now,
252                thehex <<= 8 - i; //    set 0 on the last bits of a byte.
253                break;
254            }
255            thehex <<= 1;                 //    Make the space for the new bit.
256            thehex |= (int)q_bin.front(); //    Push this bit into byte.
257            q_bin.pop();
258        }
259        uc.push_back((unsigned char)thehex);
260    }
261
262    if (uc.back() == 0) uc.pop_back();     //   TOTP may abandon last zero.
263    if (uc.size() % 2 != 0) uc.pop_back(); //   TOTP may abandon odd res.
264    return uc;
265}
266
267//  Get Unix Time.
268time_t getUnixTime()
269{
270    return time(0);
271}
272
273//  Calculate the TOTP time signature.
274time_t getTimeSign(int refreshPeriod, time_t specUnixTime)
275{
276    time_t outTime = specUnixTime / refreshPeriod;
277    return outTime;
278}
279
280//  Transform time_t aka <long long> to bytes.
281vector<unsigned char> llong2bytes(time_t tt)
282{
283    uint64_t value = static_cast<uint64_t>(tt);
284
285    vector<unsigned char> bytes(8);
286
287    for (int i = 7; i >= 0; --i)
288    {
289        bytes[i] = static_cast<unsigned char>(value & 0xFF);
290        value >>= 8;
291    }
292
293    return bytes;
294}
295
296//  Fast Exponentiation algorithm.
297unsigned fastpow(unsigned base, unsigned index)
298{
299    if (index == 0) return 1;
300    unsigned t = 1;
301    while (index != 0)
302    {
303        if (index & 1) t *= base;
304        index >>= 1;
305        base *= base;
306    }
307    return t;
308}
309
310//  Calculate TOTP according to RFC standard.
311std::string hash_to_TOTP(const unsigned char* hmac, unsigned int length, int digit)
312{
313    int offset = hmac[length - 1] & 0x0F;
314
315    uint32_t bin_code = ((hmac[offset]     & 0x7F) << 24) |
316                        ((hmac[offset + 1] & 0xFF) << 16) |
317                        ((hmac[offset + 2] & 0xFF) << 8)  |
318                        ( hmac[offset + 3] & 0xFF);
319
320    uint32_t mod = 1;
321    for (int i = 0; i < digit; ++i) mod *= 10;
322
323    uint32_t otp = bin_code % mod;
324
325    std::ostringstream oss;
326    oss << std::setw(digit) << std::setfill('0') << otp;
327    return oss.str();
328}
329
330std::string TOTP::GenerateTOTP(const std::string& secret)
331{
332    return GenerateTOTP(6, 30, HMAC_SHA1, secret, getUnixTime());
333}
334
335std::string TOTP::GenerateTOTP(int digit, int refreshSeconds, int algorithm, const std::string& secret, int specTime)
336{
337    vector<unsigned char> h_msg = llong2bytes(getTimeSign(refreshSeconds, specTime)); //    Get current time signature and transform time_t aka <long long> to bytes.
338    vector<unsigned char> h_key = base32_decode(secret); // Transform base32 encoded secret key to decoded bytes.
339
340    unsigned char* out_hmac = new unsigned char[algorithm]; //  Perform openssl function to calculate HMAC-SHA1 hash.
341    unsigned int   out_hmac_length;
342    const JEVP_MD* emd;
343    emd = JEVP_sha1();
344    JHMAC(emd, h_key.data(), (int)h_key.size(), h_msg.data(), (int)h_msg.size(), out_hmac, &out_hmac_length);
345
346    string fine = hash_to_TOTP(out_hmac, out_hmac_length, digit);
347    delete[] out_hmac;
348
349    return fine; // Calculate TOTP according to RFC standard.
350}
351
352std::string TOTP::currentTOTP()
353{
354    return GenerateTOTP(digit, refreshSeconds, algorithm, secret, getUnixTime());
355}