basic_auth.cpp 5.1 KB

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