pbe.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  3. * Copyright (C) 2015 Red Hat, Inc.
  4. * All rights reserved.
  5. *
  6. * License: GPL (version 3 or any later version).
  7. * See LICENSE for details.
  8. * END COPYRIGHT BLOCK **/
  9. #ifdef HAVE_CONFIG_H
  10. #include <config.h>
  11. #endif
  12. #include <string.h>
  13. #include <stdio.h>
  14. #include <ldap.h>
  15. #include <nss.h>
  16. #include <svrcore.h>
  17. #define NEED_TOK_PBE /* see slap.h - defines tokPBE and ptokPBE */
  18. #include "rever.h"
  19. struct pk11MechItem
  20. {
  21. CK_MECHANISM_TYPE type;
  22. const char *mechName;
  23. };
  24. static const struct pk11MechItem DESmech = {CKM_DES_CBC, "DES CBC encryption"};
  25. static const struct pk11MechItem AESmech = {CKM_AES_CBC, "AES CBC encryption"};
  26. static Slapi_Mutex *pbe_lock = NULL;
  27. struct pk11ContextStore
  28. {
  29. PK11SlotInfo *slot;
  30. const struct pk11MechItem *mech;
  31. PK11SymKey *key;
  32. SECItem *params;
  33. int length;
  34. unsigned char *crypt;
  35. char *algid_base64;
  36. };
  37. /*
  38. * der_algid converting functions:
  39. *
  40. * SECStatus ATOB_ConvertAsciiToItem(SECItem *binary_item, const char *ascii);
  41. * char * BTOA_ConvertItemToAscii(SECItem *binary_item);
  42. *
  43. */
  44. static int encode_path(char *inPlain, char **outCipher, char *path, int mech);
  45. static int decode_path(char *inCipher, char **outPlain, char *path, int mech, char *algid);
  46. static SVRCOREError genKey(struct pk11ContextStore **out, char *path, int mech, PRArenaPool *arena, char *algid);
  47. static SVRCOREError cryptPassword(struct pk11ContextStore *store, char *clear, unsigned char **out);
  48. static SVRCOREError decryptPassword(struct pk11ContextStore *store, unsigned char *cipher, char **out, int len);
  49. static void freePBE(struct pk11ContextStore *store);
  50. void
  51. init_pbe_plugin()
  52. {
  53. if (!pbe_lock) {
  54. pbe_lock = slapi_new_mutex();
  55. }
  56. }
  57. int
  58. encode(char *inPlain, char **outCipher, int mech)
  59. {
  60. return encode_path(inPlain, outCipher, NULL, mech);
  61. }
  62. static int
  63. encode_path(char *inPlain, char **outCipher, char *path, int mech)
  64. {
  65. struct pk11ContextStore *context = NULL;
  66. PRArenaPool *arena = NULL;
  67. unsigned char *cipher = NULL;
  68. char *tmp = NULL;
  69. char *base = NULL;
  70. int len = 0;
  71. int err;
  72. *outCipher = NULL;
  73. err = 1;
  74. if (genKey(&context, path, mech, arena, NULL) == SVRCORE_Success) {
  75. /* Try an encryption */
  76. if (cryptPassword(context, inPlain, &cipher) == SVRCORE_Success) {
  77. base = BTOA_DataToAscii(cipher, context->length);
  78. if (base != NULL) {
  79. const char *scheme;
  80. if (mech == AES_MECH) {
  81. scheme = AES_REVER_SCHEME_NAME;
  82. len = 3 + strlen(scheme) + strlen(context->algid_base64) + strlen(base) + 1;
  83. if ((tmp = slapi_ch_malloc(len))) {
  84. /*
  85. * {AES-<BASE64_ALG_ID>}<ENCODED PASSWORD>
  86. */
  87. sprintf(tmp, "%c%s-%s%c%s", PWD_HASH_PREFIX_START, scheme,
  88. context->algid_base64, PWD_HASH_PREFIX_END, base);
  89. }
  90. } else {
  91. /* Old school DES */
  92. scheme = DES_REVER_SCHEME_NAME;
  93. if ((tmp = slapi_ch_malloc(3 + strlen(scheme) + strlen(base)))) {
  94. sprintf(tmp, "%c%s%c%s", PWD_HASH_PREFIX_START, scheme,
  95. PWD_HASH_PREFIX_END, base);
  96. }
  97. }
  98. if (tmp != NULL) {
  99. *outCipher = tmp;
  100. tmp = NULL;
  101. err = 0;
  102. }
  103. PORT_Free(base);
  104. }
  105. }
  106. }
  107. freePBE(context);
  108. return (err);
  109. }
  110. int
  111. decode(char *inCipher, char **outPlain, int mech, char *algid)
  112. {
  113. return decode_path(inCipher, outPlain, NULL, mech, algid);
  114. }
  115. static int
  116. decode_path(char *inCipher, char **outPlain, char *path, int mech, char *algid)
  117. {
  118. struct pk11ContextStore *context = NULL;
  119. PRArenaPool *arena = NULL;
  120. unsigned char *base = NULL;
  121. char *plain = NULL;
  122. int err;
  123. int len = 0;
  124. *outPlain = NULL;
  125. err = 1;
  126. if (genKey(&context, path, mech, arena, algid) == SVRCORE_Success) {
  127. /* it seems that there is memory leak in that function: bug 400170 */
  128. base = ATOB_AsciiToData(inCipher, (unsigned int *)&len);
  129. if (base != NULL) {
  130. if (decryptPassword(context, base, &plain, len) == SVRCORE_Success) {
  131. *outPlain = plain;
  132. err = 0;
  133. }
  134. }
  135. }
  136. slapi_ch_free_string(&algid);
  137. PORT_Free(base);
  138. PORT_FreeArena(arena, PR_TRUE);
  139. freePBE(context);
  140. return (err);
  141. }
  142. static void
  143. freePBE(struct pk11ContextStore *store)
  144. {
  145. if (store) {
  146. if (store->slot)
  147. slapd_pk11_freeSlot(store->slot);
  148. if (store->key)
  149. slapd_pk11_freeSymKey(store->key);
  150. if (store->params)
  151. SECITEM_FreeItem(store->params, PR_TRUE);
  152. slapi_ch_free((void **)&store->crypt);
  153. slapi_ch_free_string(&store->algid_base64);
  154. slapi_ch_free((void **)&store);
  155. }
  156. }
  157. static SVRCOREError
  158. genKey(struct pk11ContextStore **out, char *path, int mech, PRArenaPool *arena, char *alg)
  159. {
  160. SVRCOREError err = SVRCORE_Success;
  161. struct pk11ContextStore *store = NULL;
  162. SECItem *pwitem = NULL;
  163. SECItem *result = NULL;
  164. SECItem *salt = NULL;
  165. SECItem der_algid = {0};
  166. SECAlgorithmID *algid = NULL;
  167. SECOidTag algoid;
  168. CK_MECHANISM pbeMech;
  169. CK_MECHANISM cryptoMech;
  170. /* Have to use long form init due to internal structs */
  171. SECAlgorithmID my_algid = {{0}, {0}};
  172. char *configdir = NULL;
  173. char *der_ascii = NULL;
  174. char *iv = NULL;
  175. int free_it = 0;
  176. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  177. store = (struct pk11ContextStore *)slapi_ch_calloc(1, sizeof(*store));
  178. if (store == NULL) {
  179. err = SVRCORE_NoMemory_Error;
  180. goto done;
  181. }
  182. *out = store;
  183. store->slot = slapd_pk11_getInternalKeySlot();
  184. if (store->slot == NULL) {
  185. err = SVRCORE_NoSuchToken_Error;
  186. goto done;
  187. }
  188. /* Generate a key and parameters to do the encryption */
  189. if (mech == AES_MECH) {
  190. store->mech = &AESmech;
  191. algoid = SEC_OID_AES_256_CBC;
  192. } else {
  193. store->mech = &DESmech;
  194. algoid = SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC;
  195. }
  196. /* Generate a unique id, used as salt for the key generation */
  197. if (path == NULL) {
  198. configdir = config_get_configdir();
  199. if (configdir == NULL) {
  200. err = SVRCORE_System_Error;
  201. goto done;
  202. }
  203. } else {
  204. configdir = slapi_ch_strdup(path);
  205. }
  206. if (slapi_uniqueIDGenerateFromNameString(&iv, NULL, configdir, strlen(configdir)) != UID_SUCCESS) {
  207. err = SVRCORE_System_Error;
  208. goto done;
  209. }
  210. pwitem = (SECItem *)PORT_Alloc(sizeof(SECItem));
  211. if (pwitem == NULL) {
  212. err = SVRCORE_NoMemory_Error;
  213. goto done;
  214. }
  215. pwitem->type = siBuffer;
  216. pwitem->data = (unsigned char *)PORT_Alloc(strlen(iv) + 1);
  217. if (pwitem->data == NULL) {
  218. err = SVRCORE_NoMemory_Error;
  219. goto done;
  220. }
  221. strcpy((char *)pwitem->data, iv);
  222. pwitem->len = strlen(iv) + 1;
  223. salt = (SECItem *)PORT_Alloc(sizeof(SECItem));
  224. if (salt == NULL) {
  225. err = SVRCORE_NoMemory_Error;
  226. goto done;
  227. }
  228. salt->type = siBuffer;
  229. salt->data = (unsigned char *)PORT_Alloc(strlen(iv) + 1);
  230. if (salt->data == NULL) {
  231. err = SVRCORE_NoMemory_Error;
  232. goto done;
  233. }
  234. strcpy((char *)salt->data, iv);
  235. salt->len = strlen(iv) + 1;
  236. if (!alg) {
  237. /*
  238. * This is DES, or we are encoding AES - the process is the same.
  239. */
  240. algid = slapd_pk11_createPBEAlgorithmID(algoid, 2, salt);
  241. free_it = 1; /* we need to free this algid */
  242. /*
  243. * The following is only need for AES - we need to store
  244. * algid for future decodings(unlike with DES). So convert
  245. * algid to its DER encoding. Then convert the DER to ascii,
  246. * and finally convert the DER ascii to base64 so we can store
  247. * it in the cipher prefix.
  248. */
  249. SEC_ASN1EncodeItem(arena, &der_algid, algid, SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
  250. der_ascii = BTOA_ConvertItemToAscii(&der_algid);
  251. store->algid_base64 = PL_Base64Encode(der_ascii, strlen(der_ascii), NULL);
  252. slapi_ch_free_string(&der_ascii);
  253. } else {
  254. /*
  255. * We are decoding AES - use the supplied algid
  256. */
  257. /* Decode the base64 der encoding */
  258. der_ascii = PL_Base64Decode(alg, strlen(alg), NULL);
  259. /* convert the der ascii to the SEC item */
  260. ATOB_ConvertAsciiToItem(&der_algid, der_ascii);
  261. SEC_ASN1DecodeItem(arena, &my_algid, SEC_ASN1_GET(SECOID_AlgorithmIDTemplate), &der_algid);
  262. SECITEM_FreeItem(&der_algid, PR_FALSE);
  263. algid = &my_algid;
  264. slapi_ch_free_string(&der_ascii);
  265. }
  266. slapi_lock_mutex(pbe_lock);
  267. store->key = slapd_pk11_pbeKeyGen(store->slot, algid, pwitem, 0, 0);
  268. if (store->key == 0) {
  269. slapi_unlock_mutex(pbe_lock);
  270. err = SVRCORE_System_Error;
  271. goto done;
  272. }
  273. slapi_unlock_mutex(pbe_lock);
  274. if (mech == AES_MECH) {
  275. cryptoMech.mechanism = PK11_GetPBECryptoMechanism(algid, &store->params, pwitem);
  276. if (cryptoMech.mechanism == CKM_INVALID_MECHANISM) {
  277. err = SVRCORE_System_Error;
  278. goto done;
  279. }
  280. } else {
  281. /* DES */
  282. pbeMech.mechanism = slapd_pk11_algtagToMechanism(algoid);
  283. result = slapd_pk11_paramFromAlgid(algid);
  284. if (result) {
  285. pbeMech.pParameter = result->data;
  286. pbeMech.ulParameterLen = result->len;
  287. }
  288. if (slapd_pk11_mapPBEMechanismToCryptoMechanism(&pbeMech, &cryptoMech, pwitem,
  289. PR_FALSE) != CKR_OK) {
  290. err = SVRCORE_System_Error;
  291. goto done;
  292. }
  293. store->params = (SECItem *)PORT_Alloc(sizeof(SECItem));
  294. if (store->params == NULL) {
  295. err = SVRCORE_System_Error;
  296. goto done;
  297. }
  298. store->params->type = store->mech->type;
  299. store->params->data = (unsigned char *)PORT_Alloc(cryptoMech.ulParameterLen);
  300. if (store->params->data == NULL) {
  301. err = SVRCORE_System_Error;
  302. goto done;
  303. }
  304. memcpy(store->params->data, (unsigned char *)cryptoMech.pParameter, cryptoMech.ulParameterLen);
  305. store->params->len = cryptoMech.ulParameterLen;
  306. PORT_Free(cryptoMech.pParameter);
  307. }
  308. done:
  309. SECITEM_FreeItem(result, PR_TRUE);
  310. SECITEM_FreeItem(pwitem, PR_TRUE);
  311. SECITEM_FreeItem(salt, PR_TRUE);
  312. if (free_it) {
  313. secoid_destroyAlgorithmID(algid, PR_TRUE);
  314. }
  315. slapi_ch_free_string(&configdir);
  316. slapi_ch_free_string(&iv);
  317. if (arena) {
  318. PORT_FreeArena(arena, PR_TRUE);
  319. }
  320. return (err);
  321. }
  322. static SVRCOREError
  323. decryptPassword(struct pk11ContextStore *store, unsigned char *cipher, char **out, int len)
  324. {
  325. SVRCOREError err = SVRCORE_Success;
  326. unsigned char *plain = NULL;
  327. unsigned char *cipher_with_padding = NULL;
  328. SECStatus rv;
  329. PK11Context *ctx = NULL;
  330. int outLen = 0;
  331. int blocksize = 0;
  332. blocksize = slapd_pk11_getBlockSize(store->mech->type, 0);
  333. store->length = len;
  334. /*
  335. * store->length is the max. length of the returned clear text -
  336. * must be >= length of crypted bytes - also must be a multiple
  337. * of blocksize
  338. */
  339. if (blocksize != 0) {
  340. store->length += blocksize - (store->length % blocksize);
  341. }
  342. /* plain will hold the returned clear text */
  343. plain = (unsigned char *)slapi_ch_calloc(sizeof(unsigned char),
  344. store->length + 1);
  345. if (!plain) {
  346. err = SVRCORE_NoMemory_Error;
  347. goto done;
  348. }
  349. /*
  350. * create a buffer holding the original cipher bytes, padded with
  351. * zeros to a multiple of blocksize - do not need +1 since buffer is not
  352. * a string
  353. */
  354. cipher_with_padding = (unsigned char *)slapi_ch_calloc(sizeof(unsigned char),
  355. store->length);
  356. if (!cipher_with_padding) {
  357. err = SVRCORE_NoMemory_Error;
  358. goto done;
  359. }
  360. memcpy(cipher_with_padding, cipher, len);
  361. ctx = slapd_pk11_createContextBySymKey(store->mech->type, CKA_DECRYPT,
  362. store->key, store->params);
  363. if (!ctx) {
  364. err = SVRCORE_System_Error;
  365. goto done;
  366. }
  367. /*
  368. * Warning - there is a purify UMR in the NSS des code - you may see it when the
  369. * password is not a multiple of 8 bytes long
  370. */
  371. rv = slapd_pk11_cipherOp(ctx, plain, &outLen, store->length,
  372. cipher_with_padding, store->length);
  373. if (rv) {
  374. err = SVRCORE_System_Error;
  375. }
  376. rv = slapd_pk11_finalize(ctx);
  377. /*
  378. * We must do the finalize, but we only want to set the err return
  379. * code if it is not already set
  380. */
  381. if (rv && (SVRCORE_Success == err))
  382. err = SVRCORE_System_Error;
  383. done:
  384. if (err == SVRCORE_Success) {
  385. *out = (char *)plain;
  386. } else {
  387. slapi_ch_free((void **)&plain);
  388. }
  389. slapi_ch_free((void **)&cipher_with_padding);
  390. /* We should free the PK11Context... Something like : */
  391. if (ctx) {
  392. slapd_pk11_destroyContext(ctx, PR_TRUE);
  393. }
  394. return err;
  395. }
  396. static SVRCOREError
  397. cryptPassword(struct pk11ContextStore *store, char *clear, unsigned char **out)
  398. {
  399. SVRCOREError err = SVRCORE_Success;
  400. SECStatus rv;
  401. PK11Context *ctx = NULL;
  402. unsigned char *clear_with_padding = NULL; /* clear with padding up to blocksize */
  403. int blocksize = 0;
  404. int outLen = 0;
  405. blocksize = slapd_pk11_getBlockSize(store->mech->type, 0);
  406. store->length = strlen(clear);
  407. /*
  408. * The size of the clear text buffer passed to the encryption functions
  409. * must be a multiple of blocksize (usually 8 bytes) - we allocate a buffer
  410. * of this size, copy the clear text password into it, and pad the rest with
  411. * zeros.
  412. */
  413. if (blocksize != 0) {
  414. store->length += blocksize - (store->length % blocksize);
  415. }
  416. /*
  417. * store->crypt will hold the crypted password - it must be >= clear length
  418. * store->crypt is freed in NSS; let's not use slapi_ch_calloc
  419. */
  420. store->crypt = (unsigned char *)calloc(sizeof(unsigned char),
  421. store->length + 1);
  422. if (!store->crypt) {
  423. err = SVRCORE_NoMemory_Error;
  424. goto done;
  425. }
  426. /* Create a buffer big enough to hold the clear text password and padding */
  427. clear_with_padding = (unsigned char *)slapi_ch_calloc(sizeof(unsigned char),
  428. store->length + 1);
  429. if (!clear_with_padding) {
  430. err = SVRCORE_NoMemory_Error;
  431. goto done;
  432. }
  433. /*
  434. * Copy the clear text password into the buffer - the calloc insures the
  435. * remainder is zero padded .
  436. */
  437. strcpy((char *)clear_with_padding, clear);
  438. ctx = slapd_pk11_createContextBySymKey(store->mech->type, CKA_ENCRYPT,
  439. store->key, store->params);
  440. if (!ctx) {
  441. err = SVRCORE_System_Error;
  442. goto done;
  443. }
  444. rv = slapd_pk11_cipherOp(ctx, store->crypt, &outLen, store->length,
  445. clear_with_padding, store->length);
  446. if (rv) {
  447. err = SVRCORE_System_Error;
  448. }
  449. rv = slapd_pk11_finalize(ctx);
  450. /*
  451. * We must do the finalize, but we only want to set the err return
  452. * code if it is not already set
  453. */
  454. if (rv && (SVRCORE_Success == err)) {
  455. err = SVRCORE_System_Error;
  456. }
  457. done:
  458. if (err == SVRCORE_Success) {
  459. *out = store->crypt;
  460. }
  461. slapi_ch_free((void **)&clear_with_padding);
  462. /* We should free the PK11Context... Something like : */
  463. if (ctx) {
  464. slapd_pk11_destroyContext(ctx, PR_TRUE);
  465. }
  466. return err;
  467. }
  468. /*
  469. * The UUID name based generator was broken on x86 platforms. We use
  470. * this to generate the password encryption key. During migration,
  471. * we have to fix this so we can use the fixed generator. The env.
  472. * var USE_BROKEN_UUID tells the uuid generator to use the old
  473. * broken method to create the UUID. That will allow us to decrypt
  474. * the password to the correct clear text, then we can turn off
  475. * the broken method and use the fixed method to encrypt the
  476. * password.
  477. */
  478. char *
  479. migrateCredentials(char *oldpath, char *newpath, char *oldcred)
  480. {
  481. static char *useBrokenUUID = "USE_BROKEN_UUID=1";
  482. static char *disableBrokenUUID = "USE_BROKEN_UUID=0";
  483. char *plain = NULL;
  484. char *cipher = NULL;
  485. init_pbe_plugin();
  486. slapd_pk11_configurePKCS11(NULL, NULL, tokPBE, ptokPBE, NULL, NULL, NULL, NULL, 0, 0);
  487. NSS_NoDB_Init(NULL);
  488. if (getenv("MIGRATE_BROKEN_PWD")) {
  489. putenv(useBrokenUUID);
  490. }
  491. if (decode_path(oldcred, &plain, oldpath, DES_MECH, NULL) == 0) {
  492. if (getenv("MIGRATE_BROKEN_PWD")) {
  493. putenv(disableBrokenUUID);
  494. }
  495. if (encode_path(plain, &cipher, newpath, AES_MECH) != 0) {
  496. return (NULL);
  497. } else {
  498. return (cipher);
  499. }
  500. } else {
  501. return (NULL);
  502. }
  503. }