basic_auth.cpp 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #include "basic_auth.h"
  2. #include "read_wlanini.h"
  3. #include <esp_tls_crypto.h>
  4. #include <esp_log.h>
  5. #include <string>
  6. #include "esp_timer.h"
  7. #include "ClassLogFile.h"
  8. #define HTTPD_401 "401 UNAUTHORIZED"
  9. static const char *TAG = "HTTPAUTH";
  10. typedef struct {
  11. const char *username;
  12. const char *password;
  13. } basic_auth_info_t;
  14. basic_auth_info_t basic_auth_info = { NULL, NULL };
  15. // All URI handlers are registered through APPLY_BASIC_AUTH_FILTER. Measuring here
  16. // gives us a common duration for every HTTP endpoint, including static HTML/CSS/JS
  17. // and image handlers. Time spent waiting in the ESP-IDF server queue is not included.
  18. class HttpRequestTiming
  19. {
  20. public:
  21. explicit HttpRequestTiming(httpd_req_t *request)
  22. : uri(request->uri ? request->uri : "<unknown>"),
  23. method(request->method == HTTP_GET ? "GET" :
  24. request->method == HTTP_POST ? "POST" :
  25. request->method == HTTP_PUT ? "PUT" :
  26. request->method == HTTP_DELETE ? "DELETE" : "OTHER"),
  27. startUs(esp_timer_get_time())
  28. {
  29. }
  30. ~HttpRequestTiming()
  31. {
  32. const int64_t elapsedUs = esp_timer_get_time() - startUs;
  33. // Catch noticeable handler stalls without logging every normal poll.
  34. if (elapsedUs >= 100000)
  35. {
  36. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  37. std::string("Slow HTTP request: ") + method + " " + uri +
  38. " handler time " +
  39. std::to_string(static_cast<long long>(elapsedUs / 1000)) + " ms");
  40. }
  41. }
  42. private:
  43. std::string uri;
  44. const char *method;
  45. int64_t startUs;
  46. };
  47. void init_basic_auth() {
  48. if (!wlan_config.http_username.empty() && !wlan_config.http_password.empty()) {
  49. basic_auth_info.username = wlan_config.http_username.c_str();
  50. basic_auth_info.password = wlan_config.http_password.c_str();
  51. }
  52. }
  53. static char *http_auth_basic(const char *username, const char *password)
  54. {
  55. int out;
  56. char *user_info = NULL;
  57. char *digest = NULL;
  58. size_t n = 0;
  59. asprintf(&user_info, "%s:%s", username, password);
  60. if (!user_info) {
  61. ESP_LOGE(TAG, "No enough memory for user information");
  62. return NULL;
  63. }
  64. esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
  65. /* 6: The length of the "Basic " string
  66. * n: Number of bytes for a base64 encode format
  67. * 1: Number of bytes for a reserved which be used to fill zero
  68. */
  69. digest = static_cast<char*>(calloc(1, 6 + n + 1));
  70. if (digest) {
  71. strcpy(digest, "Basic ");
  72. esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
  73. }
  74. free(user_info);
  75. return digest;
  76. }
  77. esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *))
  78. {
  79. HttpRequestTiming requestTiming(req);
  80. char *buf = NULL;
  81. size_t buf_len = 0;
  82. esp_err_t ret = ESP_OK;
  83. char unauthorized[] = "You are not authorized to use this website!";
  84. if (basic_auth_info.username == NULL || basic_auth_info.password == NULL) {
  85. ret = original_handler(req);
  86. } else {
  87. buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
  88. if (buf_len > 1) {
  89. buf = static_cast<char*>(calloc(1, buf_len));
  90. if (!buf) {
  91. ESP_LOGE(TAG, "No enough memory for basic authorization");
  92. return ESP_ERR_NO_MEM;
  93. }
  94. if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) {
  95. ESP_LOGI(TAG, "Found header => Authorization: %s", buf);
  96. } else {
  97. ESP_LOGE(TAG, "No auth value received");
  98. }
  99. char *auth_credentials = http_auth_basic(basic_auth_info.username, basic_auth_info.password);
  100. if (!auth_credentials) {
  101. ESP_LOGE(TAG, "No enough memory for basic authorization credentials");
  102. free(buf);
  103. return ESP_ERR_NO_MEM;
  104. }
  105. if (strncmp(auth_credentials, buf, buf_len)) {
  106. ESP_LOGE(TAG, "Not authenticated");
  107. httpd_resp_set_status(req, HTTPD_401);
  108. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  109. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  110. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  111. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  112. } else {
  113. ESP_LOGI(TAG, "Authenticated calling http handler now!");
  114. ret=original_handler(req);
  115. }
  116. free(auth_credentials);
  117. free(buf);
  118. } else {
  119. ESP_LOGE(TAG, "No auth header received");
  120. httpd_resp_set_status(req, HTTPD_401);
  121. httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
  122. httpd_resp_set_hdr(req, "Connection", "keep-alive");
  123. httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
  124. httpd_resp_send(req, unauthorized, strlen(unauthorized));
  125. }
  126. }
  127. return ret;
  128. }