openssl.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  1. /*
  2. * OpenConnect (SSL + DTLS) VPN client
  3. *
  4. * Copyright © 2008-2015 Intel Corporation.
  5. *
  6. * Author: David Woodhouse <dwmw2@infradead.org>
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public License
  10. * version 2.1, as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. */
  17. #include <config.h>
  18. #include "openconnect-internal.h"
  19. #include <openssl/crypto.h>
  20. #include <openssl/ssl.h>
  21. #include <openssl/err.h>
  22. #include <openssl/engine.h>
  23. #include <openssl/evp.h>
  24. #include <openssl/rand.h>
  25. #include <openssl/pkcs12.h>
  26. #include <openssl/x509v3.h>
  27. #include <openssl/x509.h>
  28. #include <openssl/bio.h>
  29. #include <openssl/ui.h>
  30. #include <openssl/rsa.h>
  31. #include <sys/types.h>
  32. #include <errno.h>
  33. #include <string.h>
  34. #include <ctype.h>
  35. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  36. #define X509_up_ref(x) CRYPTO_add(&(x)->references, 1, CRYPTO_LOCK_X509)
  37. #define X509_get0_notAfter(x) X509_get_notAfter(x)
  38. #define EVP_MD_CTX_new EVP_MD_CTX_create
  39. #define EVP_MD_CTX_free EVP_MD_CTX_destroy
  40. #define X509_STORE_CTX_get0_chain(ctx) ((ctx)->chain)
  41. #define X509_STORE_CTX_get0_untrusted(ctx) ((ctx)->untrusted)
  42. #define X509_STORE_CTX_get0_cert(ctx) ((ctx)->cert)
  43. typedef int (*X509_STORE_CTX_get_issuer_fn)(X509 **issuer,
  44. X509_STORE_CTX *ctx, X509 *x);
  45. #define X509_STORE_CTX_get_get_issuer(ctx) ((ctx)->get_issuer)
  46. #define OpenSSL_version SSLeay_version
  47. #define OPENSSL_VERSION SSLEAY_VERSION
  48. #endif
  49. static char tls_library_version[32] = "";
  50. const char *openconnect_get_tls_library_version(void)
  51. {
  52. if (!*tls_library_version) {
  53. strncpy(tls_library_version,
  54. OpenSSL_version(OPENSSL_VERSION),
  55. sizeof(tls_library_version));
  56. tls_library_version[sizeof(tls_library_version)-1]='\0';
  57. }
  58. return tls_library_version;
  59. }
  60. int can_enable_insecure_crypto(void)
  61. {
  62. if (EVP_des_ede3_cbc() == NULL ||
  63. EVP_rc4() == NULL)
  64. return -ENOENT;
  65. return 0;
  66. }
  67. int openconnect_sha1(unsigned char *result, void *data, int len)
  68. {
  69. EVP_MD_CTX *c = EVP_MD_CTX_new();
  70. if (!c)
  71. return -ENOMEM;
  72. EVP_Digest(data, len, result, NULL, EVP_sha1(), NULL);
  73. EVP_MD_CTX_free(c);
  74. return 0;
  75. }
  76. int openconnect_sha256(unsigned char *result, void *data, int len)
  77. {
  78. EVP_MD_CTX *c = EVP_MD_CTX_new();
  79. if (!c)
  80. return -ENOMEM;
  81. EVP_Digest(data, len, result, NULL, EVP_sha256(), NULL);
  82. EVP_MD_CTX_free(c);
  83. return 0;
  84. }
  85. int openconnect_md5(unsigned char *result, void *data, int len)
  86. {
  87. EVP_MD_CTX *c = EVP_MD_CTX_new();
  88. if (!c)
  89. return -ENOMEM;
  90. EVP_Digest(data, len, result, NULL, EVP_md5(), NULL);
  91. EVP_MD_CTX_free(c);
  92. return 0;
  93. }
  94. int openconnect_get_peer_cert_DER(struct openconnect_info *vpninfo,
  95. unsigned char **buf)
  96. {
  97. BIO *bp = BIO_new(BIO_s_mem());
  98. BUF_MEM *certinfo;
  99. size_t l;
  100. if (!i2d_X509_bio(bp, vpninfo->peer_cert)) {
  101. BIO_free(bp);
  102. return -EIO;
  103. }
  104. BIO_get_mem_ptr(bp, &certinfo);
  105. l = certinfo->length;
  106. *buf = malloc(l);
  107. if (!*buf) {
  108. BIO_free(bp);
  109. return -ENOMEM;
  110. }
  111. memcpy(*buf, certinfo->data, l);
  112. BIO_free(bp);
  113. return l;
  114. }
  115. int openconnect_random(void *bytes, int len)
  116. {
  117. if (RAND_bytes(bytes, len) != 1)
  118. return -EIO;
  119. return 0;
  120. }
  121. /* Helper functions for reading/writing lines over TLS/DTLS.
  122. We could use cURL for the HTTP stuff, but it's overkill */
  123. static int _openconnect_openssl_write(SSL *ssl, int fd, struct openconnect_info *vpninfo, char *buf, size_t len)
  124. {
  125. size_t orig_len = len;
  126. while (len) {
  127. int done = SSL_write(ssl, buf, len);
  128. if (done > 0)
  129. len -= done;
  130. else {
  131. int err = SSL_get_error(ssl, done);
  132. fd_set wr_set, rd_set;
  133. int maxfd = fd;
  134. FD_ZERO(&wr_set);
  135. FD_ZERO(&rd_set);
  136. if (err == SSL_ERROR_WANT_READ)
  137. FD_SET(fd, &rd_set);
  138. else if (err == SSL_ERROR_WANT_WRITE)
  139. FD_SET(fd, &wr_set);
  140. else {
  141. vpn_progress(vpninfo, PRG_ERR, _("Failed to write to TLS/DTLS socket\n"));
  142. openconnect_report_ssl_errors(vpninfo);
  143. return -EIO;
  144. }
  145. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  146. select(maxfd + 1, &rd_set, &wr_set, NULL, NULL);
  147. if (is_cancel_pending(vpninfo, &rd_set)) {
  148. vpn_progress(vpninfo, PRG_ERR, _("TLS/DTLS write cancelled\n"));
  149. return -EINTR;
  150. }
  151. }
  152. }
  153. return orig_len;
  154. }
  155. static int openconnect_openssl_write(struct openconnect_info *vpninfo, char *buf, size_t len)
  156. {
  157. return _openconnect_openssl_write(vpninfo->https_ssl, vpninfo->ssl_fd, vpninfo, buf, len);
  158. }
  159. int openconnect_dtls_write(struct openconnect_info *vpninfo, void *buf, size_t len)
  160. {
  161. return _openconnect_openssl_write(vpninfo->dtls_ssl, vpninfo->dtls_fd, vpninfo, buf, len);
  162. }
  163. /* set ms to zero for no timeout */
  164. static int _openconnect_openssl_read(SSL *ssl, int fd, struct openconnect_info *vpninfo, char *buf, size_t len, unsigned ms)
  165. {
  166. int done, ret;
  167. struct timeval timeout, *tv = NULL;
  168. if (ms) {
  169. timeout.tv_sec = ms/1000;
  170. timeout.tv_usec = (ms%1000)*1000;
  171. tv = &timeout;
  172. }
  173. while ((done = SSL_read(ssl, buf, len)) == -1) {
  174. int err = SSL_get_error(ssl, done);
  175. fd_set wr_set, rd_set;
  176. int maxfd = fd;
  177. FD_ZERO(&wr_set);
  178. FD_ZERO(&rd_set);
  179. if (err == SSL_ERROR_WANT_READ)
  180. FD_SET(fd, &rd_set);
  181. else if (err == SSL_ERROR_WANT_WRITE)
  182. FD_SET(fd, &wr_set);
  183. else {
  184. vpn_progress(vpninfo, PRG_ERR, _("Failed to read from TLS/DTLS socket\n"));
  185. openconnect_report_ssl_errors(vpninfo);
  186. return -EIO;
  187. }
  188. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  189. ret = select(maxfd + 1, &rd_set, &wr_set, NULL, tv);
  190. if (is_cancel_pending(vpninfo, &rd_set)) {
  191. vpn_progress(vpninfo, PRG_ERR, _("TLS/DTLS read cancelled\n"));
  192. return -EINTR;
  193. }
  194. if (ret == 0) {
  195. return -ETIMEDOUT;
  196. }
  197. }
  198. return done;
  199. }
  200. static int openconnect_openssl_read(struct openconnect_info *vpninfo, char *buf, size_t len)
  201. {
  202. return _openconnect_openssl_read(vpninfo->https_ssl, vpninfo->ssl_fd, vpninfo, buf, len, 0);
  203. }
  204. int openconnect_dtls_read(struct openconnect_info *vpninfo, void *buf, size_t len, unsigned ms)
  205. {
  206. return _openconnect_openssl_read(vpninfo->dtls_ssl, vpninfo->dtls_fd, vpninfo, buf, len, ms);
  207. }
  208. static int openconnect_openssl_gets(struct openconnect_info *vpninfo, char *buf, size_t len)
  209. {
  210. int i = 0;
  211. int ret;
  212. if (len < 2)
  213. return -EINVAL;
  214. while (1) {
  215. ret = SSL_read(vpninfo->https_ssl, buf + i, 1);
  216. if (ret == 1) {
  217. if (buf[i] == '\n') {
  218. buf[i] = 0;
  219. if (i && buf[i-1] == '\r') {
  220. buf[i-1] = 0;
  221. i--;
  222. }
  223. return i;
  224. }
  225. i++;
  226. if (i >= len - 1) {
  227. buf[i] = 0;
  228. return i;
  229. }
  230. } else {
  231. fd_set rd_set, wr_set;
  232. int maxfd = vpninfo->ssl_fd;
  233. FD_ZERO(&rd_set);
  234. FD_ZERO(&wr_set);
  235. ret = SSL_get_error(vpninfo->https_ssl, ret);
  236. if (ret == SSL_ERROR_WANT_READ)
  237. FD_SET(vpninfo->ssl_fd, &rd_set);
  238. else if (ret == SSL_ERROR_WANT_WRITE)
  239. FD_SET(vpninfo->ssl_fd, &wr_set);
  240. else {
  241. vpn_progress(vpninfo, PRG_ERR, _("Failed to read from TLS/DTLS socket\n"));
  242. openconnect_report_ssl_errors(vpninfo);
  243. ret = -EIO;
  244. break;
  245. }
  246. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  247. select(maxfd + 1, &rd_set, &wr_set, NULL, NULL);
  248. if (is_cancel_pending(vpninfo, &rd_set)) {
  249. vpn_progress(vpninfo, PRG_ERR, _("TLS/DTLS read cancelled\n"));
  250. ret = -EINTR;
  251. break;
  252. }
  253. }
  254. }
  255. buf[i] = 0;
  256. return i ?: ret;
  257. }
  258. int ssl_nonblock_read(struct openconnect_info *vpninfo, int dtls, void *buf, int maxlen)
  259. {
  260. SSL *ssl = dtls ? vpninfo->dtls_ssl : vpninfo->https_ssl;
  261. int len, ret;
  262. if (!ssl) {
  263. vpn_progress(vpninfo, PRG_ERR,
  264. _("Attempted to read from non-existent %s session\n"),
  265. dtls ? "DTLS" : "TLS");
  266. return -1;
  267. }
  268. len = SSL_read(ssl, buf, maxlen);
  269. if (len > 0)
  270. return len;
  271. ret = SSL_get_error(ssl, len);
  272. if (ret == SSL_ERROR_WANT_WRITE || ret == SSL_ERROR_WANT_READ)
  273. return 0;
  274. vpn_progress(vpninfo, PRG_ERR, _("Read error on %s session: %d\n"),
  275. dtls ? "DTLS" : "TLS", ret);
  276. return -EIO;
  277. }
  278. int ssl_nonblock_write(struct openconnect_info *vpninfo, int dtls, void *buf, int buflen)
  279. {
  280. SSL *ssl = dtls ? vpninfo->dtls_ssl : vpninfo->https_ssl;
  281. int ret;
  282. if (!ssl) {
  283. vpn_progress(vpninfo, PRG_ERR,
  284. _("Attempted to write to non-existent %s session\n"),
  285. dtls ? "DTLS" : "TLS");
  286. return -1;
  287. }
  288. ret = SSL_write(ssl, buf, buflen);
  289. if (ret > 0)
  290. return ret;
  291. ret = SSL_get_error(ssl, ret);
  292. switch (ret) {
  293. case SSL_ERROR_WANT_WRITE:
  294. /* Waiting for the socket to become writable -- it's
  295. probably stalled, and/or the buffers are full */
  296. if (dtls)
  297. monitor_write_fd(vpninfo, dtls);
  298. else
  299. monitor_write_fd(vpninfo, ssl);
  300. /* Fall through */
  301. case SSL_ERROR_WANT_READ:
  302. return 0;
  303. default:
  304. vpn_progress(vpninfo, PRG_ERR, _("Write error on %s session: %d\n"),
  305. dtls ? "DTLS" : "TLS", ret);
  306. openconnect_report_ssl_errors(vpninfo);
  307. return -1;
  308. }
  309. }
  310. /* UI handling. All this just to handle the PIN callback from the TPM ENGINE,
  311. and turn it into a call to our ->process_auth_form function */
  312. struct ui_data {
  313. struct openconnect_info *vpninfo;
  314. struct oc_form_opt **last_opt;
  315. struct oc_auth_form form;
  316. };
  317. struct ui_form_opt {
  318. struct oc_form_opt opt;
  319. UI_STRING *uis;
  320. };
  321. #ifdef HAVE_ENGINE
  322. static int ui_open(UI *ui)
  323. {
  324. struct openconnect_info *vpninfo = UI_get0_user_data(ui);
  325. struct ui_data *ui_data;
  326. if (!vpninfo || !vpninfo->process_auth_form)
  327. return 0;
  328. ui_data = malloc(sizeof(*ui_data));
  329. if (!ui_data)
  330. return 0;
  331. memset(ui_data, 0, sizeof(*ui_data));
  332. ui_data->last_opt = &ui_data->form.opts;
  333. ui_data->vpninfo = vpninfo;
  334. ui_data->form.auth_id = (char *)"openssl_ui";
  335. UI_add_user_data(ui, ui_data);
  336. return 1;
  337. }
  338. static int ui_write(UI *ui, UI_STRING *uis)
  339. {
  340. struct ui_data *ui_data = UI_get0_user_data(ui);
  341. struct ui_form_opt *opt;
  342. switch (UI_get_string_type(uis)) {
  343. case UIT_ERROR:
  344. ui_data->form.error = (char *)UI_get0_output_string(uis);
  345. break;
  346. case UIT_INFO:
  347. ui_data->form.message = (char *)UI_get0_output_string(uis);
  348. break;
  349. case UIT_PROMPT:
  350. opt = malloc(sizeof(*opt));
  351. if (!opt)
  352. return 1;
  353. memset(opt, 0, sizeof(*opt));
  354. opt->uis = uis;
  355. opt->opt.label = opt->opt.name = (char *)UI_get0_output_string(uis);
  356. if (UI_get_input_flags(uis) & UI_INPUT_FLAG_ECHO)
  357. opt->opt.type = OC_FORM_OPT_TEXT;
  358. else
  359. opt->opt.type = OC_FORM_OPT_PASSWORD;
  360. *(ui_data->last_opt) = &opt->opt;
  361. ui_data->last_opt = &opt->opt.next;
  362. break;
  363. default:
  364. vpn_progress(ui_data->vpninfo, PRG_ERR,
  365. _("Unhandled SSL UI request type %d\n"),
  366. UI_get_string_type(uis));
  367. return 0;
  368. }
  369. return 1;
  370. }
  371. static int ui_flush(UI *ui)
  372. {
  373. struct ui_data *ui_data = UI_get0_user_data(ui);
  374. struct openconnect_info *vpninfo = ui_data->vpninfo;
  375. struct ui_form_opt *opt;
  376. int ret;
  377. ret = process_auth_form(vpninfo, &ui_data->form);
  378. if (ret)
  379. return 0;
  380. for (opt = (struct ui_form_opt *)ui_data->form.opts; opt;
  381. opt = (struct ui_form_opt *)opt->opt.next) {
  382. if (opt->opt._value && opt->uis)
  383. UI_set_result(ui, opt->uis, opt->opt._value);
  384. }
  385. return 1;
  386. }
  387. static int ui_close(UI *ui)
  388. {
  389. struct ui_data *ui_data = UI_get0_user_data(ui);
  390. struct ui_form_opt *opt, *next_opt;
  391. opt = (struct ui_form_opt *)ui_data->form.opts;
  392. while (opt) {
  393. next_opt = (struct ui_form_opt *)opt->opt.next;
  394. if (opt->opt._value)
  395. free(opt->opt._value);
  396. free(opt);
  397. opt = next_opt;
  398. }
  399. free(ui_data);
  400. UI_add_user_data(ui, NULL);
  401. return 1;
  402. }
  403. static UI_METHOD *create_openssl_ui(void)
  404. {
  405. UI_METHOD *ui_method = UI_create_method((char *)"AnyConnect VPN UI");
  406. /* Set up a UI method of our own for password/passphrase requests */
  407. UI_method_set_opener(ui_method, ui_open);
  408. UI_method_set_writer(ui_method, ui_write);
  409. UI_method_set_flusher(ui_method, ui_flush);
  410. UI_method_set_closer(ui_method, ui_close);
  411. return ui_method;
  412. }
  413. #endif
  414. static int pem_pw_cb(char *buf, int len, int w, void *ci)
  415. {
  416. struct cert_info *certinfo = ci;
  417. struct openconnect_info *vpninfo = certinfo->vpninfo;
  418. char *pass = NULL;
  419. int plen;
  420. if (certinfo->password) {
  421. pass = certinfo->password;
  422. certinfo->password = NULL;
  423. } else if (request_passphrase(vpninfo,
  424. certinfo_string(certinfo, "openconnect_pem", "openconnect_secondary_pem"),
  425. &pass,
  426. certinfo_string(certinfo, _("Enter PEM pass phrase:"),
  427. _("Enter secondary PEM pass phrase:"))))
  428. return -1;
  429. plen = strlen(pass);
  430. if (len <= plen) {
  431. vpn_progress(vpninfo, PRG_ERR,
  432. _("PEM password too long (%d >= %d)\n"),
  433. plen, len);
  434. free_pass(&pass);
  435. return -1;
  436. }
  437. memcpy(buf, pass, plen+1);
  438. free_pass(&pass);
  439. return plen;
  440. }
  441. struct ossl_cert_info {
  442. EVP_PKEY *key;
  443. X509 *cert;
  444. STACK_OF(X509) *extra_certs;
  445. const char *certs_from;
  446. };
  447. void unload_certificate(struct cert_info *certinfo, int finalize)
  448. {
  449. (void) finalize;
  450. if (!certinfo)
  451. return;
  452. if (certinfo->priv_info) {
  453. struct ossl_cert_info *oci = certinfo->priv_info;
  454. certinfo->priv_info = NULL;
  455. if (oci->key)
  456. EVP_PKEY_free(oci->key);
  457. if (oci->cert)
  458. X509_free(oci->cert);
  459. if (oci->extra_certs)
  460. sk_X509_pop_free(oci->extra_certs, X509_free);
  461. free(oci);
  462. }
  463. }
  464. static int install_ssl_ctx_certs(struct openconnect_info *vpninfo, struct ossl_cert_info *oci)
  465. {
  466. X509 *cert = oci->cert;
  467. int i;
  468. if (!cert || !oci->key) {
  469. vpn_progress(vpninfo, PRG_ERR,
  470. _("Client certificate or key missing\n"));
  471. return -EINVAL;
  472. }
  473. if (!SSL_CTX_use_PrivateKey(vpninfo->https_ctx, oci->key)) {
  474. vpn_progress(vpninfo, PRG_ERR,
  475. _("Loading private key failed\n"));
  476. openconnect_report_ssl_errors(vpninfo);
  477. return -EIO;
  478. }
  479. if (!SSL_CTX_use_certificate(vpninfo->https_ctx, cert)) {
  480. vpn_progress(vpninfo, PRG_ERR,
  481. _("Failed to install certificate in OpenSSL context\n"));
  482. openconnect_report_ssl_errors(vpninfo);
  483. return -EIO;
  484. }
  485. vpninfo->cert_x509 = cert;
  486. X509_up_ref(cert);
  487. if (!oci->extra_certs)
  488. return 0;
  489. next:
  490. for (i = 0; i < sk_X509_num(oci->extra_certs); i++) {
  491. X509 *cert2 = sk_X509_value(oci->extra_certs, i);
  492. if (X509_check_issued(cert2, cert) == X509_V_OK) {
  493. char buf[200];
  494. if (cert2 == cert)
  495. break;
  496. if (X509_check_issued(cert2, cert2) == X509_V_OK)
  497. break;
  498. X509_NAME_oneline(X509_get_subject_name(cert2),
  499. buf, sizeof(buf));
  500. vpn_progress(vpninfo, PRG_DEBUG,
  501. _("Extra cert from %s: '%s'\n"), oci->certs_from, buf);
  502. X509_up_ref(cert2);
  503. SSL_CTX_add_extra_chain_cert(vpninfo->https_ctx, cert2);
  504. cert = cert2;
  505. goto next;
  506. }
  507. }
  508. return 0;
  509. }
  510. static int load_pkcs12_certificate(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  511. struct ossl_cert_info *oci, PKCS12 *p12)
  512. {
  513. EVP_PKEY *pkey = NULL;
  514. X509 *cert = NULL;
  515. STACK_OF(X509) *ca;
  516. int ret = 0;
  517. char *pass;
  518. pass = certinfo->password;
  519. certinfo->password = NULL;
  520. retrypass:
  521. /* We do this every time round the loop, to work around a bug in
  522. OpenSSL < 1.0.0-beta2 -- where the stack at *ca will be freed
  523. when PKCS12_parse() returns an error, but *ca is left pointing
  524. to the freed memory. */
  525. ca = NULL;
  526. if (!PKCS12_parse(p12, pass, &pkey, &cert, &ca)) {
  527. unsigned long err = ERR_peek_error();
  528. if (ERR_GET_LIB(err) == ERR_LIB_PKCS12 &&
  529. #if OPENSSL_VERSION_NUMBER < 0x30000000L
  530. ERR_GET_FUNC(err) == PKCS12_F_PKCS12_PARSE &&
  531. #endif
  532. ERR_GET_REASON(err) == PKCS12_R_MAC_VERIFY_FAILURE) {
  533. if (pass)
  534. vpn_progress(vpninfo, PRG_ERR,
  535. _("Failed to decrypt PKCS#12 certificate file\n"));
  536. free_pass(&pass);
  537. if (request_passphrase(vpninfo,
  538. certinfo_string(certinfo, "openconnect_pkcs12",
  539. "openconnect_secondary_pkcs12"),
  540. &pass,
  541. certinfo_string(certinfo, _("Enter PKCS#12 pass phrase:"),
  542. _("Enter secondary PKCS#12 pass phrase:"))) < 0) {
  543. PKCS12_free(p12);
  544. return -EINVAL;
  545. }
  546. goto retrypass;
  547. }
  548. openconnect_report_ssl_errors(vpninfo);
  549. vpn_progress(vpninfo, PRG_ERR,
  550. certinfo_string(certinfo, _("Parse PKCS#12 failed (see above errors)\n"),
  551. _("Parse secondary PKCS#12 failed (see above errors)\n")));
  552. PKCS12_free(p12);
  553. free_pass(&pass);
  554. return -EINVAL;
  555. }
  556. free_pass(&pass);
  557. if (cert) {
  558. char buf[200];
  559. X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
  560. vpn_progress(vpninfo, PRG_INFO,
  561. certinfo_string(certinfo, _("Using client certificate '%s'\n"),
  562. _("Using secondary certificate '%s'\n")), buf);
  563. } else {
  564. vpn_progress(vpninfo, PRG_ERR,
  565. certinfo_string(certinfo, _("PKCS#12 contained no certificate!\n"),
  566. _("Secondary PKCS#12 contained no certificate!\n")));
  567. ret = -EINVAL;
  568. }
  569. if (!pkey) {
  570. vpn_progress(vpninfo, PRG_ERR,
  571. certinfo_string(certinfo, _("PKCS#12 contained no private key!\n"),
  572. _("Secondary PKCS#12 contained no private key!\n")));
  573. ret = -EINVAL;
  574. }
  575. oci->key = pkey;
  576. oci->cert = cert;
  577. oci->extra_certs = ca;
  578. oci->certs_from = _("PKCS#12");
  579. PKCS12_free(p12);
  580. if (ret)
  581. unload_certificate(certinfo, 1);
  582. return ret;
  583. }
  584. #ifdef HAVE_ENGINE
  585. static int load_tpm_certificate(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  586. struct ossl_cert_info *oci, const char *engine)
  587. {
  588. ENGINE *e;
  589. EVP_PKEY *key;
  590. UI_METHOD *meth = NULL;
  591. int ret = 0;
  592. ENGINE_load_builtin_engines();
  593. e = ENGINE_by_id(engine);
  594. if (!e && !strcmp(engine, "tpm2")) {
  595. ERR_clear_error();
  596. e = ENGINE_by_id("tpm2tss");
  597. }
  598. if (!e) {
  599. vpn_progress(vpninfo, PRG_ERR, _("Can't load TPM engine.\n"));
  600. openconnect_report_ssl_errors(vpninfo);
  601. return -EINVAL;
  602. }
  603. if (!ENGINE_init(e) || !ENGINE_set_default_RSA(e) ||
  604. !ENGINE_set_default_RAND(e)) {
  605. vpn_progress(vpninfo, PRG_ERR, _("Failed to init TPM engine\n"));
  606. openconnect_report_ssl_errors(vpninfo);
  607. ENGINE_free(e);
  608. return -EINVAL;
  609. }
  610. if (certinfo->password) {
  611. if (!ENGINE_ctrl_cmd(e, "PIN", strlen(certinfo->password),
  612. certinfo->password, NULL, 0)) {
  613. vpn_progress(vpninfo, PRG_ERR,
  614. _("Failed to set TPM SRK password\n"));
  615. openconnect_report_ssl_errors(vpninfo);
  616. }
  617. free_pass(&certinfo->password);
  618. }
  619. /* Provide our own UI method to handle the PIN callback. */
  620. meth = create_openssl_ui();
  621. key = ENGINE_load_private_key(e, certinfo->key, meth, vpninfo);
  622. if (meth)
  623. UI_destroy_method(meth);
  624. if (!key) {
  625. vpn_progress(vpninfo, PRG_ERR,
  626. certinfo_string(certinfo, _("Failed to load TPM private key\n"),
  627. _("Failed to load secondary TPM private key\n")));
  628. openconnect_report_ssl_errors(vpninfo);
  629. ret = -EINVAL;
  630. goto out;
  631. }
  632. oci->key = key;
  633. out:
  634. ENGINE_finish(e);
  635. ENGINE_free(e);
  636. return ret;
  637. }
  638. #else
  639. static int load_tpm_certificate(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  640. struct ossl_cert_info *oci, const char *engine)
  641. {
  642. vpn_progress(vpninfo, PRG_ERR,
  643. _("This version of OpenConnect was built without TPM support\n"));
  644. return -EINVAL;
  645. }
  646. #endif
  647. /* This is a reimplementation of SSL_CTX_use_certificate_chain_file().
  648. * We do this for three reasons:
  649. *
  650. * - Firstly, we have no way to obtain the primary X509 certificate
  651. * after SSL_CTX_use_certificate_chain_file() has loaded it, and we
  652. * need to inspect it to check for expiry and report its name etc.
  653. * So in the past we've opened the cert file again and read the cert
  654. * again in a reload_pem_cert() function which was a partial
  655. * reimplementation anyway.
  656. *
  657. * - Secondly, on Windows, OpenSSL only partially handles UTF-8 filenames.
  658. * Specifically, BIO_new_file() will convert UTF-8 to UTF-16 and attempt
  659. * to use _wfopen() to open the file, but BIO_read_filename() will not.
  660. * It is BIO_read_filename() which the SSL_CTX_*_file functions use, and
  661. * thus they don't work with UTF-8 file names. This is filed as RT#3479:
  662. * http://rt.openssl.org/Ticket/Display.html?id=3479
  663. *
  664. * - Finally, and least importantly, it does actually matter which supporting
  665. * certs we offer on the wire because of RT#1942. Doing this for ourselves
  666. * allows us to explicitly print the supporting certs that we're using,
  667. * which may assist in diagnosing problems.
  668. */
  669. static int load_cert_chain_file(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  670. struct ossl_cert_info *oci)
  671. {
  672. BIO *b;
  673. FILE *f = openconnect_fopen_utf8(vpninfo, certinfo->cert, "rb");
  674. STACK_OF(X509) *extra_certs = NULL;
  675. char buf[200];
  676. if (!f) {
  677. vpn_progress(vpninfo, PRG_ERR,
  678. certinfo_string(certinfo, _("Failed to open certificate file %s: %s\n"),
  679. _("Failed to open secondary certificate file %s: %s\n")),
  680. certinfo->cert, strerror(errno));
  681. return -ENOENT;
  682. }
  683. b = BIO_new_fp(f, 1);
  684. if (!b) {
  685. fclose(f);
  686. err:
  687. vpn_progress(vpninfo, PRG_ERR,
  688. _("Loading certificate failed\n"));
  689. openconnect_report_ssl_errors(vpninfo);
  690. return -EIO;
  691. }
  692. oci->cert = PEM_read_bio_X509_AUX(b, NULL, NULL, NULL);
  693. if (!oci->cert) {
  694. BIO_free(b);
  695. goto err;
  696. }
  697. X509_NAME_oneline(X509_get_subject_name(oci->cert), buf, sizeof(buf));
  698. vpn_progress(vpninfo, PRG_INFO,
  699. certinfo_string(certinfo, _("Using client certificate '%s'\n"),
  700. _("Using secondary certificate '%s'\n")), buf);
  701. while (1) {
  702. X509 *x = PEM_read_bio_X509(b, NULL, NULL, NULL);
  703. if (!x) {
  704. unsigned long err = ERR_peek_last_error();
  705. if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
  706. ERR_GET_REASON(err) == PEM_R_NO_START_LINE)
  707. ERR_clear_error();
  708. else
  709. goto err_extra;
  710. break;
  711. }
  712. if (!extra_certs)
  713. extra_certs = sk_X509_new_null();
  714. if (!extra_certs) {
  715. err_extra:
  716. vpn_progress(vpninfo, PRG_ERR,
  717. certinfo_string(certinfo, _("Failed to process all supporting certs. Trying anyway...\n"),
  718. _("Failed to process secondary supporting certs. Trying anyway...\n")));
  719. openconnect_report_ssl_errors(vpninfo);
  720. X509_free(x);
  721. /* It might work without... */
  722. break;
  723. }
  724. if (!sk_X509_push(extra_certs, x))
  725. goto err_extra;
  726. }
  727. BIO_free(b);
  728. oci->extra_certs = extra_certs;
  729. oci->certs_from = _("PEM file");
  730. return 0;
  731. }
  732. #ifdef ANDROID_KEYSTORE
  733. static BIO *BIO_from_keystore(struct openconnect_info *vpninfo, const char *item)
  734. {
  735. unsigned char *content;
  736. BIO *b;
  737. int len;
  738. const char *p = item + 9;
  739. /* Skip first two slashes if the user has given it as
  740. keystore://foo ... */
  741. if (*p == '/')
  742. p++;
  743. if (*p == '/')
  744. p++;
  745. len = keystore_fetch(p, &content);
  746. if (len < 0) {
  747. vpn_progress(vpninfo, PRG_ERR,
  748. _("Failed to load item '%s' from keystore: %s\n"),
  749. p, keystore_strerror(len));
  750. return NULL;
  751. }
  752. if (!(b = BIO_new(BIO_s_mem())) || BIO_write(b, content, len) != len) {
  753. vpn_progress(vpninfo, PRG_ERR,
  754. _("Failed to create BIO for keystore item '%s'\n"),
  755. p);
  756. free(content);
  757. BIO_free(b);
  758. return NULL;
  759. }
  760. free(content);
  761. return b;
  762. }
  763. #endif
  764. static int is_pem_password_error(struct openconnect_info *vpninfo, struct cert_info *certinfo)
  765. {
  766. unsigned long err = ERR_peek_error();
  767. openconnect_report_ssl_errors(vpninfo);
  768. #ifndef EVP_F_EVP_DECRYPTFINAL_EX
  769. #define EVP_F_EVP_DECRYPTFINAL_EX EVP_F_EVP_DECRYPTFINAL
  770. #endif
  771. /* If the user fat-fingered the passphrase, try again */
  772. if (ERR_GET_LIB(err) == ERR_LIB_EVP &&
  773. #if OPENSSL_VERSION_NUMBER < 0x30000000L
  774. ERR_GET_FUNC(err) == EVP_F_EVP_DECRYPTFINAL_EX &&
  775. #endif
  776. ERR_GET_REASON(err) == EVP_R_BAD_DECRYPT) {
  777. vpn_progress(vpninfo, PRG_ERR,
  778. certinfo_string(certinfo, _("Loading private key failed (wrong passphrase?)\n"),
  779. _("Loading secondary private key failed (wrong passphrase?)\n")));
  780. ERR_clear_error();
  781. return 1;
  782. }
  783. vpn_progress(vpninfo, PRG_ERR,
  784. certinfo_string(certinfo, _("Loading private key failed (see above errors)\n"),
  785. _("Loading secondary private key failed (see above errors)\n")));
  786. return 0;
  787. }
  788. static int xload_certificate(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  789. struct ossl_cert_info *oci)
  790. {
  791. FILE *f;
  792. char buf[256];
  793. int ret;
  794. if (!strncmp(certinfo->cert, "pkcs11:", 7)) {
  795. int ret = load_pkcs11_certificate(vpninfo, certinfo, &oci->cert);
  796. if (ret)
  797. return ret;
  798. goto got_cert;
  799. }
  800. vpn_progress(vpninfo, PRG_DEBUG,
  801. certinfo_string(certinfo, _("Using certificate file %s\n"),
  802. _("Using secondary certificate file %s\n")),
  803. certinfo->cert);
  804. if (strncmp(certinfo->cert, "keystore:", 9)) {
  805. PKCS12 *p12;
  806. f = openconnect_fopen_utf8(vpninfo, certinfo->cert, "rb");
  807. if (!f) {
  808. vpn_progress(vpninfo, PRG_ERR,
  809. _("Failed to open certificate file %s: %s\n"),
  810. certinfo->cert, strerror(errno));
  811. return -ENOENT;
  812. }
  813. p12 = d2i_PKCS12_fp(f, NULL);
  814. fclose(f);
  815. if (p12)
  816. return load_pkcs12_certificate(vpninfo, certinfo, oci, p12);
  817. /* Not PKCS#12. Clear error and fall through to see if it's a PEM file... */
  818. ERR_clear_error();
  819. }
  820. /* It's PEM or TPM now, and either way we need to load the plain cert: */
  821. #ifdef ANDROID_KEYSTORE
  822. if (!strncmp(certinfo->cert, "keystore:", 9)) {
  823. BIO *b = BIO_from_keystore(vpninfo, certinfo->cert);
  824. if (!b)
  825. return -EINVAL;
  826. oci->cert = PEM_read_bio_X509_AUX(b, NULL, pem_pw_cb, certinfo);
  827. BIO_free(b);
  828. if (!oci->cert) {
  829. vpn_progress(vpninfo, PRG_ERR,
  830. _("Failed to load X509 certificate from keystore\n"));
  831. openconnect_report_ssl_errors(vpninfo);
  832. return -EINVAL;
  833. }
  834. } else
  835. #endif /* ANDROID_KEYSTORE */
  836. {
  837. int ret = load_cert_chain_file(vpninfo, certinfo, oci);
  838. if (ret)
  839. return ret;
  840. }
  841. got_cert:
  842. #ifdef ANDROID_KEYSTORE
  843. if (!strncmp(certinfo->key, "keystore:", 9)) {
  844. BIO *b;
  845. again_android:
  846. b = BIO_from_keystore(vpninfo, certinfo->key);
  847. if (!b)
  848. return -EINVAL;
  849. oci->key = PEM_read_bio_PrivateKey(b, NULL, pem_pw_cb, certinfo);
  850. BIO_free(b);
  851. if (!oci->key) {
  852. if (is_pem_password_error(vpninfo, certinfo))
  853. goto again_android;
  854. return -EINVAL;
  855. }
  856. return 0;
  857. }
  858. #endif /* ANDROID_KEYSTORE */
  859. if (!strncmp(certinfo->key, "pkcs11:", 7))
  860. return load_pkcs11_key(vpninfo, certinfo, &oci->key);
  861. f = openconnect_fopen_utf8(vpninfo, certinfo->key, "rb");
  862. if (!f) {
  863. vpn_progress(vpninfo, PRG_ERR,
  864. _("Failed to open private key file %s: %s\n"),
  865. certinfo->key, strerror(errno));
  866. return -ENOENT;
  867. }
  868. buf[255] = 0;
  869. while (fgets(buf, 255, f)) {
  870. if (!strcmp(buf, "-----BEGIN TSS KEY BLOB-----\n")) {
  871. fclose(f);
  872. return load_tpm_certificate(vpninfo, certinfo, oci, "tpm");
  873. } else if (!strcmp(buf, "-----BEGIN TSS2 KEY BLOB-----\n") ||
  874. !strcmp(buf, "-----BEGIN TSS2 PRIVATE KEY-----\n")) {
  875. fclose(f);
  876. return load_tpm_certificate(vpninfo, certinfo, oci, "tpm2");
  877. } else if (!strcmp(buf, "-----BEGIN RSA PRIVATE KEY-----\n") ||
  878. !strcmp(buf, "-----BEGIN DSA PRIVATE KEY-----\n") ||
  879. !strcmp(buf, "-----BEGIN EC PRIVATE KEY-----\n") ||
  880. !strcmp(buf, "-----BEGIN ENCRYPTED PRIVATE KEY-----\n") ||
  881. !strcmp(buf, "-----BEGIN PRIVATE KEY-----\n")) {
  882. BIO *b = BIO_new_fp(f, BIO_CLOSE);
  883. if (!b) {
  884. fclose(f);
  885. vpn_progress(vpninfo, PRG_ERR,
  886. certinfo_string(certinfo, _("Loading private key failed\n"),
  887. _("Loading secondary private key failed\n")));
  888. openconnect_report_ssl_errors(vpninfo);
  889. return -EINVAL;
  890. }
  891. again:
  892. fseek(f, 0, SEEK_SET);
  893. oci->key = PEM_read_bio_PrivateKey(b, NULL, pem_pw_cb, certinfo);
  894. if (!oci->key) {
  895. if (is_pem_password_error(vpninfo, certinfo))
  896. goto again;
  897. BIO_free(b);
  898. return -EINVAL;
  899. }
  900. ret = 0;
  901. BIO_free(b);
  902. return ret;
  903. }
  904. }
  905. /* Not PEM? Try DER... */
  906. fseek(f, 0, SEEK_SET);
  907. /* This will catch PKCS#1 and unencrypted PKCS#8
  908. * (except in OpenSSL 0.9.8 where it doesn't handle
  909. * the latter but nobody cares about 0.9.8 any more. */
  910. oci->key = d2i_PrivateKey_fp(f, NULL);
  911. if (oci->key) {
  912. ret = 0;
  913. fclose(f);
  914. return ret;
  915. } else {
  916. /* Encrypted PKCS#8 DER */
  917. X509_SIG *p8;
  918. fseek(f, 0, SEEK_SET);
  919. p8 = d2i_PKCS8_fp(f, NULL);
  920. if (p8) {
  921. PKCS8_PRIV_KEY_INFO *p8inf;
  922. char *pass = certinfo->password;
  923. fclose(f);
  924. while (!(p8inf = PKCS8_decrypt(p8, pass ? : "", pass ? strlen(pass) : 0))) {
  925. unsigned long err = ERR_peek_error();
  926. if (ERR_GET_LIB(err) == ERR_LIB_EVP &&
  927. #if OPENSSL_VERSION_NUMBER < 0x30000000L
  928. ERR_GET_FUNC(err) == EVP_F_EVP_DECRYPTFINAL_EX &&
  929. #endif
  930. ERR_GET_REASON(err) == EVP_R_BAD_DECRYPT) {
  931. ERR_clear_error();
  932. if (pass) {
  933. vpn_progress(vpninfo, PRG_ERR,
  934. certinfo_string(certinfo, _("Failed to decrypt PKCS#8 certificate file\n"),
  935. _("Failed to decrypt secondary PKCS#8 certificate file\n")));
  936. free_pass(&pass);
  937. pass = NULL;
  938. }
  939. if (request_passphrase(vpninfo,
  940. certinfo_string(certinfo, "openconnect_pkcs8",
  941. "openconnect_secondary_pkcs8"),
  942. &pass,
  943. certinfo_string(certinfo, _("Enter PKCS#8 pass phrase:"),
  944. _("Enter PKCS#8 secondary pass phrase:"))) >= 0)
  945. continue;
  946. } else {
  947. vpn_progress(vpninfo, PRG_ERR,
  948. certinfo_string(certinfo, _("Failed to decrypt PKCS#8 certificate file\n"),
  949. _("Failed to decrypt secondary PKCS#8 certificate file\n")));
  950. openconnect_report_ssl_errors(vpninfo);
  951. }
  952. free_pass(&pass);
  953. certinfo->password = NULL;
  954. X509_SIG_free(p8);
  955. return -EINVAL;
  956. }
  957. free_pass(&pass);
  958. certinfo->password = NULL;
  959. oci->key = EVP_PKCS82PKEY(p8inf);
  960. PKCS8_PRIV_KEY_INFO_free(p8inf);
  961. X509_SIG_free(p8);
  962. if (oci->key == NULL) {
  963. vpn_progress(vpninfo, PRG_ERR,
  964. certinfo_string(certinfo, _("Failed to convert PKCS#8 to OpenSSL EVP_PKEY\n"),
  965. _("Failed to convert secondary PKCS#8 to OpenSSL EVP_PKEY\n")));
  966. return -EIO;
  967. }
  968. ret = 0;
  969. return ret;
  970. }
  971. }
  972. fclose(f);
  973. vpn_progress(vpninfo, PRG_ERR,
  974. _("Failed to identify private key type in '%s'\n"),
  975. certinfo->key);
  976. return -EINVAL;
  977. }
  978. int load_certificate(struct openconnect_info *vpninfo, struct cert_info *certinfo, int flags)
  979. {
  980. struct ossl_cert_info *oci;
  981. int ret;
  982. (void) flags;
  983. certinfo->priv_info = oci = calloc(1, sizeof(*oci));
  984. if (!oci) {
  985. ret = -ENOMEM;
  986. goto done;
  987. }
  988. certinfo->vpninfo = vpninfo;
  989. ret = xload_certificate(vpninfo, certinfo, oci);
  990. done:
  991. if (ret)
  992. unload_certificate(certinfo, 1);
  993. return ret;
  994. }
  995. static int get_cert_fingerprint(struct openconnect_info *vpninfo,
  996. X509 *cert, const EVP_MD *type,
  997. char *buf)
  998. {
  999. unsigned char md[EVP_MAX_MD_SIZE];
  1000. unsigned int i, n;
  1001. if (!X509_digest(cert, type, md, &n))
  1002. return -ENOMEM;
  1003. for (i = 0; i < n; i++)
  1004. sprintf(&buf[i*2], "%02X", md[i]);
  1005. return 0;
  1006. }
  1007. int get_cert_md5_fingerprint(struct openconnect_info *vpninfo,
  1008. void *cert, char *buf)
  1009. {
  1010. return get_cert_fingerprint(vpninfo, cert, EVP_md5(), buf);
  1011. }
  1012. static int set_peer_cert_hash(struct openconnect_info *vpninfo)
  1013. {
  1014. EVP_PKEY *pkey;
  1015. BIO *bp = BIO_new(BIO_s_mem());
  1016. BUF_MEM *keyinfo;
  1017. /* We can't use X509_pubkey_digest() because it only hashes the
  1018. subjectPublicKey BIT STRING, and not the whole of the
  1019. SubjectPublicKeyInfo SEQUENCE. */
  1020. pkey = X509_get_pubkey(vpninfo->peer_cert);
  1021. if (!i2d_PUBKEY_bio(bp, pkey)) {
  1022. EVP_PKEY_free(pkey);
  1023. BIO_free(bp);
  1024. return -ENOMEM;
  1025. }
  1026. EVP_PKEY_free(pkey);
  1027. BIO_get_mem_ptr(bp, &keyinfo);
  1028. openconnect_sha256(vpninfo->peer_cert_sha256_raw, keyinfo->data, keyinfo->length);
  1029. openconnect_sha1(vpninfo->peer_cert_sha1_raw, keyinfo->data, keyinfo->length);
  1030. BIO_free(bp);
  1031. return 0;
  1032. }
  1033. #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
  1034. static int match_hostname_elem(const char *hostname, int helem_len,
  1035. const char *match, int melem_len)
  1036. {
  1037. if (!helem_len && !melem_len)
  1038. return 0;
  1039. if (!helem_len || !melem_len)
  1040. return -1;
  1041. if (match[0] == '*') {
  1042. int i;
  1043. for (i = 1 ; i <= helem_len; i++) {
  1044. if (!match_hostname_elem(hostname + i, helem_len - i,
  1045. match + 1, melem_len - 1))
  1046. return 0;
  1047. }
  1048. return -1;
  1049. }
  1050. /* From the NetBSD (5.1) man page for ctype(3):
  1051. Values of type char or signed char must first be cast to unsigned char,
  1052. to ensure that the values are within the correct range. The result
  1053. should then be cast to int to avoid warnings from some compilers.
  1054. We do indeed get warning "array subscript has type 'char'" without
  1055. the casts. Ick. */
  1056. if (toupper((int)(unsigned char)hostname[0]) ==
  1057. toupper((int)(unsigned char)match[0]))
  1058. return match_hostname_elem(hostname + 1, helem_len - 1,
  1059. match + 1, melem_len - 1);
  1060. return -1;
  1061. }
  1062. static int match_hostname(const char *hostname, const char *match)
  1063. {
  1064. while (*match) {
  1065. const char *h_dot, *m_dot;
  1066. int helem_len, melem_len;
  1067. h_dot = strchr(hostname, '.');
  1068. m_dot = strchr(match, '.');
  1069. if (h_dot && m_dot) {
  1070. helem_len = h_dot - hostname + 1;
  1071. melem_len = m_dot - match + 1;
  1072. } else if (!h_dot && !m_dot) {
  1073. helem_len = strlen(hostname);
  1074. melem_len = strlen(match);
  1075. } else
  1076. return -1;
  1077. if (match_hostname_elem(hostname, helem_len,
  1078. match, melem_len))
  1079. return -1;
  1080. hostname += helem_len;
  1081. match += melem_len;
  1082. }
  1083. if (*hostname)
  1084. return -1;
  1085. return 0;
  1086. }
  1087. /* cf. RFC2818 and RFC2459 */
  1088. static int match_cert_hostname(struct openconnect_info *vpninfo, X509 *peer_cert,
  1089. const unsigned char *ipaddr, int ipaddrlen)
  1090. {
  1091. STACK_OF(GENERAL_NAME) *altnames;
  1092. X509_NAME *subjname;
  1093. ASN1_STRING *subjasn1;
  1094. char *subjstr = NULL;
  1095. int i, altdns = 0;
  1096. int ret;
  1097. altnames = X509_get_ext_d2i(peer_cert, NID_subject_alt_name,
  1098. NULL, NULL);
  1099. for (i = 0; i < sk_GENERAL_NAME_num(altnames); i++) {
  1100. const GENERAL_NAME *this = sk_GENERAL_NAME_value(altnames, i);
  1101. if (this->type == GEN_DNS) {
  1102. char *str;
  1103. int len = ASN1_STRING_to_UTF8((void *)&str, this->d.ia5);
  1104. if (len < 0)
  1105. continue;
  1106. altdns = 1;
  1107. /* We don't like names with embedded NUL */
  1108. if (strlen(str) != len)
  1109. continue;
  1110. if (!match_hostname(vpninfo->hostname, str)) {
  1111. vpn_progress(vpninfo, PRG_DEBUG,
  1112. _("Matched DNS altname '%s'\n"),
  1113. str);
  1114. GENERAL_NAMES_free(altnames);
  1115. OPENSSL_free(str);
  1116. return 0;
  1117. } else {
  1118. vpn_progress(vpninfo, PRG_DEBUG,
  1119. _("No match for altname '%s'\n"),
  1120. str);
  1121. }
  1122. OPENSSL_free(str);
  1123. } else if (this->type == GEN_IPADD && ipaddrlen) {
  1124. char host[80];
  1125. int family;
  1126. if (this->d.ip->length == 4) {
  1127. family = AF_INET;
  1128. } else if (this->d.ip->length == 16) {
  1129. family = AF_INET6;
  1130. } else {
  1131. vpn_progress(vpninfo, PRG_ERR,
  1132. _("Certificate has GEN_IPADD altname with bogus length %d\n"),
  1133. this->d.ip->length);
  1134. continue;
  1135. }
  1136. /* We only do this for the debug messages */
  1137. inet_ntop(family, this->d.ip->data, host, sizeof(host));
  1138. if (this->d.ip->length == ipaddrlen &&
  1139. !memcmp(ipaddr, this->d.ip->data, ipaddrlen)) {
  1140. vpn_progress(vpninfo, PRG_DEBUG,
  1141. _("Matched %s address '%s'\n"),
  1142. (family == AF_INET6) ? "IPv6" : "IPv4",
  1143. host);
  1144. GENERAL_NAMES_free(altnames);
  1145. return 0;
  1146. } else {
  1147. vpn_progress(vpninfo, PRG_DEBUG,
  1148. _("No match for %s address '%s'\n"),
  1149. (family == AF_INET6) ? "IPv6" : "IPv4",
  1150. host);
  1151. }
  1152. } else if (this->type == GEN_URI) {
  1153. char *str;
  1154. char *url_proto, *url_host, *url_path, *url_host2;
  1155. int url_port;
  1156. int len = ASN1_STRING_to_UTF8((void *)&str, this->d.ia5);
  1157. if (len < 0)
  1158. continue;
  1159. /* We don't like names with embedded NUL */
  1160. if (strlen(str) != len)
  1161. continue;
  1162. if (internal_parse_url(str, &url_proto, &url_host, &url_port, &url_path, 0)) {
  1163. OPENSSL_free(str);
  1164. continue;
  1165. }
  1166. if (!url_proto || strcasecmp(url_proto, "https"))
  1167. goto no_uri_match;
  1168. if (url_port != vpninfo->port)
  1169. goto no_uri_match;
  1170. /* Leave url_host as it was so that it can be freed */
  1171. url_host2 = url_host;
  1172. if (ipaddrlen == 16 && vpninfo->hostname[0] != '[' &&
  1173. url_host[0] == '[' && url_host[strlen(url_host)-1] == ']') {
  1174. /* Cope with https://[IPv6]/ when the hostname is bare IPv6 */
  1175. url_host[strlen(url_host)-1] = 0;
  1176. url_host2++;
  1177. }
  1178. if (strcasecmp(vpninfo->hostname, url_host2))
  1179. goto no_uri_match;
  1180. if (url_path) {
  1181. vpn_progress(vpninfo, PRG_DEBUG,
  1182. _("URI '%s' has non-empty path; ignoring\n"),
  1183. str);
  1184. goto no_uri_match_silent;
  1185. }
  1186. vpn_progress(vpninfo, PRG_DEBUG,
  1187. _("Matched URI '%s'\n"),
  1188. str);
  1189. free(url_proto);
  1190. free(url_host);
  1191. free(url_path);
  1192. OPENSSL_free(str);
  1193. GENERAL_NAMES_free(altnames);
  1194. return 0;
  1195. no_uri_match:
  1196. vpn_progress(vpninfo, PRG_DEBUG,
  1197. _("No match for URI '%s'\n"),
  1198. str);
  1199. no_uri_match_silent:
  1200. free(url_proto);
  1201. free(url_host);
  1202. free(url_path);
  1203. OPENSSL_free(str);
  1204. }
  1205. }
  1206. GENERAL_NAMES_free(altnames);
  1207. /* According to RFC2818, we don't use the legacy subject name if
  1208. there was an altname with DNS type. */
  1209. if (altdns) {
  1210. vpn_progress(vpninfo, PRG_ERR,
  1211. _("No altname in peer cert matched '%s'\n"),
  1212. vpninfo->hostname);
  1213. return -EINVAL;
  1214. }
  1215. subjname = X509_get_subject_name(peer_cert);
  1216. if (!subjname) {
  1217. vpn_progress(vpninfo, PRG_ERR,
  1218. _("No subject name in peer cert!\n"));
  1219. return -EINVAL;
  1220. }
  1221. /* Find the _last_ (most specific) commonName */
  1222. i = -1;
  1223. while (1) {
  1224. int j = X509_NAME_get_index_by_NID(subjname, NID_commonName, i);
  1225. if (j >= 0)
  1226. i = j;
  1227. else
  1228. break;
  1229. }
  1230. subjasn1 = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subjname, i));
  1231. i = ASN1_STRING_to_UTF8((void *)&subjstr, subjasn1);
  1232. if (!subjstr || strlen(subjstr) != i) {
  1233. vpn_progress(vpninfo, PRG_ERR,
  1234. _("Failed to parse subject name in peer cert\n"));
  1235. return -EINVAL;
  1236. }
  1237. ret = 0;
  1238. if (match_hostname(vpninfo->hostname, subjstr)) {
  1239. vpn_progress(vpninfo, PRG_ERR,
  1240. _("Peer cert subject mismatch ('%s' != '%s')\n"),
  1241. subjstr, vpninfo->hostname);
  1242. ret = -EINVAL;
  1243. } else {
  1244. vpn_progress(vpninfo, PRG_DEBUG,
  1245. _("Matched peer certificate subject name '%s'\n"),
  1246. subjstr);
  1247. }
  1248. OPENSSL_free(subjstr);
  1249. return ret;
  1250. }
  1251. #else
  1252. static int match_cert_hostname(struct openconnect_info *vpninfo, X509 *peer_cert,
  1253. const unsigned char *ipaddr, int ipaddrlen)
  1254. {
  1255. char *matched = NULL;
  1256. if (ipaddrlen && X509_check_ip(peer_cert, ipaddr, ipaddrlen, 0) == 1) {
  1257. if (vpninfo->verbose >= PRG_DEBUG) {
  1258. char host[80];
  1259. int family;
  1260. if (ipaddrlen == 4)
  1261. family = AF_INET;
  1262. else
  1263. family = AF_INET6;
  1264. /* In Windows, the 'src' argument of inet_ntop() isn't const */
  1265. inet_ntop(family, (void *)ipaddr, host, sizeof(host));
  1266. vpn_progress(vpninfo, PRG_DEBUG,
  1267. _("Matched %s address '%s'\n"),
  1268. (family == AF_INET6) ? "IPv6" : "IPv4",
  1269. host);
  1270. }
  1271. return 0;
  1272. }
  1273. if (X509_check_host(peer_cert, vpninfo->hostname, 0, 0, &matched) == 1) {
  1274. vpn_progress(vpninfo, PRG_DEBUG,
  1275. _("Matched peer certificate subject name '%s'\n"),
  1276. matched);
  1277. OPENSSL_free(matched);
  1278. return 0;
  1279. }
  1280. /* We do it like this because these two strings are already
  1281. * translated in gnutls.c */
  1282. vpn_progress(vpninfo, PRG_INFO,
  1283. _("Server certificate verify failed: %s\n"),
  1284. _("certificate does not match hostname"));
  1285. return -EINVAL;
  1286. }
  1287. #endif /* OpenSSL < 1.0.2 */
  1288. /* Before OpenSSL 1.1 we could do this directly. And needed to. */
  1289. #ifndef SSL_CTX_get_extra_chain_certs_only
  1290. #define SSL_CTX_get_extra_chain_certs_only(ctx, st) \
  1291. (void)(*(st) = (ctx)->extra_certs)
  1292. #endif
  1293. static void workaround_openssl_certchain_bug(struct openconnect_info *vpninfo,
  1294. SSL *ssl)
  1295. {
  1296. /* OpenSSL has problems with certificate chains -- if there are
  1297. multiple certs with the same name, it doesn't necessarily
  1298. choose the _right_ one. (RT#1942)
  1299. Pick the right ones for ourselves and add them manually. */
  1300. X509 *cert = SSL_get_certificate(ssl);
  1301. X509 *cert2;
  1302. X509_STORE *store = SSL_CTX_get_cert_store(vpninfo->https_ctx);
  1303. X509_STORE_CTX *ctx;
  1304. void *extra_certs;
  1305. X509_STORE_CTX_get_issuer_fn issuer_fn;
  1306. if (!cert || !store)
  1307. return;
  1308. /* If we already have 'supporting' certs, don't add them again */
  1309. SSL_CTX_get_extra_chain_certs_only(vpninfo->https_ctx, &extra_certs);
  1310. if (extra_certs)
  1311. return;
  1312. ctx = X509_STORE_CTX_new();
  1313. if (!ctx)
  1314. return;
  1315. if (X509_STORE_CTX_init(ctx, store, NULL, NULL))
  1316. goto out;
  1317. issuer_fn = X509_STORE_CTX_get_get_issuer(ctx);
  1318. while (issuer_fn(&cert2, ctx, cert) == 1) {
  1319. char buf[200];
  1320. if (cert2 == cert)
  1321. break;
  1322. if (X509_check_issued(cert2, cert2) == X509_V_OK)
  1323. break;
  1324. cert = cert2;
  1325. X509_NAME_oneline(X509_get_subject_name(cert),
  1326. buf, sizeof(buf));
  1327. vpn_progress(vpninfo, PRG_DEBUG,
  1328. _("Extra cert from cafile: '%s'\n"), buf);
  1329. SSL_CTX_add_extra_chain_cert(vpninfo->https_ctx, cert);
  1330. }
  1331. out:
  1332. X509_STORE_CTX_free(ctx);
  1333. }
  1334. int openconnect_get_peer_cert_chain(struct openconnect_info *vpninfo,
  1335. struct oc_cert **chainp)
  1336. {
  1337. struct oc_cert *chain, *p;
  1338. X509_STORE_CTX *ctx = vpninfo->cert_list_handle;
  1339. STACK_OF(X509) *untrusted;
  1340. int i, cert_list_size;
  1341. if (!ctx)
  1342. return -EINVAL;
  1343. untrusted = X509_STORE_CTX_get0_untrusted(ctx);
  1344. if (!untrusted)
  1345. return -EINVAL;
  1346. cert_list_size = sk_X509_num(untrusted);
  1347. if (!cert_list_size)
  1348. return -EIO;
  1349. p = chain = calloc(cert_list_size, sizeof(struct oc_cert));
  1350. if (!chain)
  1351. return -ENOMEM;
  1352. for (i = 0; i < cert_list_size; i++, p++) {
  1353. X509 *cert = sk_X509_value(untrusted, i);
  1354. p->der_len = i2d_X509(cert, &p->der_data);
  1355. if (p->der_len < 0) {
  1356. openconnect_free_peer_cert_chain(vpninfo, chain);
  1357. return -ENOMEM;
  1358. }
  1359. }
  1360. *chainp = chain;
  1361. return cert_list_size;
  1362. }
  1363. void openconnect_free_peer_cert_chain(struct openconnect_info *vpninfo,
  1364. struct oc_cert *chain)
  1365. {
  1366. int i;
  1367. for (i = 0; i < vpninfo->cert_list_size; i++)
  1368. OPENSSL_free(chain[i].der_data);
  1369. free(chain);
  1370. }
  1371. static int ssl_app_verify_callback(X509_STORE_CTX *ctx, void *arg)
  1372. {
  1373. struct openconnect_info *vpninfo = arg;
  1374. const char *err_string = NULL;
  1375. X509 *cert = X509_STORE_CTX_get0_cert(ctx);
  1376. #ifdef X509_V_FLAG_PARTIAL_CHAIN
  1377. X509_VERIFY_PARAM *param;
  1378. #endif
  1379. if (vpninfo->peer_cert) {
  1380. /* This is a *rehandshake*. Require that the server
  1381. * presents exactly the same certificate as the
  1382. * first time. */
  1383. if (X509_cmp(cert, vpninfo->peer_cert)) {
  1384. vpn_progress(vpninfo, PRG_ERR, _("Server presented different cert on rehandshake\n"));
  1385. return 0;
  1386. }
  1387. vpn_progress(vpninfo, PRG_TRACE, _("Server presented identical cert on rehandshake\n"));
  1388. return 1;
  1389. }
  1390. vpninfo->peer_cert = cert;
  1391. X509_up_ref(cert);
  1392. set_peer_cert_hash(vpninfo);
  1393. #ifdef X509_V_FLAG_PARTIAL_CHAIN
  1394. param = X509_STORE_CTX_get0_param(ctx);
  1395. if (param)
  1396. X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_PARTIAL_CHAIN);
  1397. #endif
  1398. if (!X509_verify_cert(ctx)) {
  1399. err_string = X509_verify_cert_error_string(X509_STORE_CTX_get_error(ctx));
  1400. } else {
  1401. unsigned char addrbuf[sizeof(struct in6_addr)];
  1402. int addrlen = 0;
  1403. if (inet_pton(AF_INET, vpninfo->hostname, addrbuf) > 0)
  1404. addrlen = 4;
  1405. else if (inet_pton(AF_INET6, vpninfo->hostname, addrbuf) > 0)
  1406. addrlen = 16;
  1407. else if (vpninfo->hostname[0] == '[' &&
  1408. vpninfo->hostname[strlen(vpninfo->hostname)-1] == ']') {
  1409. char *p = &vpninfo->hostname[strlen(vpninfo->hostname)-1];
  1410. *p = 0;
  1411. if (inet_pton(AF_INET6, vpninfo->hostname + 1, addrbuf) > 0)
  1412. addrlen = 16;
  1413. *p = ']';
  1414. }
  1415. if (match_cert_hostname(vpninfo, vpninfo->peer_cert, addrbuf, addrlen))
  1416. err_string = _("certificate does not match hostname");
  1417. else
  1418. return 1;
  1419. }
  1420. vpn_progress(vpninfo, PRG_INFO,
  1421. _("Server certificate verify failed: %s\n"),
  1422. err_string);
  1423. if (vpninfo->validate_peer_cert) {
  1424. int ret;
  1425. vpninfo->cert_list_handle = ctx;
  1426. ret = vpninfo->validate_peer_cert(vpninfo->cbdata, err_string);
  1427. vpninfo->cert_list_handle = NULL;
  1428. if (!ret)
  1429. return 1;
  1430. }
  1431. return 0;
  1432. }
  1433. static int check_certificate_expiry(struct openconnect_info *vpninfo, struct cert_info *certinfo,
  1434. struct ossl_cert_info *oci)
  1435. {
  1436. method_const ASN1_TIME *notAfter;
  1437. const char *reason = NULL;
  1438. time_t t;
  1439. int i;
  1440. if (!oci->cert)
  1441. return 0;
  1442. t = time(NULL);
  1443. notAfter = X509_get0_notAfter(oci->cert);
  1444. i = X509_cmp_time(notAfter, &t);
  1445. if (!i) {
  1446. vpn_progress(vpninfo, PRG_ERR,
  1447. certinfo_string(certinfo, _("Error in client cert notAfter field\n"),
  1448. _("Error in secondary client cert notAfter field\n")));
  1449. return -EINVAL;
  1450. } else if (i < 0) {
  1451. reason = certinfo_string(certinfo, _("Client certificate has expired at"),
  1452. _("Secondary client certificate has expired at"));
  1453. } else {
  1454. t += vpninfo->cert_expire_warning;
  1455. i = X509_cmp_time(notAfter, &t);
  1456. if (i < 0)
  1457. reason = certinfo_string(certinfo, _("Client certificate expires soon at"),
  1458. _("Secondary client certificate expires soon at"));
  1459. }
  1460. if (reason) {
  1461. BIO *bp = BIO_new(BIO_s_mem());
  1462. BUF_MEM *bm;
  1463. const char *expiry = _("<error>");
  1464. char zero = 0;
  1465. if (bp) {
  1466. ASN1_TIME_print(bp, notAfter);
  1467. BIO_write(bp, &zero, 1);
  1468. BIO_get_mem_ptr(bp, &bm);
  1469. expiry = bm->data;
  1470. }
  1471. vpn_progress(vpninfo, PRG_ERR, "%s: %s\n", reason, expiry);
  1472. if (bp)
  1473. BIO_free(bp);
  1474. }
  1475. return 0;
  1476. }
  1477. static int load_primary_certificate(struct openconnect_info *vpninfo)
  1478. {
  1479. struct cert_info *certinfo = &vpninfo->certinfo[0];
  1480. struct ossl_cert_info *oci;
  1481. int ret = load_certificate(vpninfo, certinfo, 0);
  1482. oci = certinfo->priv_info;
  1483. if (!ret)
  1484. ret = install_ssl_ctx_certs(vpninfo, oci);
  1485. if (!ret && !SSL_CTX_check_private_key(vpninfo->https_ctx)) {
  1486. vpn_progress(vpninfo, PRG_ERR,
  1487. _("SSL certificate and key do not match\n"));
  1488. ret = -EINVAL;
  1489. }
  1490. if (!ret)
  1491. check_certificate_expiry(vpninfo, &vpninfo->certinfo[0], oci);
  1492. unload_certificate(certinfo, 1);
  1493. return ret;
  1494. }
  1495. int openconnect_install_ctx_verify(struct openconnect_info *vpninfo, SSL_CTX *ctx)
  1496. {
  1497. /* We've seen certificates in the wild which don't have the
  1498. purpose fields filled in correctly */
  1499. SSL_CTX_set_purpose(ctx, X509_PURPOSE_ANY);
  1500. SSL_CTX_set_cert_verify_callback(ctx, ssl_app_verify_callback,
  1501. vpninfo);
  1502. if (!vpninfo->no_system_trust)
  1503. SSL_CTX_set_default_verify_paths(ctx);
  1504. #ifdef ANDROID_KEYSTORE
  1505. if (vpninfo->cafile && !strncmp(vpninfo->cafile, "keystore:", 9)) {
  1506. STACK_OF(X509_INFO) *stack;
  1507. X509_STORE *store;
  1508. X509_INFO *info;
  1509. BIO *b = BIO_from_keystore(vpninfo, vpninfo->cafile);
  1510. if (!b)
  1511. return -EINVAL;
  1512. stack = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL);
  1513. BIO_free(b);
  1514. if (!stack) {
  1515. vpn_progress(vpninfo, PRG_ERR,
  1516. _("Failed to read certs from CA file '%s'\n"),
  1517. vpninfo->cafile);
  1518. openconnect_report_ssl_errors(vpninfo);
  1519. return -ENOENT;
  1520. }
  1521. store = SSL_CTX_get_cert_store(ctx);
  1522. while ((info = sk_X509_INFO_pop(stack))) {
  1523. if (info->x509)
  1524. X509_STORE_add_cert(store, info->x509);
  1525. if (info->crl)
  1526. X509_STORE_add_crl(store, info->crl);
  1527. X509_INFO_free(info);
  1528. }
  1529. sk_X509_INFO_free(stack);
  1530. } else
  1531. #endif
  1532. if (vpninfo->cafile) {
  1533. /* OpenSSL does actually manage to cope with UTF-8 for
  1534. this one, under Windows. So only convert for legacy
  1535. UNIX. */
  1536. char *cafile = openconnect_utf8_to_legacy(vpninfo,
  1537. vpninfo->cafile);
  1538. int err = SSL_CTX_load_verify_locations(ctx, cafile, NULL);
  1539. if (cafile != vpninfo->cafile)
  1540. free(cafile);
  1541. if (!err) {
  1542. vpn_progress(vpninfo, PRG_ERR,
  1543. _("Failed to open CA file '%s'\n"),
  1544. vpninfo->cafile);
  1545. openconnect_report_ssl_errors(vpninfo);
  1546. return -EINVAL;
  1547. }
  1548. }
  1549. return 0;
  1550. }
  1551. int openconnect_open_https(struct openconnect_info *vpninfo)
  1552. {
  1553. SSL *https_ssl;
  1554. BIO *https_bio;
  1555. int ssl_sock;
  1556. int err;
  1557. if (vpninfo->https_ssl)
  1558. return 0;
  1559. if (vpninfo->peer_cert) {
  1560. X509_free(vpninfo->peer_cert);
  1561. vpninfo->peer_cert = NULL;
  1562. }
  1563. free(vpninfo->peer_cert_hash);
  1564. vpninfo->peer_cert_hash = NULL;
  1565. free(vpninfo->cstp_cipher);
  1566. vpninfo->cstp_cipher = NULL;
  1567. ssl_sock = connect_https_socket(vpninfo);
  1568. if (ssl_sock < 0)
  1569. return ssl_sock;
  1570. if (!vpninfo->https_ctx) {
  1571. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  1572. vpninfo->https_ctx = SSL_CTX_new(SSLv23_client_method());
  1573. if (vpninfo->https_ctx)
  1574. SSL_CTX_set_options(vpninfo->https_ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
  1575. #else
  1576. vpninfo->https_ctx = SSL_CTX_new(TLS_client_method());
  1577. if (vpninfo->https_ctx &&
  1578. !SSL_CTX_set_min_proto_version(vpninfo->https_ctx, TLS1_VERSION)) {
  1579. SSL_CTX_free(vpninfo->https_ctx);
  1580. vpninfo->https_ctx = NULL;
  1581. }
  1582. #endif
  1583. if (!vpninfo->https_ctx) {
  1584. vpn_progress(vpninfo, PRG_ERR,
  1585. _("Create TLSv1 CTX failed\n"));
  1586. openconnect_report_ssl_errors(vpninfo);
  1587. return -EINVAL;
  1588. }
  1589. /* Try to work around the broken firewalls which reject ClientHello
  1590. * packets in certain size ranges. If we have SSL_OP_TLSEXT_PADDING
  1591. * use it, else fall back to SSL_OP_NO_TICKET which mostly worked for
  1592. * a long time. */
  1593. #if defined(SSL_OP_TLSEXT_PADDING)
  1594. SSL_CTX_set_options(vpninfo->https_ctx, SSL_OP_TLSEXT_PADDING);
  1595. #elif defined(SSL_OP_NO_TICKET)
  1596. SSL_CTX_set_options(vpninfo->https_ctx, SSL_OP_NO_TICKET);
  1597. #endif
  1598. #if OPENSSL_VERSION_NUMBER >= 0x010100000L
  1599. if (vpninfo->allow_insecure_crypto) {
  1600. /* OpenSSL versions after 1.1.0 added the notion of a "security level"
  1601. * that enforces checks on certificates and ciphers.
  1602. * These security levels overlap in functionality with the ciphersuite
  1603. * priority/allow-strings.
  1604. *
  1605. * For now we will set the security level to 0, thus reverting
  1606. * to the functionality seen in versions before 1.1.0. */
  1607. SSL_CTX_set_security_level(vpninfo->https_ctx, 0);
  1608. /* OpenSSL 3.0.0 refuses legacy renegotiation by default.
  1609. * Current versions of the Cisco ASA doesn't seem to cope */
  1610. SSL_CTX_set_options(vpninfo->https_ctx, SSL_OP_LEGACY_SERVER_CONNECT);
  1611. }
  1612. #endif
  1613. if (vpninfo->certinfo[0].cert) {
  1614. err = load_primary_certificate(vpninfo);
  1615. if (err) {
  1616. vpn_progress(vpninfo, PRG_ERR,
  1617. _("Loading certificate failed. Aborting.\n"));
  1618. SSL_CTX_free(vpninfo->https_ctx);
  1619. vpninfo->https_ctx = NULL;
  1620. closesocket(ssl_sock);
  1621. return err;
  1622. }
  1623. }
  1624. if (!vpninfo->ciphersuite_config) {
  1625. struct oc_text_buf *buf = buf_alloc();
  1626. if (vpninfo->pfs)
  1627. buf_append(buf, "HIGH:!aNULL:!eNULL:-RSA");
  1628. else if (vpninfo->allow_insecure_crypto)
  1629. buf_append(buf, "ALL");
  1630. else
  1631. buf_append(buf, "DEFAULT:-3DES:-RC4");
  1632. if (buf_error(buf)) {
  1633. vpn_progress(vpninfo, PRG_ERR,
  1634. _("Failed to construct OpenSSL cipher list\n"));
  1635. return buf_free(buf);
  1636. }
  1637. vpninfo->ciphersuite_config = buf->data;
  1638. buf->data = NULL;
  1639. buf_free(buf);
  1640. }
  1641. if (!SSL_CTX_set_cipher_list(vpninfo->https_ctx, vpninfo->ciphersuite_config)) {
  1642. vpn_progress(vpninfo, PRG_ERR,
  1643. _("Failed to set OpenSSL cipher list (\"%s\")\n"),
  1644. vpninfo->ciphersuite_config);
  1645. openconnect_report_ssl_errors(vpninfo);
  1646. SSL_CTX_free(vpninfo->https_ctx);
  1647. vpninfo->https_ctx = NULL;
  1648. closesocket(ssl_sock);
  1649. return -EIO;
  1650. }
  1651. err = openconnect_install_ctx_verify(vpninfo, vpninfo->https_ctx);
  1652. if (err) {
  1653. SSL_CTX_free(vpninfo->https_ctx);
  1654. vpninfo->https_ctx = NULL;
  1655. closesocket(ssl_sock);
  1656. return err;
  1657. }
  1658. }
  1659. https_ssl = SSL_new(vpninfo->https_ctx);
  1660. workaround_openssl_certchain_bug(vpninfo, https_ssl);
  1661. https_bio = BIO_new_socket(ssl_sock, BIO_NOCLOSE);
  1662. BIO_set_nbio(https_bio, 1);
  1663. SSL_set_bio(https_ssl, https_bio, https_bio);
  1664. /*
  1665. * If a ClientHello is between 256 and 511 bytes, the
  1666. * server cannot distinguish between a SSLv2 formatted
  1667. * packet and a SSLv3 formatted packet.
  1668. *
  1669. * F5 BIG-IP reverse proxies in particular will
  1670. * silently drop an ambiguous ClientHello.
  1671. *
  1672. * OpenSSL fixes this in v1.0.1g+ by padding ClientHello
  1673. * packets to at least 512 bytes.
  1674. *
  1675. * For older versions of OpenSSL, we try to avoid long
  1676. * packets by silently disabling extensions such as SNI.
  1677. *
  1678. * Discussion:
  1679. * https://www.ietf.org/mail-archive/web/tls/current/msg10423.html
  1680. *
  1681. * OpenSSL commits:
  1682. * 4fcdd66fff5fea0cfa1055c6680a76a4303f28a2
  1683. * cd6bd5ffda616822b52104fee0c4c7d623fd4f53
  1684. */
  1685. #if OPENSSL_VERSION_NUMBER >= 0x10001070 && !defined(LIBRESSL_VERSION_NUMBER)
  1686. if (string_is_hostname(vpninfo->hostname))
  1687. SSL_set_tlsext_host_name(https_ssl, vpninfo->hostname);
  1688. #endif
  1689. SSL_set_verify(https_ssl, SSL_VERIFY_PEER, NULL);
  1690. vpn_progress(vpninfo, PRG_INFO, _("SSL negotiation with %s\n"),
  1691. vpninfo->hostname);
  1692. while ((err = SSL_connect(https_ssl)) <= 0) {
  1693. fd_set wr_set, rd_set;
  1694. int maxfd = ssl_sock;
  1695. FD_ZERO(&wr_set);
  1696. FD_ZERO(&rd_set);
  1697. err = SSL_get_error(https_ssl, err);
  1698. if (err == SSL_ERROR_WANT_READ)
  1699. FD_SET(ssl_sock, &rd_set);
  1700. else if (err == SSL_ERROR_WANT_WRITE)
  1701. FD_SET(ssl_sock, &wr_set);
  1702. else {
  1703. vpn_progress(vpninfo, PRG_ERR, _("SSL connection failure\n"));
  1704. openconnect_report_ssl_errors(vpninfo);
  1705. SSL_free(https_ssl);
  1706. closesocket(ssl_sock);
  1707. return -EINVAL;
  1708. }
  1709. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  1710. select(maxfd + 1, &rd_set, &wr_set, NULL, NULL);
  1711. if (is_cancel_pending(vpninfo, &rd_set)) {
  1712. vpn_progress(vpninfo, PRG_ERR, _("SSL connection cancelled\n"));
  1713. SSL_free(https_ssl);
  1714. closesocket(ssl_sock);
  1715. return -EINVAL;
  1716. }
  1717. }
  1718. if (asprintf(&vpninfo->cstp_cipher, "%s-%s",
  1719. SSL_get_version(https_ssl), SSL_get_cipher_name(https_ssl)) < 0) {
  1720. SSL_free(https_ssl);
  1721. closesocket(ssl_sock);
  1722. return -ENOMEM;
  1723. }
  1724. vpninfo->ssl_fd = ssl_sock;
  1725. vpninfo->https_ssl = https_ssl;
  1726. vpninfo->ssl_read = openconnect_openssl_read;
  1727. vpninfo->ssl_write = openconnect_openssl_write;
  1728. vpninfo->ssl_gets = openconnect_openssl_gets;
  1729. vpn_progress(vpninfo, PRG_INFO, _("Connected to HTTPS on %s with ciphersuite %s\n"),
  1730. vpninfo->hostname, vpninfo->cstp_cipher);
  1731. return 0;
  1732. }
  1733. int cstp_handshake(struct openconnect_info *vpninfo, unsigned init)
  1734. {
  1735. return -EOPNOTSUPP;
  1736. }
  1737. void openconnect_close_https(struct openconnect_info *vpninfo, int final)
  1738. {
  1739. if (vpninfo->https_ssl) {
  1740. SSL_free(vpninfo->https_ssl);
  1741. vpninfo->https_ssl = NULL;
  1742. }
  1743. if (vpninfo->ssl_fd != -1) {
  1744. unmonitor_fd(vpninfo, ssl);
  1745. closesocket(vpninfo->ssl_fd);
  1746. vpninfo->ssl_fd = -1;
  1747. }
  1748. if (final) {
  1749. if (vpninfo->https_ctx) {
  1750. SSL_CTX_free(vpninfo->https_ctx);
  1751. vpninfo->https_ctx = NULL;
  1752. }
  1753. if (vpninfo->cert_x509) {
  1754. X509_free(vpninfo->cert_x509);
  1755. vpninfo->cert_x509 = NULL;
  1756. }
  1757. }
  1758. }
  1759. int openconnect_init_ssl(void)
  1760. {
  1761. #ifdef _WIN32
  1762. int ret = openconnect__win32_sock_init();
  1763. if (ret)
  1764. return ret;
  1765. #endif
  1766. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  1767. SSL_library_init();
  1768. ERR_clear_error();
  1769. SSL_load_error_strings();
  1770. OpenSSL_add_all_algorithms();
  1771. #endif
  1772. return 0;
  1773. }
  1774. char *openconnect_get_peer_cert_details(struct openconnect_info *vpninfo)
  1775. {
  1776. BIO *bp = BIO_new(BIO_s_mem());
  1777. BUF_MEM *certinfo;
  1778. char zero = 0;
  1779. char *ret;
  1780. X509_print_ex(bp, vpninfo->peer_cert, 0, 0);
  1781. BIO_write(bp, &zero, 1);
  1782. BIO_get_mem_ptr(bp, &certinfo);
  1783. ret = strdup(certinfo->data);
  1784. BIO_free(bp);
  1785. return ret;
  1786. }
  1787. void openconnect_free_cert_info(struct openconnect_info *vpninfo,
  1788. void *buf)
  1789. {
  1790. free(buf);
  1791. }
  1792. int openconnect_local_cert_md5(struct openconnect_info *vpninfo,
  1793. char *buf)
  1794. {
  1795. buf[0] = 0;
  1796. if (!vpninfo->cert_x509)
  1797. return -EIO;
  1798. if (get_cert_md5_fingerprint(vpninfo, vpninfo->cert_x509, buf))
  1799. return -EIO;
  1800. return 0;
  1801. }
  1802. #ifdef HAVE_LIBPCSCLITE
  1803. int openconnect_hash_yubikey_password(struct openconnect_info *vpninfo,
  1804. const char *password, int pwlen,
  1805. const void *ident, int id_len)
  1806. {
  1807. if (!PKCS5_PBKDF2_HMAC_SHA1(password, pwlen, ident, id_len, 1000, 16,
  1808. vpninfo->yubikey_pwhash))
  1809. return -EIO;
  1810. return 0;
  1811. }
  1812. int openconnect_yubikey_chalresp(struct openconnect_info *vpninfo,
  1813. const void *challenge, int chall_len, void *result)
  1814. {
  1815. unsigned int mdlen = SHA1_SIZE;
  1816. if (!HMAC(EVP_sha1(), vpninfo->yubikey_pwhash, 16, challenge, chall_len, result, &mdlen))
  1817. return -EIO;
  1818. return 0;
  1819. }
  1820. #endif
  1821. int hotp_hmac(struct openconnect_info *vpninfo, const void *challenge)
  1822. {
  1823. unsigned char hash[64]; /* Enough for a SHA256 */
  1824. unsigned int hashlen = sizeof(hash);
  1825. const EVP_MD *alg;
  1826. switch(vpninfo->oath_hmac_alg) {
  1827. case OATH_ALG_HMAC_SHA1:
  1828. alg = EVP_sha1();
  1829. break;
  1830. case OATH_ALG_HMAC_SHA256:
  1831. alg = EVP_sha256();
  1832. break;
  1833. case OATH_ALG_HMAC_SHA512:
  1834. alg = EVP_sha512();
  1835. break;
  1836. default:
  1837. vpn_progress(vpninfo, PRG_ERR,
  1838. _("Unsupported OATH HMAC algorithm\n"));
  1839. return -EINVAL;
  1840. }
  1841. if (!HMAC(alg, vpninfo->oath_secret, vpninfo->oath_secret_len,
  1842. challenge, 8, hash, &hashlen)) {
  1843. vpninfo->progress(vpninfo, PRG_ERR,
  1844. _("Failed to calculate OATH HMAC\n"));
  1845. openconnect_report_ssl_errors(vpninfo);
  1846. return -EINVAL;
  1847. }
  1848. hashlen = hash[hashlen - 1] & 15;
  1849. return load_be32(&hash[hashlen]) & 0x7fffffff;
  1850. }
  1851. static long ttls_ctrl_func(BIO *b, int cmd, long larg, void *iarg);
  1852. static int ttls_pull_func(BIO *b, char *buf, int len);
  1853. static int ttls_push_func(BIO *b, const char *buf, int len);
  1854. #ifdef HAVE_BIO_METH_FREE
  1855. static BIO_METHOD *eap_ttls_method(void)
  1856. {
  1857. BIO_METHOD *meth = BIO_meth_new(BIO_get_new_index(), "EAP-TTLS");
  1858. BIO_meth_set_write(meth, ttls_push_func);
  1859. BIO_meth_set_read(meth, ttls_pull_func);
  1860. BIO_meth_set_ctrl(meth, ttls_ctrl_func);
  1861. return meth;
  1862. }
  1863. #else /* !HAVE_BIO_METH_FREE */
  1864. #define BIO_TYPE_EAP_TTLS 0x80
  1865. static BIO_METHOD ttls_bio_meth = {
  1866. .type = BIO_TYPE_EAP_TTLS,
  1867. .name = "EAP-TTLS",
  1868. .bwrite = ttls_push_func,
  1869. .bread = ttls_pull_func,
  1870. .ctrl = ttls_ctrl_func,
  1871. };
  1872. static BIO_METHOD *eap_ttls_method(void)
  1873. {
  1874. return &ttls_bio_meth;
  1875. }
  1876. static inline void BIO_set_data(BIO *b, void *p)
  1877. {
  1878. b->ptr = p;
  1879. }
  1880. static inline void *BIO_get_data(BIO *b)
  1881. {
  1882. return b->ptr;
  1883. }
  1884. static void BIO_set_init(BIO *b, int i)
  1885. {
  1886. b->init = i;
  1887. }
  1888. #endif /* !HAVE_BIO_METH_FREE */
  1889. static int ttls_push_func(BIO *b, const char *buf, int len)
  1890. {
  1891. struct openconnect_info *vpninfo = BIO_get_data(b);
  1892. int ret = pulse_eap_ttls_send(vpninfo, buf, len);
  1893. if (ret >= 0)
  1894. return ret;
  1895. return 0;
  1896. }
  1897. static int ttls_pull_func(BIO *b, char *buf, int len)
  1898. {
  1899. struct openconnect_info *vpninfo = BIO_get_data(b);
  1900. int ret = pulse_eap_ttls_recv(vpninfo, buf, len);
  1901. if (ret >= 0)
  1902. return ret;
  1903. return 0;
  1904. }
  1905. static long ttls_ctrl_func(BIO *b, int cmd, long larg, void *iarg)
  1906. {
  1907. switch(cmd) {
  1908. case BIO_CTRL_FLUSH:
  1909. return 1;
  1910. default:
  1911. return 0;
  1912. }
  1913. }
  1914. void *establish_eap_ttls(struct openconnect_info *vpninfo)
  1915. {
  1916. SSL *ttls_ssl = NULL;
  1917. BIO *bio;
  1918. int err;
  1919. if (!vpninfo->ttls_bio_meth)
  1920. vpninfo->ttls_bio_meth = eap_ttls_method();
  1921. bio = BIO_new(vpninfo->ttls_bio_meth);
  1922. BIO_set_data(bio, vpninfo);
  1923. BIO_set_init(bio, 1);
  1924. ttls_ssl = SSL_new(vpninfo->https_ctx);
  1925. workaround_openssl_certchain_bug(vpninfo, ttls_ssl);
  1926. SSL_set_bio(ttls_ssl, bio, bio);
  1927. SSL_set_verify(ttls_ssl, SSL_VERIFY_PEER, NULL);
  1928. vpn_progress(vpninfo, PRG_INFO, _("EAP-TTLS negotiation with %s\n"),
  1929. vpninfo->hostname);
  1930. err = SSL_connect(ttls_ssl);
  1931. if (err == 1) {
  1932. vpn_progress(vpninfo, PRG_TRACE,
  1933. _("Established EAP-TTLS session\n"));
  1934. return ttls_ssl;
  1935. }
  1936. err = SSL_get_error(ttls_ssl, err);
  1937. vpn_progress(vpninfo, PRG_ERR, _("EAP-TTLS connection failure %d\n"), err);
  1938. openconnect_report_ssl_errors(vpninfo);
  1939. SSL_free(ttls_ssl);
  1940. return NULL;
  1941. }
  1942. void destroy_eap_ttls(struct openconnect_info *vpninfo, void *ttls)
  1943. {
  1944. SSL_free(ttls);
  1945. /* Leave the BIO_METH for now. It may get reused and we don't want to
  1946. * have to call BIO_get_new_index() more times than is necessary */
  1947. }
  1948. #ifdef HAVE_HPKE_SUPPORT
  1949. static int generate_strap_key(EC_KEY **key, char **pubkey,
  1950. unsigned char *privder_in, int privderlen,
  1951. unsigned char **pubder, int *pubderlen)
  1952. {
  1953. EC_KEY *lkey;
  1954. struct oc_text_buf *buf = NULL;
  1955. unsigned char *der = NULL;
  1956. int len;
  1957. if (privder_in) {
  1958. lkey = d2i_ECPrivateKey(NULL, (const unsigned char **)&privder_in, privderlen);
  1959. if (!lkey)
  1960. return -EIO;
  1961. } else {
  1962. lkey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1963. if (!lkey)
  1964. return -EIO;
  1965. if (!EC_KEY_generate_key(lkey)) {
  1966. EC_KEY_free(lkey);
  1967. return -EIO;
  1968. }
  1969. }
  1970. len = i2d_EC_PUBKEY(lkey, &der);
  1971. buf = buf_alloc();
  1972. buf_append_base64(buf, der, len, 0);
  1973. if (buf_error(buf)) {
  1974. EC_KEY_free(lkey);
  1975. free(der);
  1976. return buf_free(buf);
  1977. }
  1978. /* All done. There are no failure modes from here on, so
  1979. * install the resulting key/pubkey/etc. where the caller
  1980. * asked us to, freeing the previous ones if needed. */
  1981. EC_KEY_free(*key);
  1982. *key = lkey;
  1983. free(*pubkey);
  1984. *pubkey = buf->data;
  1985. /* If the caller wants the DER, give it to them */
  1986. if (pubder && pubderlen) {
  1987. *pubder = der;
  1988. *pubderlen = len;
  1989. } else {
  1990. free(der);
  1991. }
  1992. buf->data = NULL;
  1993. buf_free(buf);
  1994. return 0;
  1995. }
  1996. int generate_strap_keys(struct openconnect_info *vpninfo)
  1997. {
  1998. int err;
  1999. err = generate_strap_key(&vpninfo->strap_key, &vpninfo->strap_pubkey,
  2000. NULL, 0, NULL, NULL);
  2001. if (err) {
  2002. vpn_progress(vpninfo, PRG_ERR,
  2003. _("Failed to generate STRAP key"));
  2004. openconnect_report_ssl_errors(vpninfo);
  2005. free_strap_keys(vpninfo);
  2006. return -EIO;
  2007. }
  2008. err = generate_strap_key(&vpninfo->strap_dh_key, &vpninfo->strap_dh_pubkey,
  2009. NULL, 0, NULL, NULL);
  2010. if (err) {
  2011. vpn_progress(vpninfo, PRG_ERR,
  2012. _("Failed to generate STRAP DH key\n"));
  2013. openconnect_report_ssl_errors(vpninfo);
  2014. free_strap_keys(vpninfo);
  2015. return -EIO;
  2016. }
  2017. return 0;
  2018. }
  2019. void free_strap_keys(struct openconnect_info *vpninfo)
  2020. {
  2021. if (vpninfo->strap_key)
  2022. EC_KEY_free(vpninfo->strap_key);
  2023. if (vpninfo->strap_dh_key)
  2024. EC_KEY_free(vpninfo->strap_dh_key);
  2025. vpninfo->strap_key = vpninfo->strap_dh_key = NULL;
  2026. }
  2027. int ingest_strap_privkey(struct openconnect_info *vpninfo, unsigned char *der, int len)
  2028. {
  2029. if (generate_strap_key(&vpninfo->strap_key,
  2030. &vpninfo->strap_pubkey, der, len, NULL, 0)) {
  2031. vpn_progress(vpninfo, PRG_ERR,
  2032. _("Failed to decode STRAP key\n"));
  2033. openconnect_report_ssl_errors(vpninfo);
  2034. return -EIO;
  2035. }
  2036. return 0;
  2037. }
  2038. void append_strap_privkey(struct openconnect_info *vpninfo,
  2039. struct oc_text_buf *buf)
  2040. {
  2041. unsigned char *der = NULL;
  2042. int derlen = i2d_ECPrivateKey(vpninfo->strap_key, &der);
  2043. if (derlen > 0)
  2044. buf_append_base64(buf, der, derlen, 0);
  2045. }
  2046. #include <openssl/kdf.h>
  2047. int ecdh_compute_secp256r1(struct openconnect_info *vpninfo, const unsigned char *pubkey,
  2048. int pubkey_len, unsigned char *secret)
  2049. {
  2050. const EC_POINT *point;
  2051. EC_KEY *pkey;
  2052. int ret = 0;
  2053. if (!(pkey = d2i_EC_PUBKEY(NULL, &pubkey, pubkey_len)) ||
  2054. !(point = EC_KEY_get0_public_key(pkey))) {
  2055. vpn_progress(vpninfo, PRG_ERR,
  2056. _("Failed to decode server DH key\n"));
  2057. openconnect_report_ssl_errors(vpninfo);
  2058. ret = -EIO;
  2059. goto out;
  2060. }
  2061. /* Perform the DH secret derivation from our STRAP-DH key
  2062. * and the one the server returned to us in the payload. */
  2063. if (ECDH_compute_key(secret, 32, point, vpninfo->strap_dh_key, NULL) <= 0) {
  2064. vpn_progress(vpninfo, PRG_ERR, _("Failed to compute DH secret\n"));
  2065. openconnect_report_ssl_errors(vpninfo);
  2066. ret = -EIO;
  2067. }
  2068. out:
  2069. EC_KEY_free(pkey);
  2070. return ret;
  2071. }
  2072. int hkdf_sha256_extract_expand(struct openconnect_info *vpninfo, unsigned char *buf,
  2073. const unsigned char *info, int infolen)
  2074. {
  2075. size_t buflen = 32;
  2076. int ret = 0;
  2077. /* Next, use HKDF to generate the actual key used for encryption. */
  2078. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
  2079. if (!ctx || !EVP_PKEY_derive_init(ctx) ||
  2080. !EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) ||
  2081. !EVP_PKEY_CTX_set1_hkdf_key(ctx, buf, buflen) ||
  2082. !EVP_PKEY_CTX_hkdf_mode(ctx, EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) ||
  2083. !EVP_PKEY_CTX_add1_hkdf_info(ctx, info, infolen) ||
  2084. EVP_PKEY_derive(ctx, buf, &buflen) != 1) {
  2085. vpn_progress(vpninfo, PRG_ERR, _("HKDF key derivation failed\n"));
  2086. openconnect_report_ssl_errors(vpninfo);
  2087. ret = -EINVAL;
  2088. }
  2089. EVP_PKEY_CTX_free(ctx);
  2090. return ret;
  2091. }
  2092. int aes_256_gcm_decrypt(struct openconnect_info *vpninfo, unsigned char *key,
  2093. unsigned char *data, int len,
  2094. unsigned char *iv, unsigned char *tag)
  2095. {
  2096. /* Finally, we actually decrypt the sso-token */
  2097. EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
  2098. int ret = 0, i = 0;
  2099. if (!cctx ||
  2100. !EVP_DecryptInit_ex(cctx, EVP_aes_256_gcm(), NULL, key, iv) ||
  2101. !EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_SET_TAG, 12, tag) ||
  2102. !EVP_DecryptUpdate(cctx, data, &len, data, len) ||
  2103. !EVP_DecryptFinal(cctx, NULL, &i)) {
  2104. vpn_progress(vpninfo, PRG_ERR, _("SSO token decryption failed\n"));
  2105. openconnect_report_ssl_errors(vpninfo);
  2106. ret = -EINVAL;
  2107. }
  2108. EVP_CIPHER_CTX_free(cctx);
  2109. return ret;
  2110. }
  2111. void append_strap_verify(struct openconnect_info *vpninfo,
  2112. struct oc_text_buf *buf, int rekey)
  2113. {
  2114. unsigned char finished[64];
  2115. size_t flen = SSL_get_finished(vpninfo->https_ssl, finished, sizeof(finished));
  2116. if (flen > sizeof(finished)) {
  2117. vpn_progress(vpninfo, PRG_ERR,
  2118. _("SSL Finished message too large (%zd bytes)\n"), flen);
  2119. if (!buf_error(buf))
  2120. buf->error = -EIO;
  2121. return;
  2122. }
  2123. /* If we're rekeying, we need to sign the Verify header with the *old* key. */
  2124. EVP_PKEY *evpkey = EVP_PKEY_new();
  2125. if (!evpkey || EVP_PKEY_set1_EC_KEY(evpkey, vpninfo->strap_key) <= 0) {
  2126. vpn_progress(vpninfo, PRG_ERR,
  2127. _("STRAP signature failed\n"));
  2128. fail_errors:
  2129. openconnect_report_ssl_errors(vpninfo);
  2130. fail_pkey:
  2131. if (!buf_error(buf))
  2132. buf->error = -EIO;
  2133. EVP_PKEY_free(evpkey);
  2134. return;
  2135. }
  2136. unsigned char *pubkey_der = NULL;
  2137. int pubkey_derlen = 0;
  2138. if (rekey) {
  2139. if (generate_strap_key(&vpninfo->strap_key, &vpninfo->strap_pubkey,
  2140. NULL, 0, &pubkey_der, &pubkey_derlen)) {
  2141. vpn_progress(vpninfo, PRG_ERR,
  2142. _("Failed to regenerate STRAP key\n"));
  2143. goto fail_errors;
  2144. }
  2145. } else {
  2146. pubkey_der = openconnect_base64_decode(&pubkey_derlen, vpninfo->strap_pubkey);
  2147. if (!pubkey_der) {
  2148. vpn_progress(vpninfo, PRG_ERR,
  2149. _("Failed to generate STRAP key DER\n"));
  2150. goto fail_pkey;
  2151. }
  2152. }
  2153. EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  2154. const EVP_MD *md = EVP_sha256(); /* We only support prime256v1 for now */
  2155. unsigned char signature_bin[128];
  2156. size_t siglen = sizeof(signature_bin);
  2157. int ok = (mdctx &&
  2158. EVP_DigestSignInit(mdctx, NULL, md, NULL, evpkey) > 0 &&
  2159. EVP_DigestSignUpdate(mdctx, finished, flen) > 0 &&
  2160. EVP_DigestSignUpdate(mdctx, pubkey_der, pubkey_derlen) > 0 &&
  2161. EVP_DigestSignFinal(mdctx, (void *)signature_bin, &siglen) > 0);
  2162. EVP_MD_CTX_free(mdctx);
  2163. EVP_PKEY_free(evpkey);
  2164. free(pubkey_der);
  2165. if (!ok) {
  2166. vpn_progress(vpninfo, PRG_ERR,
  2167. _("STRAP signature failed\n"));
  2168. goto fail_errors;
  2169. }
  2170. buf_append_base64(buf, signature_bin, siglen, 0);
  2171. }
  2172. #endif /* HAVE_HPKE_SUPPORT */
  2173. int export_certificate_pkcs7(struct openconnect_info *vpninfo,
  2174. struct cert_info *certinfo,
  2175. cert_format_t format,
  2176. struct oc_text_buf **pp7b)
  2177. {
  2178. struct ossl_cert_info *oci;
  2179. PKCS7 *p7 = NULL;
  2180. BIO *bio = NULL;
  2181. BUF_MEM *bptr = NULL;
  2182. struct oc_text_buf *p7b = NULL;
  2183. int ret, ok;
  2184. if (!(certinfo && (oci = certinfo->priv_info) && pp7b))
  2185. return -EINVAL;
  2186. /* We have the client certificate in 'oci.cert' and *optionally*
  2187. * a stack of intermediate certs in oci.extra_certs. For the TLS
  2188. * connection those would be used by SSL_CTX_use_certificate() and
  2189. * SSL_CTX_add_extra_chain_cert() respectively. For PKCS7_sign()
  2190. * we need the actual cert at the head of the stack, so *create*
  2191. * one if needed, and insert oci.cert at position zero. */
  2192. if (!oci->extra_certs)
  2193. oci->extra_certs = sk_X509_new_null();
  2194. if (!oci->extra_certs)
  2195. goto err;
  2196. if (!sk_X509_insert(oci->extra_certs, oci->cert, 0))
  2197. goto err;
  2198. X509_up_ref(oci->cert);
  2199. p7 = PKCS7_sign(NULL, NULL, oci->extra_certs, NULL, PKCS7_DETACHED);
  2200. if (!p7) {
  2201. err:
  2202. vpn_progress(vpninfo, PRG_ERR,
  2203. _("Failed to create PKCS#7 structure\n"));
  2204. ret = -EIO;
  2205. goto out;
  2206. }
  2207. ret = 0;
  2208. bio = BIO_new(BIO_s_mem());
  2209. if (!bio) {
  2210. ret = -ENOMEM;
  2211. goto pkcs7_error;
  2212. }
  2213. if (format == CERT_FORMAT_ASN1) {
  2214. ok = i2d_PKCS7_bio(bio, p7);
  2215. } else if (format == CERT_FORMAT_PEM) {
  2216. ok = PEM_write_bio_PKCS7(bio, p7);
  2217. } else {
  2218. ret = -EINVAL;
  2219. goto pkcs7_error;
  2220. }
  2221. if (!ok) {
  2222. ret = -EIO;
  2223. goto pkcs7_error;
  2224. }
  2225. BIO_get_mem_ptr(bio, &bptr);
  2226. p7b = buf_alloc();
  2227. if (!p7b)
  2228. ret = -ENOMEM;
  2229. if (ret < 0) {
  2230. pkcs7_error:
  2231. vpn_progress(vpninfo, PRG_ERR,
  2232. _("Failed to output PKCS#7 structure\n"));
  2233. goto out;
  2234. }
  2235. BIO_set_close(bio, BIO_NOCLOSE);
  2236. p7b->data = bptr->data;
  2237. p7b->pos = bptr->length;
  2238. *pp7b = p7b;
  2239. p7b = NULL;
  2240. out:
  2241. buf_free(p7b);
  2242. BIO_free(bio);
  2243. if (p7)
  2244. PKCS7_free(p7);
  2245. return ret;
  2246. }
  2247. int multicert_sign_data(struct openconnect_info *vpninfo,
  2248. struct cert_info *certinfo,
  2249. unsigned int hashes,
  2250. const void *chdata, size_t chdata_len,
  2251. struct oc_text_buf **psignature)
  2252. {
  2253. struct table_entry {
  2254. openconnect_hash_type id;
  2255. const EVP_MD *(*evp_md_fn)(void);
  2256. };
  2257. static struct table_entry table[] = {
  2258. { OPENCONNECT_HASH_SHA512, &EVP_sha512 },
  2259. { OPENCONNECT_HASH_SHA384, &EVP_sha384 },
  2260. { OPENCONNECT_HASH_SHA256, &EVP_sha256 },
  2261. { OPENCONNECT_HASH_UNKNOWN },
  2262. };
  2263. struct ossl_cert_info *oci;
  2264. struct oc_text_buf *signature;
  2265. openconnect_hash_type hash;
  2266. int ret;
  2267. /**
  2268. * Check preconditions...
  2269. */
  2270. if (!(certinfo && (oci = certinfo->priv_info)
  2271. && hashes && chdata && chdata_len && psignature))
  2272. return -EINVAL;
  2273. *psignature = NULL;
  2274. signature = buf_alloc();
  2275. if (!signature)
  2276. goto out_of_memory;
  2277. for (const struct table_entry *entry = table;
  2278. (hash = entry->id) != OPENCONNECT_HASH_UNKNOWN;
  2279. entry++) {
  2280. if ((hashes & MULTICERT_HASH_FLAG(hash)) == 0)
  2281. continue;
  2282. EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  2283. if (!mdctx)
  2284. goto out_of_memory;
  2285. const EVP_MD *md = (*entry->evp_md_fn)();
  2286. size_t siglen = 0;
  2287. int ok = (EVP_DigestSignInit(mdctx, NULL, md, NULL, oci->key) > 0 &&
  2288. EVP_DigestSignUpdate(mdctx, chdata, chdata_len) > 0 &&
  2289. EVP_DigestSignFinal(mdctx, NULL, &siglen) > 0 &&
  2290. !buf_ensure_space(signature, siglen) &&
  2291. EVP_DigestSignFinal(mdctx, (void *)signature->data, &siglen) > 0);
  2292. EVP_MD_CTX_free(mdctx);
  2293. if (ok) {
  2294. signature->pos = siglen;
  2295. *psignature = signature;
  2296. return hash;
  2297. }
  2298. }
  2299. /** Error path */
  2300. ret = -EIO;
  2301. if (buf_error(signature)) {
  2302. out_of_memory:
  2303. ret = -ENOMEM;
  2304. }
  2305. buf_free(signature);
  2306. vpn_progress(vpninfo, PRG_ERR,
  2307. _("Failed to generate signature for multiple certificate authentication\n"));
  2308. openconnect_report_ssl_errors(vpninfo);
  2309. return ret;
  2310. }