12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255 |
- const char crypto_c_id[] =
- "$Id$";
- #include "orconfig.h"
- #ifdef MS_WINDOWS
- #define WIN32_WINNT 0x400
- #define _WIN32_WINNT 0x400
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include <wincrypt.h>
- #endif
- #include <openssl/err.h>
- #include <openssl/rsa.h>
- #include <openssl/pem.h>
- #include <openssl/evp.h>
- #include <openssl/rand.h>
- #include <openssl/opensslv.h>
- #include <openssl/bn.h>
- #include <openssl/dh.h>
- #include <openssl/conf.h>
- #include <openssl/hmac.h>
- #ifdef HAVE_CTYPE_H
- #include <ctype.h>
- #endif
- #ifdef HAVE_UNISTD_H
- #include <unistd.h>
- #endif
- #ifdef HAVE_FCNTL_H
- #include <fcntl.h>
- #endif
- #ifdef HAVE_SYS_FCNTL_H
- #include <sys/fcntl.h>
- #endif
- #define CRYPTO_PRIVATE
- #include "crypto.h"
- #include "log.h"
- #include "aes.h"
- #include "util.h"
- #include "container.h"
- #include "compat.h"
- #if OPENSSL_VERSION_NUMBER < 0x00907000l
- #error "We require openssl >= 0.9.7"
- #endif
- #include <openssl/engine.h>
- #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
- #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
- #ifdef TOR_IS_MULTITHREADED
- static tor_mutex_t **_openssl_mutexes = NULL;
- static int _n_openssl_mutexes = 0;
- #endif
- struct crypto_pk_env_t
- {
- int refs;
- RSA *key;
- };
- struct crypto_cipher_env_t
- {
- char key[CIPHER_KEY_LEN];
- aes_cnt_cipher_t *cipher;
- };
- struct crypto_dh_env_t {
- DH *dh;
- };
- static int setup_openssl_threading(void);
- static int tor_check_dh_key(BIGNUM *bn);
- static INLINE int
- crypto_get_rsa_padding_overhead(int padding)
- {
- switch (padding)
- {
- case RSA_NO_PADDING: return 0;
- case RSA_PKCS1_OAEP_PADDING: return 42;
- case RSA_PKCS1_PADDING: return 11;
- default: tor_assert(0); return -1;
- }
- }
- static INLINE int
- crypto_get_rsa_padding(int padding)
- {
- switch (padding)
- {
- case PK_NO_PADDING: return RSA_NO_PADDING;
- case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
- case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
- default: tor_assert(0); return -1;
- }
- }
- static int _crypto_global_initialized = 0;
- static void
- crypto_log_errors(int severity, const char *doing)
- {
- unsigned long err;
- const char *msg, *lib, *func;
- while ((err = ERR_get_error()) != 0) {
- msg = (const char*)ERR_reason_error_string(err);
- lib = (const char*)ERR_lib_error_string(err);
- func = (const char*)ERR_func_error_string(err);
- if (!msg) msg = "(null)";
- if (!lib) lib = "(null)";
- if (!func) func = "(null)";
- if (doing) {
- log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
- doing, msg, lib, func);
- } else {
- log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
- }
- }
- }
- static void
- log_engine(const char *fn, ENGINE *e)
- {
- if (e) {
- const char *name, *id;
- name = ENGINE_get_name(e);
- id = ENGINE_get_id(e);
- log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
- name?name:"?", id?id:"?", fn);
- } else {
- log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
- }
- }
- int
- crypto_global_init(int useAccel)
- {
- if (!_crypto_global_initialized) {
- ERR_load_crypto_strings();
- OpenSSL_add_all_algorithms();
- _crypto_global_initialized = 1;
- setup_openssl_threading();
-
- if (useAccel < 0) {
- log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
- }
- if (useAccel > 0) {
- log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
- ENGINE_load_builtin_engines();
- if (!ENGINE_register_all_complete())
- return -1;
-
- log_engine("RSA", ENGINE_get_default_RSA());
- log_engine("DH", ENGINE_get_default_DH());
- log_engine("RAND", ENGINE_get_default_RAND());
- log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
- log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
- log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
- }
- }
- return 0;
- }
- void
- crypto_thread_cleanup(void)
- {
- ERR_remove_state(0);
- }
- int
- crypto_global_cleanup(void)
- {
- EVP_cleanup();
- ERR_remove_state(0);
- ERR_free_strings();
- ENGINE_cleanup();
- CONF_modules_unload(1);
- CRYPTO_cleanup_all_ex_data();
- #ifdef TOR_IS_MULTITHREADED
- if (_n_openssl_mutexes) {
- int n = _n_openssl_mutexes;
- tor_mutex_t **ms = _openssl_mutexes;
- int i;
- _openssl_mutexes = NULL;
- _n_openssl_mutexes = 0;
- for (i=0;i<n;++i) {
- tor_mutex_free(ms[i]);
- }
- tor_free(ms);
- }
- #endif
- return 0;
- }
- crypto_pk_env_t *
- _crypto_new_pk_env_rsa(RSA *rsa)
- {
- crypto_pk_env_t *env;
- tor_assert(rsa);
- env = tor_malloc(sizeof(crypto_pk_env_t));
- env->refs = 1;
- env->key = rsa;
- return env;
- }
- crypto_pk_env_t *
- _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
- {
- RSA *rsa;
- if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
- return NULL;
- return _crypto_new_pk_env_rsa(rsa);
- }
- RSA *
- _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
- {
- return env->key;
- }
- EVP_PKEY *
- _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
- {
- RSA *key = NULL;
- EVP_PKEY *pkey = NULL;
- tor_assert(env->key);
- if (private) {
- if (!(key = RSAPrivateKey_dup(env->key)))
- goto error;
- } else {
- if (!(key = RSAPublicKey_dup(env->key)))
- goto error;
- }
- if (!(pkey = EVP_PKEY_new()))
- goto error;
- if (!(EVP_PKEY_assign_RSA(pkey, key)))
- goto error;
- return pkey;
- error:
- if (pkey)
- EVP_PKEY_free(pkey);
- if (key)
- RSA_free(key);
- return NULL;
- }
- DH *
- _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
- {
- return dh->dh;
- }
- crypto_pk_env_t *
- crypto_new_pk_env(void)
- {
- RSA *rsa;
- rsa = RSA_new();
- if (!rsa) return NULL;
- return _crypto_new_pk_env_rsa(rsa);
- }
- void
- crypto_free_pk_env(crypto_pk_env_t *env)
- {
- tor_assert(env);
- if (--env->refs > 0)
- return;
- if (env->key)
- RSA_free(env->key);
- tor_free(env);
- }
- crypto_cipher_env_t *
- crypto_create_init_cipher(const char *key, int encrypt_mode)
- {
- int r;
- crypto_cipher_env_t *crypto = NULL;
- if (! (crypto = crypto_new_cipher_env())) {
- log_warn(LD_CRYPTO, "Unable to allocate crypto object");
- return NULL;
- }
- if (crypto_cipher_set_key(crypto, key)) {
- crypto_log_errors(LOG_WARN, "setting symmetric key");
- goto error;
- }
- if (encrypt_mode)
- r = crypto_cipher_encrypt_init_cipher(crypto);
- else
- r = crypto_cipher_decrypt_init_cipher(crypto);
- if (r)
- goto error;
- return crypto;
- error:
- if (crypto)
- crypto_free_cipher_env(crypto);
- return NULL;
- }
- crypto_cipher_env_t *
- crypto_new_cipher_env(void)
- {
- crypto_cipher_env_t *env;
- env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
- env->cipher = aes_new_cipher();
- return env;
- }
- void
- crypto_free_cipher_env(crypto_cipher_env_t *env)
- {
- tor_assert(env);
- tor_assert(env->cipher);
- aes_free_cipher(env->cipher);
- memset(env, 0, sizeof(crypto_cipher_env_t));
- tor_free(env);
- }
- int
- crypto_pk_generate_key(crypto_pk_env_t *env)
- {
- tor_assert(env);
- if (env->key)
- RSA_free(env->key);
- env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
- if (!env->key) {
- crypto_log_errors(LOG_WARN, "generating RSA key");
- return -1;
- }
- return 0;
- }
- int
- crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
- const char *s)
- {
- BIO *b;
- tor_assert(env);
- tor_assert(s);
-
- b = BIO_new_mem_buf((char*)s, -1);
- if (env->key)
- RSA_free(env->key);
- env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
- BIO_free(b);
- if (!env->key) {
- crypto_log_errors(LOG_WARN, "Error parsing private key");
- return -1;
- }
- return 0;
- }
- int
- crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
- const char *keyfile)
- {
- char *contents;
- int r;
-
- contents = read_file_to_str(keyfile, 0, NULL);
- if (!contents) {
- log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
- return -1;
- }
-
- r = crypto_pk_read_private_key_from_string(env, contents);
- tor_free(contents);
- if (r)
- return -1;
-
- if (crypto_pk_check_key(env) <= 0)
- return -1;
- return 0;
- }
- int
- crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
- size_t *len)
- {
- BUF_MEM *buf;
- BIO *b;
- tor_assert(env);
- tor_assert(env->key);
- tor_assert(dest);
- b = BIO_new(BIO_s_mem());
-
- if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
- crypto_log_errors(LOG_WARN, "writing public key to string");
- BIO_free(b);
- return -1;
- }
- BIO_get_mem_ptr(b, &buf);
- (void)BIO_set_close(b, BIO_NOCLOSE);
- BIO_free(b);
- tor_assert(buf->length >= 0);
- *dest = tor_malloc(buf->length+1);
- memcpy(*dest, buf->data, buf->length);
- (*dest)[buf->length] = 0;
- *len = buf->length;
- BUF_MEM_free(buf);
- return 0;
- }
- int
- crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
- size_t len)
- {
- BIO *b;
- tor_assert(env);
- tor_assert(src);
- tor_assert(len<INT_MAX);
- b = BIO_new(BIO_s_mem());
- BIO_write(b, src, (int)len);
- if (env->key)
- RSA_free(env->key);
- env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
- BIO_free(b);
- if (!env->key) {
- crypto_log_errors(LOG_WARN, "reading public key from string");
- return -1;
- }
- return 0;
- }
- int
- crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
- const char *fname)
- {
- BIO *bio;
- char *cp;
- long len;
- char *s;
- int r;
- tor_assert(PRIVATE_KEY_OK(env));
- if (!(bio = BIO_new(BIO_s_mem())))
- return -1;
- if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
- == 0) {
- crypto_log_errors(LOG_WARN, "writing private key");
- BIO_free(bio);
- return -1;
- }
- len = BIO_get_mem_data(bio, &cp);
- tor_assert(len >= 0);
- s = tor_malloc(len+1);
- memcpy(s, cp, len);
- s[len]='\0';
- r = write_str_to_file(fname, s, 0);
- BIO_free(bio);
- tor_free(s);
- return r;
- }
- int
- crypto_pk_check_key(crypto_pk_env_t *env)
- {
- int r;
- tor_assert(env);
- r = RSA_check_key(env->key);
- if (r <= 0)
- crypto_log_errors(LOG_WARN,"checking RSA key");
- return r;
- }
- int
- crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
- {
- int result;
- if (!a || !b)
- return -1;
- if (!a->key || !b->key)
- return -1;
- tor_assert(PUBLIC_KEY_OK(a));
- tor_assert(PUBLIC_KEY_OK(b));
- result = BN_cmp((a->key)->n, (b->key)->n);
- if (result)
- return result;
- return BN_cmp((a->key)->e, (b->key)->e);
- }
- size_t
- crypto_pk_keysize(crypto_pk_env_t *env)
- {
- tor_assert(env);
- tor_assert(env->key);
- return (size_t) RSA_size(env->key);
- }
- crypto_pk_env_t *
- crypto_pk_dup_key(crypto_pk_env_t *env)
- {
- tor_assert(env);
- tor_assert(env->key);
- env->refs++;
- return env;
- }
- int
- crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
- const char *from, size_t fromlen, int padding)
- {
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen<INT_MAX);
- r = RSA_public_encrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, crypto_get_rsa_padding(padding));
- if (r<0) {
- crypto_log_errors(LOG_WARN, "performing RSA encryption");
- return -1;
- }
- return r;
- }
- int
- crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
- const char *from, size_t fromlen,
- int padding, int warnOnFailure)
- {
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(env->key);
- tor_assert(fromlen<INT_MAX);
- if (!env->key->p)
-
- return -1;
- r = RSA_private_decrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, crypto_get_rsa_padding(padding));
- if (r<0) {
- crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
- "performing RSA decryption");
- return -1;
- }
- return r;
- }
- int
- crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
- const char *from, size_t fromlen)
- {
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- r = RSA_public_decrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, RSA_PKCS1_PADDING);
- if (r<0) {
- crypto_log_errors(LOG_WARN, "checking RSA signature");
- return -1;
- }
- return r;
- }
- int
- crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
- size_t datalen, const char *sig, size_t siglen)
- {
- char digest[DIGEST_LEN];
- char *buf;
- int r;
- tor_assert(env);
- tor_assert(data);
- tor_assert(sig);
- if (crypto_digest(digest,data,datalen)<0) {
- log_warn(LD_BUG, "couldn't compute digest");
- return -1;
- }
- buf = tor_malloc(crypto_pk_keysize(env)+1);
- r = crypto_pk_public_checksig(env,buf,sig,siglen);
- if (r != DIGEST_LEN) {
- log_warn(LD_CRYPTO, "Invalid signature");
- tor_free(buf);
- return -1;
- }
- if (memcmp(buf, digest, DIGEST_LEN)) {
- log_warn(LD_CRYPTO, "Signature mismatched with digest.");
- tor_free(buf);
- return -1;
- }
- tor_free(buf);
- return 0;
- }
- int
- crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
- const char *from, size_t fromlen)
- {
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- if (!env->key->p)
-
- return -1;
- r = RSA_private_encrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, RSA_PKCS1_PADDING);
- if (r<0) {
- crypto_log_errors(LOG_WARN, "generating RSA signature");
- return -1;
- }
- return r;
- }
- int
- crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
- const char *from, size_t fromlen)
- {
- int r;
- char digest[DIGEST_LEN];
- if (crypto_digest(digest,from,fromlen)<0)
- return -1;
- r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
- memset(digest, 0, sizeof(digest));
- return r;
- }
- int
- crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
- char *to,
- const char *from,
- size_t fromlen,
- int padding, int force)
- {
- int overhead, outlen, r;
- size_t pkeylen, symlen;
- crypto_cipher_env_t *cipher = NULL;
- char *buf = NULL;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
- pkeylen = crypto_pk_keysize(env);
- if (padding == PK_NO_PADDING && fromlen < pkeylen)
- return -1;
- if (!force && fromlen+overhead <= pkeylen) {
-
- return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
- }
- cipher = crypto_new_cipher_env();
- if (!cipher) return -1;
- if (crypto_cipher_generate_key(cipher)<0)
- goto err;
-
- if (padding == PK_NO_PADDING)
- cipher->key[0] &= 0x7f;
- if (crypto_cipher_encrypt_init_cipher(cipher)<0)
- goto err;
- buf = tor_malloc(pkeylen+1);
- memcpy(buf, cipher->key, CIPHER_KEY_LEN);
- memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
-
- symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
- outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
- if (outlen!=(int)pkeylen) {
- goto err;
- }
- r = crypto_cipher_encrypt(cipher, to+outlen,
- from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
- if (r<0) goto err;
- memset(buf, 0, pkeylen);
- tor_free(buf);
- crypto_free_cipher_env(cipher);
- tor_assert(outlen+symlen < INT_MAX);
- return (int)(outlen + symlen);
- err:
- if (buf) {
- memset(buf, 0, pkeylen);
- tor_free(buf);
- }
- if (cipher) crypto_free_cipher_env(cipher);
- return -1;
- }
- int
- crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
- char *to,
- const char *from,
- size_t fromlen,
- int padding, int warnOnFailure)
- {
- int outlen, r;
- size_t pkeylen;
- crypto_cipher_env_t *cipher = NULL;
- char *buf = NULL;
- pkeylen = crypto_pk_keysize(env);
- if (fromlen <= pkeylen) {
- return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
- warnOnFailure);
- }
- buf = tor_malloc(pkeylen+1);
- outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
- warnOnFailure);
- if (outlen<0) {
- log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
- "Error decrypting public-key data");
- goto err;
- }
- if (outlen < CIPHER_KEY_LEN) {
- log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
- "No room for a symmetric key");
- goto err;
- }
- cipher = crypto_create_init_cipher(buf, 0);
- if (!cipher) {
- goto err;
- }
- memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
- outlen -= CIPHER_KEY_LEN;
- r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
- if (r<0)
- goto err;
- memset(buf,0,pkeylen);
- tor_free(buf);
- crypto_free_cipher_env(cipher);
- tor_assert(outlen + fromlen < INT_MAX);
- return (int)(outlen + (fromlen-pkeylen));
- err:
- memset(buf,0,pkeylen);
- tor_free(buf);
- if (cipher) crypto_free_cipher_env(cipher);
- return -1;
- }
- int
- crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
- {
- int len;
- unsigned char *buf, *cp;
- len = i2d_RSAPublicKey(pk->key, NULL);
- if (len < 0 || (size_t)len > dest_len)
- return -1;
- cp = buf = tor_malloc(len+1);
- len = i2d_RSAPublicKey(pk->key, &cp);
- if (len < 0) {
- crypto_log_errors(LOG_WARN,"encoding public key");
- tor_free(buf);
- return -1;
- }
-
- memcpy(dest,buf,len);
- tor_free(buf);
- return len;
- }
- crypto_pk_env_t *
- crypto_pk_asn1_decode(const char *str, size_t len)
- {
- RSA *rsa;
- unsigned char *buf;
-
- const unsigned char *cp;
- cp = buf = tor_malloc(len);
- memcpy(buf,str,len);
- rsa = d2i_RSAPublicKey(NULL, &cp, len);
- tor_free(buf);
- if (!rsa) {
- crypto_log_errors(LOG_WARN,"decoding public key");
- return NULL;
- }
- return _crypto_new_pk_env_rsa(rsa);
- }
- int
- crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
- {
- unsigned char *buf, *bufp;
- int len;
- len = i2d_RSAPublicKey(pk->key, NULL);
- if (len < 0)
- return -1;
- buf = bufp = tor_malloc(len+1);
- len = i2d_RSAPublicKey(pk->key, &bufp);
- if (len < 0) {
- crypto_log_errors(LOG_WARN,"encoding public key");
- tor_free(buf);
- return -1;
- }
- if (crypto_digest(digest_out, (char*)buf, len) < 0) {
- tor_free(buf);
- return -1;
- }
- tor_free(buf);
- return 0;
- }
- void
- add_spaces_to_fp(char *out, size_t outlen, const char *in)
- {
- int n = 0;
- char *end = out+outlen;
- while (*in && out<end) {
- *out++ = *in++;
- if (++n == 4 && *in && out<end) {
- n = 0;
- *out++ = ' ';
- }
- }
- tor_assert(out<end);
- *out = '\0';
- }
- int
- crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
- {
- char digest[DIGEST_LEN];
- char hexdigest[HEX_DIGEST_LEN+1];
- if (crypto_pk_get_digest(pk, digest)) {
- return -1;
- }
- base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
- if (add_space) {
- add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
- } else {
- strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
- }
- return 0;
- }
- int
- crypto_pk_check_fingerprint_syntax(const char *s)
- {
- int i;
- for (i = 0; i < FINGERPRINT_LEN; ++i) {
- if ((i%5) == 4) {
- if (!TOR_ISSPACE(s[i])) return 0;
- } else {
- if (!TOR_ISXDIGIT(s[i])) return 0;
- }
- }
- if (s[FINGERPRINT_LEN]) return 0;
- return 1;
- }
- int
- crypto_cipher_generate_key(crypto_cipher_env_t *env)
- {
- tor_assert(env);
- return crypto_rand(env->key, CIPHER_KEY_LEN);
- }
- int
- crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
- {
- tor_assert(env);
- tor_assert(key);
- if (!env->key)
- return -1;
- memcpy(env->key, key, CIPHER_KEY_LEN);
- return 0;
- }
- void
- crypto_cipher_generate_iv(char *iv_out)
- {
- crypto_rand(iv_out, CIPHER_IV_LEN);
- }
- int
- crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
- {
- tor_assert(env);
- tor_assert(iv);
- aes_set_iv(env->cipher, iv);
- return 0;
- }
- const char *
- crypto_cipher_get_key(crypto_cipher_env_t *env)
- {
- return env->key;
- }
- int
- crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
- {
- tor_assert(env);
- aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
- return 0;
- }
- int
- crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
- {
- tor_assert(env);
- aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
- return 0;
- }
- int
- crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
- const char *from, size_t fromlen)
- {
- tor_assert(env);
- tor_assert(env->cipher);
- tor_assert(from);
- tor_assert(fromlen);
- tor_assert(to);
- aes_crypt(env->cipher, from, fromlen, to);
- return 0;
- }
- int
- crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
- const char *from, size_t fromlen)
- {
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- aes_crypt(env->cipher, from, fromlen, to);
- return 0;
- }
- int
- crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
- {
- aes_crypt_inplace(env->cipher, buf, len);
- return 0;
- }
- int
- crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
- char *to, size_t tolen,
- const char *from, size_t fromlen)
- {
- tor_assert(cipher);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- if (fromlen < 1)
- return -1;
- if (tolen < fromlen + CIPHER_IV_LEN)
- return -1;
- crypto_cipher_generate_iv(to);
- if (crypto_cipher_set_iv(cipher, to)<0)
- return -1;
- crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
- return (int)(fromlen + CIPHER_IV_LEN);
- }
- int
- crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
- char *to, size_t tolen,
- const char *from, size_t fromlen)
- {
- tor_assert(cipher);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- if (fromlen <= CIPHER_IV_LEN)
- return -1;
- if (tolen < fromlen - CIPHER_IV_LEN)
- return -1;
- if (crypto_cipher_set_iv(cipher, from)<0)
- return -1;
- crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
- return (int)(fromlen - CIPHER_IV_LEN);
- }
- int
- crypto_digest(char *digest, const char *m, size_t len)
- {
- tor_assert(m);
- tor_assert(digest);
- return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
- }
- struct crypto_digest_env_t {
- SHA_CTX d;
- };
- crypto_digest_env_t *
- crypto_new_digest_env(void)
- {
- crypto_digest_env_t *r;
- r = tor_malloc(sizeof(crypto_digest_env_t));
- SHA1_Init(&r->d);
- return r;
- }
- void
- crypto_free_digest_env(crypto_digest_env_t *digest)
- {
- memset(digest, 0, sizeof(crypto_digest_env_t));
- tor_free(digest);
- }
- void
- crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
- size_t len)
- {
- tor_assert(digest);
- tor_assert(data);
-
- SHA1_Update(&digest->d, (void*)data, len);
- }
- void
- crypto_digest_get_digest(crypto_digest_env_t *digest,
- char *out, size_t out_len)
- {
- unsigned char r[DIGEST_LEN];
- SHA_CTX tmpctx;
- tor_assert(digest);
- tor_assert(out);
- tor_assert(out_len <= DIGEST_LEN);
-
- memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
- SHA1_Final(r, &tmpctx);
- memcpy(out, r, out_len);
- memset(r, 0, sizeof(r));
- }
- crypto_digest_env_t *
- crypto_digest_dup(const crypto_digest_env_t *digest)
- {
- crypto_digest_env_t *r;
- tor_assert(digest);
- r = tor_malloc(sizeof(crypto_digest_env_t));
- memcpy(r,digest,sizeof(crypto_digest_env_t));
- return r;
- }
- void
- crypto_digest_assign(crypto_digest_env_t *into,
- const crypto_digest_env_t *from)
- {
- tor_assert(into);
- tor_assert(from);
- memcpy(into,from,sizeof(crypto_digest_env_t));
- }
- void
- crypto_hmac_sha1(char *hmac_out,
- const char *key, size_t key_len,
- const char *msg, size_t msg_len)
- {
- tor_assert(key_len < INT_MAX);
- tor_assert(msg_len < INT_MAX);
- HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
- (unsigned char*)hmac_out, NULL);
- }
- static BIGNUM *dh_param_p = NULL;
- static BIGNUM *dh_param_g = NULL;
- static void
- init_dh_param(void)
- {
- BIGNUM *p, *g;
- int r;
- if (dh_param_p && dh_param_g)
- return;
- p = BN_new();
- g = BN_new();
- tor_assert(p);
- tor_assert(g);
-
- r = BN_hex2bn(&p,
- "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
- "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
- "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
- "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
- "49286651ECE65381FFFFFFFFFFFFFFFF");
- tor_assert(r);
- r = BN_set_word(g, 2);
- tor_assert(r);
- dh_param_p = p;
- dh_param_g = g;
- }
- #define DH_PRIVATE_KEY_BITS 320
- crypto_dh_env_t *
- crypto_dh_new(void)
- {
- crypto_dh_env_t *res = NULL;
- if (!dh_param_p)
- init_dh_param();
- res = tor_malloc_zero(sizeof(crypto_dh_env_t));
- if (!(res->dh = DH_new()))
- goto err;
- if (!(res->dh->p = BN_dup(dh_param_p)))
- goto err;
- if (!(res->dh->g = BN_dup(dh_param_g)))
- goto err;
- res->dh->length = DH_PRIVATE_KEY_BITS;
- return res;
- err:
- crypto_log_errors(LOG_WARN, "creating DH object");
- if (res && res->dh) DH_free(res->dh);
- if (res) tor_free(res);
- return NULL;
- }
- int
- crypto_dh_get_bytes(crypto_dh_env_t *dh)
- {
- tor_assert(dh);
- return DH_size(dh->dh);
- }
- int
- crypto_dh_generate_public(crypto_dh_env_t *dh)
- {
- again:
- if (!DH_generate_key(dh->dh)) {
- crypto_log_errors(LOG_WARN, "generating DH key");
- return -1;
- }
- if (tor_check_dh_key(dh->dh->pub_key)<0) {
- log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
- "the-universe chances really do happen. Trying again.");
-
- BN_free(dh->dh->pub_key);
- BN_free(dh->dh->priv_key);
- dh->dh->pub_key = dh->dh->priv_key = NULL;
- goto again;
- }
- return 0;
- }
- int
- crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
- {
- int bytes;
- tor_assert(dh);
- if (!dh->dh->pub_key) {
- if (crypto_dh_generate_public(dh)<0)
- return -1;
- }
- tor_assert(dh->dh->pub_key);
- bytes = BN_num_bytes(dh->dh->pub_key);
- tor_assert(bytes >= 0);
- if (pubkey_len < (size_t)bytes) {
- log_warn(LD_CRYPTO,
- "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
- (int) pubkey_len, bytes);
- return -1;
- }
- memset(pubkey, 0, pubkey_len);
- BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
- return 0;
- }
- static int
- tor_check_dh_key(BIGNUM *bn)
- {
- BIGNUM *x;
- char *s;
- tor_assert(bn);
- x = BN_new();
- tor_assert(x);
- if (!dh_param_p)
- init_dh_param();
- BN_set_word(x, 1);
- if (BN_cmp(bn,x)<=0) {
- log_warn(LD_CRYPTO, "DH key must be at least 2.");
- goto err;
- }
- BN_copy(x,dh_param_p);
- BN_sub_word(x, 1);
- if (BN_cmp(bn,x)>=0) {
- log_warn(LD_CRYPTO, "DH key must be at most p-2.");
- goto err;
- }
- BN_free(x);
- return 0;
- err:
- BN_free(x);
- s = BN_bn2hex(bn);
- log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
- OPENSSL_free(s);
- return -1;
- }
- #undef MIN
- #define MIN(a,b) ((a)<(b)?(a):(b))
- ssize_t
- crypto_dh_compute_secret(crypto_dh_env_t *dh,
- const char *pubkey, size_t pubkey_len,
- char *secret_out, size_t secret_bytes_out)
- {
- char *secret_tmp = NULL;
- BIGNUM *pubkey_bn = NULL;
- size_t secret_len=0;
- int result=0;
- tor_assert(dh);
- tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
- tor_assert(pubkey_len < INT_MAX);
- if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
- (int)pubkey_len, NULL)))
- goto error;
- if (tor_check_dh_key(pubkey_bn)<0) {
-
- log_warn(LD_CRYPTO,"Rejected invalid g^x");
- goto error;
- }
- secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
- result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
- if (result < 0) {
- log_warn(LD_CRYPTO,"DH_compute_key() failed.");
- goto error;
- }
- secret_len = result;
-
-
- if (crypto_expand_key_material(secret_tmp, secret_len,
- secret_out, secret_bytes_out)<0)
- goto error;
- secret_len = secret_bytes_out;
- goto done;
- error:
- result = -1;
- done:
- crypto_log_errors(LOG_WARN, "completing DH handshake");
- if (pubkey_bn)
- BN_free(pubkey_bn);
- tor_free(secret_tmp);
- if (result < 0)
- return result;
- else
- return secret_len;
- }
- int
- crypto_expand_key_material(const char *key_in, size_t key_in_len,
- char *key_out, size_t key_out_len)
- {
- int i;
- char *cp, *tmp = tor_malloc(key_in_len+1);
- char digest[DIGEST_LEN];
-
- tor_assert(key_out_len <= DIGEST_LEN*256);
- memcpy(tmp, key_in, key_in_len);
- for (cp = key_out, i=0; cp < key_out+key_out_len;
- ++i, cp += DIGEST_LEN) {
- tmp[key_in_len] = i;
- if (crypto_digest(digest, tmp, key_in_len+1))
- goto err;
- memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
- }
- memset(tmp, 0, key_in_len+1);
- tor_free(tmp);
- memset(digest, 0, sizeof(digest));
- return 0;
- err:
- memset(tmp, 0, key_in_len+1);
- tor_free(tmp);
- memset(digest, 0, sizeof(digest));
- return -1;
- }
- void
- crypto_dh_free(crypto_dh_env_t *dh)
- {
- tor_assert(dh);
- tor_assert(dh->dh);
- DH_free(dh->dh);
- tor_free(dh);
- }
- #define ADD_ENTROPY 32
- #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
- #define RAND_POLL_IS_SAFE \
- ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
- OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
- (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
- #define USE_RAND_POLL (HAVE_RAND_POLL && RAND_POLL_IS_SAFE)
- int
- crypto_seed_rng(int startup)
- {
- char buf[ADD_ENTROPY];
- int rand_poll_status = 0;
-
- #ifdef MS_WINDOWS
- static int provider_set = 0;
- static HCRYPTPROV provider;
- #else
- static const char *filenames[] = {
- "/dev/srandom", "/dev/urandom", "/dev/random", NULL
- };
- int fd, i;
- size_t n;
- #endif
- #if HAVE_RAND_POLL
-
- if (startup || RAND_POLL_IS_SAFE) {
- rand_poll_status = RAND_poll();
- if (rand_poll_status == 0)
- log_warn(LD_CRYPTO, "RAND_poll() failed.");
- }
- #endif
- #ifdef MS_WINDOWS
- if (!provider_set) {
- if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
- CRYPT_VERIFYCONTEXT)) {
- if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
- log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
- return rand_poll_status ? 0 : -1;
- }
- }
- provider_set = 1;
- }
- if (!CryptGenRandom(provider, sizeof(buf), buf)) {
- log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
- return rand_poll_status ? 0 : -1;
- }
- RAND_seed(buf, sizeof(buf));
- memset(buf, 0, sizeof(buf));
- return 0;
- #else
- for (i = 0; filenames[i]; ++i) {
- fd = open(filenames[i], O_RDONLY, 0);
- if (fd<0) continue;
- log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
- n = read_all(fd, buf, sizeof(buf), 0);
- close(fd);
- if (n != sizeof(buf)) {
- log_warn(LD_CRYPTO,
- "Error reading from entropy source (read only %lu bytes).",
- (unsigned long)n);
- return -1;
- }
- RAND_seed(buf, (int)sizeof(buf));
- memset(buf, 0, sizeof(buf));
- return 0;
- }
- log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
- return rand_poll_status ? 0 : -1;
- #endif
- }
- int
- crypto_rand(char *to, size_t n)
- {
- int r;
- tor_assert(n < INT_MAX);
- tor_assert(to);
- r = RAND_bytes((unsigned char*)to, (int)n);
- if (r == 0)
- crypto_log_errors(LOG_WARN, "generating random data");
- return (r == 1) ? 0 : -1;
- }
- int
- crypto_rand_int(unsigned int max)
- {
- unsigned int val;
- unsigned int cutoff;
- tor_assert(max < UINT_MAX);
- tor_assert(max > 0);
-
- cutoff = UINT_MAX - (UINT_MAX%max);
- while (1) {
- crypto_rand((char*)&val, sizeof(val));
- if (val < cutoff)
- return val % max;
- }
- }
- uint64_t
- crypto_rand_uint64(uint64_t max)
- {
- uint64_t val;
- uint64_t cutoff;
- tor_assert(max < UINT64_MAX);
- tor_assert(max > 0);
-
- cutoff = UINT64_MAX - (UINT64_MAX%max);
- while (1) {
- crypto_rand((char*)&val, sizeof(val));
- if (val < cutoff)
- return val % max;
- }
- }
- char *
- crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
- const char *suffix)
- {
- char *result, *rand_bytes;
- int randlen, rand_bytes_len;
- size_t resultlen, prefixlen;
- tor_assert(max_rand_len >= min_rand_len);
- randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
- prefixlen = strlen(prefix);
- resultlen = prefixlen + strlen(suffix) + randlen + 16;
- rand_bytes_len = ((randlen*5)+7)/8;
- if (rand_bytes_len % 5)
- rand_bytes_len += 5 - (rand_bytes_len%5);
- rand_bytes = tor_malloc(rand_bytes_len);
- crypto_rand(rand_bytes, rand_bytes_len);
- result = tor_malloc(resultlen);
- memcpy(result, prefix, prefixlen);
- base32_encode(result+prefixlen, resultlen-prefixlen,
- rand_bytes, rand_bytes_len);
- tor_free(rand_bytes);
- strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
- return result;
- }
- void *
- smartlist_choose(const smartlist_t *sl)
- {
- int len = smartlist_len(sl);
- if (len)
- return smartlist_get(sl,crypto_rand_int(len));
- return NULL;
- }
- void
- smartlist_shuffle(smartlist_t *sl)
- {
- int i;
-
- for (i = smartlist_len(sl)-1; i > 0; --i) {
- int j = crypto_rand_int(i+1);
- smartlist_swap(sl, i, j);
- }
- }
- int
- base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
- {
-
- EVP_ENCODE_CTX ctx;
- int len, ret;
- tor_assert(srclen < INT_MAX);
-
- if (destlen < ((srclen/48)+1)*66)
- return -1;
- if (destlen > SIZE_T_CEILING)
- return -1;
- EVP_EncodeInit(&ctx);
- EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
- (unsigned char*)src, (int)srclen);
- EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
- ret += len;
- return ret;
- }
- #define X 255
- #define SP 64
- #define PAD 65
- static const uint8_t base64_decode_table[256] = {
- X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
- X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
- X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
- 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
- };
- int
- base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
- {
- #ifdef USE_OPENSSL_BASE64
- EVP_ENCODE_CTX ctx;
- int len, ret;
-
- if (destlen < ((srclen/64)+1)*49)
- return -1;
- if (destlen > SIZE_T_CEILING)
- return -1;
- EVP_DecodeInit(&ctx);
- EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
- (unsigned char*)src, srclen);
- EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
- ret += len;
- return ret;
- #else
- const char *eos = src+srclen;
- uint32_t n=0;
- int n_idx=0;
- char *dest_orig = dest;
-
- if (destlen < (srclen*3)/4)
- return -1;
- if (destlen > SIZE_T_CEILING)
- return -1;
-
- for ( ; src < eos; ++src) {
- unsigned char c = (unsigned char) *src;
- uint8_t v = base64_decode_table[c];
- switch (v) {
- case X:
-
- return -1;
- case SP:
-
- continue;
- case PAD:
-
- goto end_of_loop;
- default:
-
- n = (n<<6) | v;
- if ((++n_idx) == 4) {
-
- *dest++ = (n>>16);
- *dest++ = (n>>8) & 0xff;
- *dest++ = (n) & 0xff;
- n_idx = 0;
- n = 0;
- }
- }
- }
- end_of_loop:
-
- switch (n_idx) {
- case 0:
- default:
-
- break;
- case 1:
-
- return -1;
- case 2:
-
- *dest++ = n >> 4;
- break;
- case 3:
-
- *dest++ = n >> 10;
- *dest++ = n >> 2;
- }
- tor_assert((dest-dest_orig) <= (ssize_t)destlen);
- tor_assert((dest-dest_orig) <= INT_MAX);
- return (int)(dest-dest_orig);
- #endif
- }
- #undef X
- #undef SP
- #undef NIL
- int
- digest_to_base64(char *d64, const char *digest)
- {
- char buf[256];
- base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
- buf[BASE64_DIGEST_LEN] = '\0';
- memcpy(d64, buf, BASE64_DIGEST_LEN+1);
- return 0;
- }
- int
- digest_from_base64(char *digest, const char *d64)
- {
- #ifdef USE_OPENSSL_BASE64
- char buf_in[BASE64_DIGEST_LEN+3];
- char buf[256];
- if (strlen(d64) != BASE64_DIGEST_LEN)
- return -1;
- memcpy(buf_in, d64, BASE64_DIGEST_LEN);
- memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
- if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
- return -1;
- memcpy(digest, buf, DIGEST_LEN);
- return 0;
- #else
- if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
- return 0;
- else
- return -1;
- #endif
- }
- void
- base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
- {
- unsigned int i, bit, v, u;
- size_t nbits = srclen * 8;
- tor_assert((nbits%5) == 0);
- tor_assert((nbits/5)+1 <= destlen);
- tor_assert(destlen < SIZE_T_CEILING);
- for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
-
- v = ((uint8_t)src[bit/8]) << 8;
- if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
-
- u = (v >> (11-(bit%8))) & 0x1F;
- dest[i] = BASE32_CHARS[u];
- }
- dest[i] = '\0';
- }
- int
- base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
- {
-
- unsigned int i, j, bit;
- size_t nbits;
- char *tmp;
- nbits = srclen * 5;
- tor_assert((nbits%8) == 0);
- tor_assert((nbits/8) <= destlen);
- tor_assert(destlen < SIZE_T_CEILING);
-
- tmp = tor_malloc_zero(srclen);
- for (j = 0; j < srclen; ++j) {
- if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
- else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
- else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
- else {
- log_warn(LD_BUG, "illegal character in base32 encoded string");
- tor_free(tmp);
- return -1;
- }
- }
-
- for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
- switch (bit % 40) {
- case 0:
- dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
- (((uint8_t)tmp[(bit/5)+1]) >> 2);
- break;
- case 8:
- dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
- (((uint8_t)tmp[(bit/5)+1]) << 1) +
- (((uint8_t)tmp[(bit/5)+2]) >> 4);
- break;
- case 16:
- dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
- (((uint8_t)tmp[(bit/5)+1]) >> 1);
- break;
- case 24:
- dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
- (((uint8_t)tmp[(bit/5)+1]) << 2) +
- (((uint8_t)tmp[(bit/5)+2]) >> 3);
- break;
- case 32:
- dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
- ((uint8_t)tmp[(bit/5)+1]);
- break;
- }
- }
- memset(tmp, 0, srclen);
- tor_free(tmp);
- tmp = NULL;
- return 0;
- }
- void
- secret_to_key(char *key_out, size_t key_out_len, const char *secret,
- size_t secret_len, const char *s2k_specifier)
- {
- crypto_digest_env_t *d;
- uint8_t c;
- size_t count, tmplen;
- char *tmp;
- tor_assert(key_out_len < SIZE_T_CEILING);
- #define EXPBIAS 6
- c = s2k_specifier[8];
- count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
- #undef EXPBIAS
- tor_assert(key_out_len <= DIGEST_LEN);
- d = crypto_new_digest_env();
- tmplen = 8+secret_len;
- tmp = tor_malloc(tmplen);
- memcpy(tmp,s2k_specifier,8);
- memcpy(tmp+8,secret,secret_len);
- secret_len += 8;
- while (count) {
- if (count >= secret_len) {
- crypto_digest_add_bytes(d, tmp, secret_len);
- count -= secret_len;
- } else {
- crypto_digest_add_bytes(d, tmp, count);
- count = 0;
- }
- }
- crypto_digest_get_digest(d, key_out, key_out_len);
- memset(tmp, 0, tmplen);
- tor_free(tmp);
- crypto_free_digest_env(d);
- }
- #ifdef TOR_IS_MULTITHREADED
- static void
- _openssl_locking_cb(int mode, int n, const char *file, int line)
- {
- (void)file;
- (void)line;
- if (!_openssl_mutexes)
-
- return;
- if (mode & CRYPTO_LOCK)
- tor_mutex_acquire(_openssl_mutexes[n]);
- else
- tor_mutex_release(_openssl_mutexes[n]);
- }
- static int
- setup_openssl_threading(void)
- {
- int i;
- int n = CRYPTO_num_locks();
- _n_openssl_mutexes = n;
- _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
- for (i=0; i < n; ++i)
- _openssl_mutexes[i] = tor_mutex_new();
- CRYPTO_set_locking_callback(_openssl_locking_cb);
- CRYPTO_set_id_callback(tor_get_thread_id);
- return 0;
- }
- #else
- static int
- setup_openssl_threading(void)
- {
- return 0;
- }
- #endif
|