saslwrapper.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. #include <stdint.h>
  20. #include <string>
  21. #include <sasl/sasl.h>
  22. #include <sstream>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <unistd.h>
  26. #include <iostream>
  27. using namespace std;
  28. namespace saslwrapper {
  29. class ClientImpl {
  30. public:
  31. ClientImpl() : conn(0), cbIndex(0), maxBufSize(65535), minSsf(0), maxSsf(65535), externalSsf(0), secret(0) {}
  32. ~ClientImpl() { if (conn) sasl_dispose(&conn); conn = 0; }
  33. /**
  34. * Set attributes to be used in authenticating the session. All attributes should be set
  35. * before init() is called.
  36. *
  37. * @param key Name of attribute being set
  38. * @param value Value of attribute being set
  39. * @return true iff success. If false is returned, call getError() for error details.
  40. *
  41. * Available attribute keys:
  42. *
  43. * service - Name of the service being accessed
  44. * username - User identity for authentication
  45. * authname - User identity for authorization (if different from username)
  46. * password - Password associated with username
  47. * host - Fully qualified domain name of the server host
  48. * maxbufsize - Maximum receive buffer size for the security layer
  49. * minssf - Minimum acceptable security strength factor (integer)
  50. * maxssf - Maximum acceptable security strength factor (integer)
  51. * externalssf - Security strength factor supplied by external mechanism (i.e. SSL/TLS)
  52. * externaluser - Authentication ID (of client) as established by external mechanism
  53. */
  54. bool setAttr(const string& key, const string& value);
  55. bool setAttr(const string& key, uint32_t value);
  56. /**
  57. * Initialize the client object. This should be called after all of the properties have been set.
  58. *
  59. * @return true iff success. If false is returned, call getError() for error details.
  60. */
  61. bool init();
  62. /**
  63. * Start the SASL exchange with the server.
  64. *
  65. * @param mechList List of mechanisms provided by the server
  66. * @param chosen The mechanism chosen by the client
  67. * @param initialResponse Initial block of data to send to the server
  68. *
  69. * @return true iff success. If false is returned, call getError() for error details.
  70. */
  71. bool start(const string& mechList, string& chosen, string& initialResponse);
  72. /**
  73. * Step the SASL handshake.
  74. *
  75. * @param challenge The challenge supplied by the server
  76. * @param response (output) The response to be sent back to the server
  77. *
  78. * @return true iff success. If false is returned, call getError() for error details.
  79. */
  80. bool step(const string& challenge, string& response);
  81. /**
  82. * Encode data for secure transmission to the server.
  83. *
  84. * @param clearText Clear text data to be encrypted
  85. * @param cipherText (output) Encrypted data to be transmitted
  86. *
  87. * @return true iff success. If false is returned, call getError() for error details.
  88. */
  89. bool encode(const string& clearText, string& cipherText);
  90. /**
  91. * Decode data received from the server.
  92. *
  93. * @param cipherText Encrypted data received from the server
  94. * @param clearText (output) Decrypted clear text data
  95. *
  96. * @return true iff success. If false is returned, call getError() for error details.
  97. */
  98. bool decode(const string& cipherText, string& clearText);
  99. /**
  100. * Get the user identity (used for authentication) associated with this session.
  101. * Note that this is particularly useful for single-sign-on mechanisms in which the
  102. * username is not supplied by the application.
  103. *
  104. * @param userId (output) Authenticated user ID for this session.
  105. */
  106. bool getUserId(string& userId);
  107. /**
  108. * Get the security strength factor associated with this session.
  109. *
  110. * @param ssf (output) Negotiated SSF value.
  111. */
  112. bool getSSF(int *ssf);
  113. /**
  114. * Get error message for last error.
  115. * This function will return the last error message then clear the error state.
  116. * If there was no error or the error state has been cleared, this function will output
  117. * an empty string.
  118. *
  119. * @param error Error message string
  120. */
  121. void getError(string& error);
  122. private:
  123. // Declare private copy constructor and assignment operator. Ensure that this
  124. // class is non-copyable.
  125. ClientImpl(const ClientImpl&);
  126. const ClientImpl& operator=(const ClientImpl&);
  127. void addCallback(unsigned long id, void* proc);
  128. void lastCallback() { addCallback(SASL_CB_LIST_END, 0); }
  129. void setError(const string& context, int code, const string& text = "", const string& text2 = "");
  130. void interact(sasl_interact_t* prompt);
  131. static int cbName(void *context, int id, const char **result, unsigned *len);
  132. static int cbPassword(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret);
  133. static bool initialized;
  134. sasl_conn_t* conn;
  135. sasl_callback_t callbacks[8];
  136. int cbIndex;
  137. string error;
  138. string serviceName;
  139. string userName;
  140. string authName;
  141. string password;
  142. string hostName;
  143. string externalUserName;
  144. uint32_t maxBufSize;
  145. uint32_t minSsf;
  146. uint32_t maxSsf;
  147. uint32_t externalSsf;
  148. sasl_secret_t* secret;
  149. };
  150. }
  151. using namespace saslwrapper;
  152. bool ClientImpl::initialized = false;
  153. bool ClientImpl::init()
  154. {
  155. int result;
  156. if (!initialized) {
  157. initialized = true;
  158. result = sasl_client_init(0);
  159. if (result != SASL_OK) {
  160. setError("sasl_client_init", result, sasl_errstring(result, 0, 0));
  161. return false;
  162. }
  163. }
  164. addCallback(SASL_CB_GETREALM, 0);
  165. if (!userName.empty()) {
  166. addCallback(SASL_CB_USER, (void*) cbName);
  167. addCallback(SASL_CB_AUTHNAME, (void*) cbName);
  168. if (!password.empty())
  169. addCallback(SASL_CB_PASS, (void*) cbPassword);
  170. else
  171. addCallback(SASL_CB_PASS, 0);
  172. }
  173. lastCallback();
  174. unsigned flags;
  175. flags = 0;
  176. if (!authName.empty() && authName != userName)
  177. flags |= SASL_NEED_PROXY;
  178. result = sasl_client_new(serviceName.c_str(), hostName.c_str(), 0, 0, callbacks, flags, &conn);
  179. if (result != SASL_OK) {
  180. setError("sasl_client_new", result, sasl_errstring(result, 0, 0));
  181. return false;
  182. }
  183. sasl_security_properties_t secprops;
  184. secprops.min_ssf = minSsf;
  185. secprops.max_ssf = maxSsf;
  186. secprops.maxbufsize = maxBufSize;
  187. secprops.property_names = 0;
  188. secprops.property_values = 0;
  189. secprops.security_flags = 0;
  190. result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
  191. if (result != SASL_OK) {
  192. setError("sasl_setprop(SASL_SEC_PROPS)", result);
  193. sasl_dispose(&conn);
  194. conn = 0;
  195. return false;
  196. }
  197. if (!externalUserName.empty()) {
  198. result = sasl_setprop(conn, SASL_AUTH_EXTERNAL, externalUserName.c_str());
  199. if (result != SASL_OK) {
  200. setError("sasl_setprop(SASL_AUTH_EXTERNAL)", result);
  201. sasl_dispose(&conn);
  202. conn = 0;
  203. return false;
  204. }
  205. result = sasl_setprop(conn, SASL_SSF_EXTERNAL, &externalSsf);
  206. if (result != SASL_OK) {
  207. setError("sasl_setprop(SASL_SSF_EXTERNAL)", result);
  208. sasl_dispose(&conn);
  209. conn = 0;
  210. return false;
  211. }
  212. }
  213. return true;
  214. }
  215. bool ClientImpl::setAttr(const string& key, const string& value)
  216. {
  217. if (key == "service")
  218. serviceName = value;
  219. else if (key == "username")
  220. userName = value;
  221. else if (key == "authname")
  222. authName = value;
  223. else if (key == "password") {
  224. password = value;
  225. free(secret);
  226. secret = (sasl_secret_t*) malloc(sizeof(sasl_secret_t) + password.length());
  227. }
  228. else if (key == "host")
  229. hostName = value;
  230. else if (key == "externaluser")
  231. externalUserName = value;
  232. else {
  233. setError("setAttr", -1, "Unknown string attribute name", key);
  234. return false;
  235. }
  236. return true;
  237. }
  238. bool ClientImpl::setAttr(const string& key, uint32_t value)
  239. {
  240. if (key == "minssf")
  241. minSsf = value;
  242. else if (key == "maxssf")
  243. maxSsf = value;
  244. else if (key == "externalssf")
  245. externalSsf = value;
  246. else if (key == "maxbufsize")
  247. maxBufSize = value;
  248. else {
  249. setError("setAttr", -1, "Unknown integer attribute name", key);
  250. return false;
  251. }
  252. return true;
  253. }
  254. bool ClientImpl::start(const string& mechList, string& chosen, string& initialResponse)
  255. {
  256. int result;
  257. sasl_interact_t* prompt = 0;
  258. const char* resp;
  259. const char* mech;
  260. unsigned int len;
  261. do {
  262. result = sasl_client_start(conn, mechList.c_str(), &prompt, &resp, &len, &mech);
  263. if (result == SASL_INTERACT)
  264. interact(prompt);
  265. } while (result == SASL_INTERACT);
  266. if (result != SASL_OK && result != SASL_CONTINUE) {
  267. setError("sasl_client_start", result);
  268. return false;
  269. }
  270. chosen = string(mech);
  271. initialResponse = string(resp, len);
  272. return true;
  273. }
  274. bool ClientImpl::step(const string& challenge, string& response)
  275. {
  276. int result;
  277. sasl_interact_t* prompt = 0;
  278. const char* resp;
  279. unsigned int len;
  280. do {
  281. result = sasl_client_step(conn, challenge.c_str(), challenge.size(), &prompt, &resp, &len);
  282. if (result == SASL_INTERACT)
  283. interact(prompt);
  284. } while (result == SASL_INTERACT);
  285. if (result != SASL_OK && result != SASL_CONTINUE) {
  286. setError("sasl_client_step", result);
  287. return false;
  288. }
  289. response = string(resp, len);
  290. return true;
  291. }
  292. bool ClientImpl::encode(const string& clearText, string& cipherText)
  293. {
  294. const char* output;
  295. unsigned int outlen;
  296. int result = sasl_encode(conn, clearText.c_str(), clearText.size(), &output, &outlen);
  297. if (result != SASL_OK) {
  298. setError("sasl_encode", result);
  299. return false;
  300. }
  301. cipherText = string(output, outlen);
  302. return true;
  303. }
  304. bool ClientImpl::decode(const string& cipherText, string& clearText)
  305. {
  306. const char* input = cipherText.c_str();
  307. unsigned int inLen = cipherText.size();
  308. unsigned int remaining = inLen;
  309. const char* cursor = input;
  310. const char* output;
  311. unsigned int outlen;
  312. clearText = string();
  313. while (remaining > 0) {
  314. unsigned int segmentLen = (remaining < maxBufSize) ? remaining : maxBufSize;
  315. int result = sasl_decode(conn, cursor, segmentLen, &output, &outlen);
  316. if (result != SASL_OK) {
  317. setError("sasl_decode", result);
  318. return false;
  319. }
  320. clearText = clearText + string(output, outlen);
  321. cursor += segmentLen;
  322. remaining -= segmentLen;
  323. }
  324. return true;
  325. }
  326. bool ClientImpl::getUserId(string& userId)
  327. {
  328. int result;
  329. const char* operName;
  330. result = sasl_getprop(conn, SASL_USERNAME, (const void**) &operName);
  331. if (result != SASL_OK) {
  332. setError("sasl_getprop(SASL_USERNAME)", result);
  333. return false;
  334. }
  335. userId = string(operName);
  336. return true;
  337. }
  338. bool ClientImpl::getSSF(int *ssf)
  339. {
  340. int result = sasl_getprop(conn, SASL_SSF, (const void **)&ssf);
  341. if (result != SASL_OK) {
  342. setError("sasl_getprop(SASL_SSF)", result);
  343. return false;
  344. }
  345. return true;
  346. }
  347. void ClientImpl::getError(string& _error)
  348. {
  349. _error = error;
  350. error.clear();
  351. }
  352. void ClientImpl::addCallback(unsigned long id, void* proc)
  353. {
  354. callbacks[cbIndex].id = id;
  355. callbacks[cbIndex].proc = (int (*)()) proc;
  356. callbacks[cbIndex].context = this;
  357. cbIndex++;
  358. }
  359. void ClientImpl::setError(const string& context, int code, const string& text, const string& text2)
  360. {
  361. stringstream err;
  362. string errtext;
  363. if (text.empty()) {
  364. if (conn) {
  365. errtext = sasl_errdetail(conn);
  366. } else {
  367. errtext = sasl_errstring(code, NULL, NULL);
  368. }
  369. } else {
  370. errtext = text;
  371. }
  372. err << "Error in " << context << " (" << code << ") " << errtext;
  373. if (!text2.empty())
  374. err << " - " << text2;
  375. error = err.str();
  376. }
  377. void ClientImpl::interact(sasl_interact_t* prompt)
  378. {
  379. string output;
  380. char* input;
  381. if (prompt->id == SASL_CB_PASS) {
  382. string ppt(prompt->prompt);
  383. ppt += ": ";
  384. char* pass = getpass(ppt.c_str());
  385. output = string(pass);
  386. } else {
  387. cout << prompt->prompt;
  388. if (prompt->defresult)
  389. cout << " [" << prompt->defresult << "]";
  390. cout << ": ";
  391. cin >> output;
  392. }
  393. prompt->result = output.c_str();
  394. prompt->len = output.length();
  395. }
  396. int ClientImpl::cbName(void *context, int id, const char **result, unsigned *len)
  397. {
  398. ClientImpl* impl = (ClientImpl*) context;
  399. if (id == SASL_CB_USER || (id == SASL_CB_AUTHNAME && impl->authName.empty())) {
  400. *result = impl->userName.c_str();
  401. //*len = impl->userName.length();
  402. } else if (id == SASL_CB_AUTHNAME) {
  403. *result = impl->authName.c_str();
  404. //*len = impl->authName.length();
  405. }
  406. return SASL_OK;
  407. }
  408. int ClientImpl::cbPassword(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
  409. {
  410. ClientImpl* impl = (ClientImpl*) context;
  411. size_t length = impl->password.length();
  412. if (id == SASL_CB_PASS) {
  413. impl->secret->len = length;
  414. ::memcpy(impl->secret->data, impl->password.c_str(), length);
  415. } else
  416. impl->secret->len = 0;
  417. *psecret = impl->secret;
  418. return SASL_OK;
  419. }