summaryrefslogtreecommitdiffhomepage
path: root/auth.cpp
diff options
context:
space:
mode:
authorRoland Reichwein <mail@reichwein.it>2020-04-26 19:52:44 +0200
committerRoland Reichwein <mail@reichwein.it>2020-04-26 19:52:44 +0200
commita595932283a3f3bf002eff5bf044762b78cab5f0 (patch)
tree790ba05f95b3fd3d6790f8132f9f6f95f908f18a /auth.cpp
parentc73f913844f6aed9e740780f8a6732477fa3d680 (diff)
crypt(3) http auth pws
Diffstat (limited to 'auth.cpp')
-rw-r--r--auth.cpp54
1 files changed, 54 insertions, 0 deletions
diff --git a/auth.cpp b/auth.cpp
new file mode 100644
index 0000000..c9c9765
--- /dev/null
+++ b/auth.cpp
@@ -0,0 +1,54 @@
+#include "auth.h"
+
+#include <crypt.h>
+#include <string.h>
+
+#include <stdexcept>
+#include <iostream>
+
+// crypt specified password
+std::string Auth::generate(const std::string& pw)
+{
+ struct crypt_data data;
+ memset((void *)&data, '\0', sizeof(data));
+
+ if (crypt_gensalt_rn("$6$", 2000, nullptr, 0, data.setting, sizeof(data.setting)) == nullptr)
+ throw std::runtime_error("Error on crypt_gensalt_r()");
+
+ strncpy(data.input, pw.data(), sizeof(data.input));
+
+ if (crypt_r(data.input, data.setting, &data) == nullptr)
+ throw std::runtime_error("Error on crypt_r()");
+
+ return data.output;
+}
+
+// validate specified password against crypted hash
+bool Auth::validate(const std::string& crypted, const std::string& pw)
+{
+ struct crypt_data data;
+ memset((void *)&data, '\0', sizeof(data));
+
+ size_t pos = crypted.find_last_of('$');
+ if (pos == crypted.npos) {
+ std::cerr << "Warning: Bad password hash configured (format)" << std::endl;
+ return false;
+ }
+
+ if (sizeof(data.setting) <= pos) {
+ std::cerr << "Warning: Bad password hash configured (salt size)" << std::endl;
+ return false;
+ }
+
+ memcpy(&data.setting, crypted.data(), pos);
+
+ strncpy(data.input, pw.data(), sizeof(data.input));
+
+ if (crypt_r(data.input, data.setting, &data) == nullptr) {
+ std::cerr << "Warning: Error on crypt_r()" << std::endl;
+ return false;
+ }
+
+ return crypted == data.output;
+}
+