3
3
#include < ArduinoOTA.h>
4
4
#include < WebServer.h>
5
5
#include " mbedtls/sha1.h"
6
- #include " sodium/utils.h"
7
6
8
7
9
8
// / We have two options - we either come in with a bearer
@@ -47,28 +46,26 @@ const char* www_password_hex = "8cb124f8c277c16ec0b2ee00569fd151a08e342b";
47
46
const char * www_username_base64 = " base64admin" ;
48
47
const char * www_password_base64 = " jLEk+MJ3wW7Asu4AVp/RUaCONCs=" ;
49
48
49
+ static unsigned char _bearer[20 ];
50
50
String * check_bearer_or_auth (HTTPAuthMethod mode, String authReq, String params[]) {
51
51
// we expect authReq to be "bearer some-secret"
52
52
//
53
53
String lcAuthReq = authReq;
54
- lcAuthReq.toLowerCase ();
54
+ lcAuthReq.toLowerCase ();
55
55
if (mode == OTHER_AUTH && (lcAuthReq.startsWith (" bearer " ))) {
56
56
String secret = authReq.substring (7 );
57
57
secret.trim ();
58
58
59
59
uint8_t sha1[20 ];
60
60
mbedtls_sha1 ((const uint8_t *) secret.c_str (), secret.length (), sha1);
61
61
62
- char sha1calc[48 ]; // large enough for base64 and Hex represenation
63
- sodium_bin2hex (sha1calc, sizeof (sha1calc), sha1, sizeof (sha1));
64
-
65
- if (secret_token_hex.equalsConstantTime (sha1calc))
66
- return new String (" anything non null" );
62
+ if (0 == memcpy (_bearer, sha1, sizeof (_bearer)))
63
+ return new String (" anything non null" );
67
64
};
68
65
69
- // that failed - so do a normal auth
70
- //
71
- return server.authenticateBasicSHA1 (www_username_hex, www_password_hex) ?
66
+ // that failed - so do a normal auth
67
+ //
68
+ return server.authenticateBasicSHA1 (www_username_hex, www_password_hex) ?
72
69
new String (params[0 ]) : NULL ;
73
70
};
74
71
@@ -83,6 +80,22 @@ void setup() {
83
80
}
84
81
ArduinoOTA.begin ();
85
82
83
+
84
+ // Convert token to a convenient binary representation.
85
+ //
86
+ if (secret_token_hex.length () != 2 * 20 ) {
87
+ Serial.println (" Bearer token does not look like a hex string ?!" );
88
+ }
89
+
90
+ #define _H2D (x ) (((x)>=' 0' && ((x) <=' 9' )) ? ((x)-' 0' ) : (((x)>=' a' && (x)<=' f' ) ? ((x)-' a' ) : 0 ))
91
+ #define H2D (x ) (_H2D(tolower((x))))
92
+ const char * _shaBase64 = secret_token_hex.c_str ();
93
+ for (int i = 0 ; i < 20 ; i++) {
94
+ unsigned char c = _shaBase64[2 * i + 0 ];
95
+ unsigned char d = _shaBase64[2 * i + 1 ];
96
+ _bearer[i] = (H2D (c) << 4 ) | H2D (d);
97
+ };
98
+
86
99
server.on (" /" , []() {
87
100
if (!server.authenticate (&check_bearer_or_auth)) {
88
101
Serial.println (" No/failed authentication" );
0 commit comments