auth.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. HTTP auth implementation. Only does basic authentication for now.
  3. */
  4. /*
  5. * ----------------------------------------------------------------------------
  6. * "THE BEER-WARE LICENSE" (Revision 42):
  7. * Jeroen Domburg <jeroen@spritesmods.com> wrote this file. As long as you retain
  8. * this notice you can do whatever you want with this stuff. If we meet some day,
  9. * and you think this stuff is worth it, you can buy me a beer in return.
  10. * ----------------------------------------------------------------------------
  11. */
  12. #include <esp8266.h>
  13. #include "auth.h"
  14. #include "base64.h"
  15. int ICACHE_FLASH_ATTR authBasic(HttpdConnData *connData) {
  16. const char *forbidden="401 Forbidden.";
  17. int no=0;
  18. int r;
  19. char hdr[(AUTH_MAX_USER_LEN+AUTH_MAX_PASS_LEN+2)*10];
  20. char userpass[AUTH_MAX_USER_LEN+AUTH_MAX_PASS_LEN+2];
  21. char user[AUTH_MAX_USER_LEN];
  22. char pass[AUTH_MAX_PASS_LEN];
  23. if (connData->conn==NULL) {
  24. //Connection aborted. Clean up.
  25. return HTTPD_CGI_DONE;
  26. }
  27. r=httpdGetHeader(connData, "Authorization", hdr, sizeof(hdr));
  28. if (r && strncmp(hdr, "Basic", 5)==0) {
  29. r=base64_decode(strlen(hdr)-6, hdr+6, sizeof(userpass), (unsigned char *)userpass);
  30. if (r<0) r=0; //just clean out string on decode error
  31. userpass[r]=0; //zero-terminate user:pass string
  32. os_printf("Auth: %s\n", userpass);
  33. while (((AuthGetUserPw)(connData->cgiArg))(connData, no,
  34. user, AUTH_MAX_USER_LEN, pass, AUTH_MAX_PASS_LEN)) {
  35. //Check user/pass against auth header
  36. if (strlen(userpass)==strlen(user)+strlen(pass)+1 &&
  37. os_strncmp(userpass, user, strlen(user))==0 &&
  38. userpass[strlen(user)]==':' &&
  39. os_strcmp(userpass+strlen(user)+1, pass)==0) {
  40. os_printf("Auth: enticated. Yay!\n");
  41. //Authenticated. Yay!
  42. return HTTPD_CGI_AUTHENTICATED;
  43. }
  44. no++; //Not authenticated with this user/pass. Check next user/pass combo.
  45. }
  46. }
  47. //Not authenticated. Go bug user with login screen.
  48. httpdStartResponse(connData, 401);
  49. httpdHeader(connData, "Content-Type", "text/plain");
  50. httpdHeader(connData, "WWW-Authenticate", "Basic realm=\""HTTP_AUTH_REALM"\"");
  51. httpdEndHeaders(connData);
  52. httpdSend(connData, forbidden, -1);
  53. //Okay, all done.
  54. return HTTPD_CGI_DONE;
  55. }