xform_esp.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. /* $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
  2. /*-
  3. * The authors of this code are John Ioannidis (ji@tla.org),
  4. * Angelos D. Keromytis (kermit@csd.uch.gr) and
  5. * Niels Provos (provos@physnet.uni-hamburg.de).
  6. *
  7. * The original version of this code was written by John Ioannidis
  8. * for BSD/OS in Athens, Greece, in November 1995.
  9. *
  10. * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
  11. * by Angelos D. Keromytis.
  12. *
  13. * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
  14. * and Niels Provos.
  15. *
  16. * Additional features in 1999 by Angelos D. Keromytis.
  17. *
  18. * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
  19. * Angelos D. Keromytis and Niels Provos.
  20. * Copyright (c) 2001 Angelos D. Keromytis.
  21. *
  22. * Permission to use, copy, and modify this software with or without fee
  23. * is hereby granted, provided that this entire notice is included in
  24. * all copies of any software which is or includes a copy or
  25. * modification of this software.
  26. * You may use this code under the GNU public license if you so wish. Please
  27. * contribute changes back to the authors under this freer than GPL license
  28. * so that we may further the use of strong encryption without limitations to
  29. * all.
  30. *
  31. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
  32. * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
  33. * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
  34. * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
  35. * PURPOSE.
  36. */
  37. #include "opt_inet.h"
  38. #include "opt_inet6.h"
  39. #include "opt_ipsec.h"
  40. #include <sys/param.h>
  41. #include <sys/systm.h>
  42. #include <sys/malloc.h>
  43. #include <sys/mbuf.h>
  44. #include <sys/socket.h>
  45. #include <sys/syslog.h>
  46. #include <sys/kernel.h>
  47. #include <sys/lock.h>
  48. #include <sys/random.h>
  49. #include <sys/mutex.h>
  50. #include <sys/sysctl.h>
  51. #include <sys/mutex.h>
  52. #include <machine/atomic.h>
  53. #include <net/if.h>
  54. #include <net/vnet.h>
  55. #include <netinet/in.h>
  56. #include <netinet/in_systm.h>
  57. #include <netinet/ip.h>
  58. #include <netinet/ip_ecn.h>
  59. #include <netinet/ip6.h>
  60. #include <netipsec/ipsec.h>
  61. #include <netipsec/ah.h>
  62. #include <netipsec/ah_var.h>
  63. #include <netipsec/esp.h>
  64. #include <netipsec/esp_var.h>
  65. #include <netipsec/xform.h>
  66. #ifdef INET6
  67. #include <netinet6/ip6_var.h>
  68. #include <netipsec/ipsec6.h>
  69. #include <netinet6/ip6_ecn.h>
  70. #endif
  71. #include <netipsec/key.h>
  72. #include <netipsec/key_debug.h>
  73. #include <opencrypto/cryptodev.h>
  74. #include <opencrypto/xform.h>
  75. #define SPI_SIZE 4
  76. VNET_DEFINE(int, esp_enable) = 1;
  77. VNET_DEFINE(int, esp_ctr_compatibility) = 1;
  78. VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
  79. VNET_PCPUSTAT_SYSINIT(espstat);
  80. #ifdef VIMAGE
  81. VNET_PCPUSTAT_SYSUNINIT(espstat);
  82. #endif /* VIMAGE */
  83. SYSCTL_DECL(_net_inet_esp);
  84. SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
  85. CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
  86. SYSCTL_INT(_net_inet_esp, OID_AUTO, ctr_compatibility,
  87. CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_ctr_compatibility), 0,
  88. "Align AES-CTR encrypted transmitted frames to blocksize");
  89. SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
  90. struct espstat, espstat,
  91. "ESP statistics (struct espstat, netipsec/esp_var.h");
  92. static MALLOC_DEFINE(M_ESP, "esp", "IPsec ESP");
  93. static int esp_input_cb(struct cryptop *op);
  94. static int esp_output_cb(struct cryptop *crp);
  95. size_t
  96. esp_hdrsiz(struct secasvar *sav)
  97. {
  98. size_t size;
  99. if (sav != NULL) {
  100. /*XXX not right for null algorithm--does it matter??*/
  101. IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
  102. ("SA with null xform"));
  103. if (sav->flags & SADB_X_EXT_OLD)
  104. size = sizeof (struct esp);
  105. else
  106. size = sizeof (struct newesp);
  107. size += sav->tdb_encalgxform->blocksize + 9;
  108. /*XXX need alg check???*/
  109. if (sav->tdb_authalgxform != NULL && sav->replay)
  110. size += ah_hdrsiz(sav);
  111. } else {
  112. /*
  113. * base header size
  114. * + max iv length for CBC mode
  115. * + max pad length
  116. * + sizeof (pad length field)
  117. * + sizeof (next header field)
  118. * + max icv supported.
  119. */
  120. size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
  121. }
  122. return size;
  123. }
  124. /*
  125. * esp_init() is called when an SPI is being set up.
  126. */
  127. static int
  128. esp_init(struct secasvar *sav, struct xformsw *xsp)
  129. {
  130. const struct enc_xform *txform;
  131. struct crypto_session_params csp;
  132. int keylen;
  133. int error;
  134. txform = enc_algorithm_lookup(sav->alg_enc);
  135. if (txform == NULL) {
  136. DPRINTF(("%s: unsupported encryption algorithm %d\n",
  137. __func__, sav->alg_enc));
  138. return EINVAL;
  139. }
  140. if (sav->key_enc == NULL) {
  141. DPRINTF(("%s: no encoding key for %s algorithm\n",
  142. __func__, txform->name));
  143. return EINVAL;
  144. }
  145. if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
  146. SADB_X_EXT_IV4B) {
  147. DPRINTF(("%s: 4-byte IV not supported with protocol\n",
  148. __func__));
  149. return EINVAL;
  150. }
  151. /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
  152. keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4 -
  153. SAV_ISCHACHA(sav) * 4;
  154. if (txform->minkey > keylen || keylen > txform->maxkey) {
  155. DPRINTF(("%s: invalid key length %u, must be in the range "
  156. "[%u..%u] for algorithm %s\n", __func__,
  157. keylen, txform->minkey, txform->maxkey,
  158. txform->name));
  159. return EINVAL;
  160. }
  161. if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
  162. sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
  163. else
  164. sav->ivlen = txform->ivsize;
  165. memset(&csp, 0, sizeof(csp));
  166. /*
  167. * Setup AH-related state.
  168. */
  169. if (sav->alg_auth != 0) {
  170. error = ah_init0(sav, xsp, &csp);
  171. if (error)
  172. return error;
  173. }
  174. /* NB: override anything set in ah_init0 */
  175. sav->tdb_xform = xsp;
  176. sav->tdb_encalgxform = txform;
  177. /*
  178. * Whenever AES-GCM is used for encryption, one
  179. * of the AES authentication algorithms is chosen
  180. * as well, based on the key size.
  181. */
  182. if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
  183. switch (keylen) {
  184. case AES_128_GMAC_KEY_LEN:
  185. sav->alg_auth = SADB_X_AALG_AES128GMAC;
  186. sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
  187. break;
  188. case AES_192_GMAC_KEY_LEN:
  189. sav->alg_auth = SADB_X_AALG_AES192GMAC;
  190. sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
  191. break;
  192. case AES_256_GMAC_KEY_LEN:
  193. sav->alg_auth = SADB_X_AALG_AES256GMAC;
  194. sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
  195. break;
  196. default:
  197. DPRINTF(("%s: invalid key length %u"
  198. "for algorithm %s\n", __func__,
  199. keylen, txform->name));
  200. return EINVAL;
  201. }
  202. csp.csp_mode = CSP_MODE_AEAD;
  203. if (sav->flags & SADB_X_SAFLAGS_ESN)
  204. csp.csp_flags |= CSP_F_SEPARATE_AAD;
  205. } else if (sav->alg_enc == SADB_X_EALG_CHACHA20POLY1305) {
  206. sav->alg_auth = SADB_X_AALG_CHACHA20POLY1305;
  207. sav->tdb_authalgxform = &auth_hash_poly1305;
  208. csp.csp_mode = CSP_MODE_AEAD;
  209. if (sav->flags & SADB_X_SAFLAGS_ESN)
  210. csp.csp_flags |= CSP_F_SEPARATE_AAD;
  211. } else if (sav->alg_auth != 0) {
  212. csp.csp_mode = CSP_MODE_ETA;
  213. if (sav->flags & SADB_X_SAFLAGS_ESN)
  214. csp.csp_flags |= CSP_F_ESN;
  215. } else
  216. csp.csp_mode = CSP_MODE_CIPHER;
  217. /* Initialize crypto session. */
  218. csp.csp_cipher_alg = sav->tdb_encalgxform->type;
  219. if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
  220. csp.csp_cipher_key = sav->key_enc->key_data;
  221. csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
  222. SAV_ISCTRORGCM(sav) * 4 - SAV_ISCHACHA(sav) * 4;
  223. };
  224. csp.csp_ivlen = txform->ivsize;
  225. error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
  226. return error;
  227. }
  228. static void
  229. esp_cleanup(struct secasvar *sav)
  230. {
  231. crypto_freesession(sav->tdb_cryptoid);
  232. sav->tdb_cryptoid = NULL;
  233. sav->tdb_authalgxform = NULL;
  234. sav->tdb_encalgxform = NULL;
  235. }
  236. /*
  237. * ESP input processing, called (eventually) through the protocol switch.
  238. */
  239. static int
  240. esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
  241. {
  242. IPSEC_DEBUG_DECLARE(char buf[128]);
  243. const struct auth_hash *esph;
  244. const struct enc_xform *espx;
  245. struct xform_data *xd;
  246. struct cryptop *crp;
  247. struct newesp *esp;
  248. uint8_t *ivp;
  249. crypto_session_t cryptoid;
  250. int alen, error, hlen, plen;
  251. uint32_t seqh;
  252. const struct crypto_session_params *csp;
  253. SECASVAR_RLOCK_TRACKER;
  254. IPSEC_ASSERT(sav != NULL, ("null SA"));
  255. IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
  256. error = EINVAL;
  257. /* Valid IP Packet length ? */
  258. if ( (skip&3) || (m->m_pkthdr.len&3) ){
  259. DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
  260. __func__, skip, m->m_pkthdr.len));
  261. ESPSTAT_INC(esps_badilen);
  262. goto bad;
  263. }
  264. if (m->m_len < skip + sizeof(*esp)) {
  265. m = m_pullup(m, skip + sizeof(*esp));
  266. if (m == NULL) {
  267. DPRINTF(("%s: cannot pullup header\n", __func__));
  268. ESPSTAT_INC(esps_hdrops); /*XXX*/
  269. error = ENOBUFS;
  270. goto bad;
  271. }
  272. }
  273. esp = (struct newesp *)(mtod(m, caddr_t) + skip);
  274. esph = sav->tdb_authalgxform;
  275. espx = sav->tdb_encalgxform;
  276. /* Determine the ESP header and auth length */
  277. if (sav->flags & SADB_X_EXT_OLD)
  278. hlen = sizeof (struct esp) + sav->ivlen;
  279. else
  280. hlen = sizeof (struct newesp) + sav->ivlen;
  281. alen = xform_ah_authsize(esph);
  282. /*
  283. * Verify payload length is multiple of encryption algorithm
  284. * block size.
  285. *
  286. * NB: This works for the null algorithm because the blocksize
  287. * is 4 and all packets must be 4-byte aligned regardless
  288. * of the algorithm.
  289. */
  290. plen = m->m_pkthdr.len - (skip + hlen + alen);
  291. if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
  292. DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
  293. " SA %s/%08lx\n", __func__, plen, espx->blocksize,
  294. ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
  295. (u_long)ntohl(sav->spi)));
  296. ESPSTAT_INC(esps_badilen);
  297. goto bad;
  298. }
  299. /*
  300. * Check sequence number.
  301. */
  302. SECASVAR_RLOCK(sav);
  303. if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
  304. if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
  305. SECASVAR_RUNLOCK(sav);
  306. DPRINTF(("%s: packet replay check for %s\n", __func__,
  307. ipsec_sa2str(sav, buf, sizeof(buf))));
  308. ESPSTAT_INC(esps_replay);
  309. error = EACCES;
  310. goto bad;
  311. }
  312. seqh = htonl(seqh);
  313. }
  314. cryptoid = sav->tdb_cryptoid;
  315. SECASVAR_RUNLOCK(sav);
  316. /* Update the counters */
  317. ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
  318. /* Get crypto descriptors */
  319. crp = crypto_getreq(cryptoid, M_NOWAIT);
  320. if (crp == NULL) {
  321. DPRINTF(("%s: failed to acquire crypto descriptors\n",
  322. __func__));
  323. ESPSTAT_INC(esps_crypto);
  324. error = ENOBUFS;
  325. goto bad;
  326. }
  327. /* Get IPsec-specific opaque pointer */
  328. xd = malloc(sizeof(*xd), M_ESP, M_NOWAIT | M_ZERO);
  329. if (xd == NULL) {
  330. DPRINTF(("%s: failed to allocate xform_data\n", __func__));
  331. goto xd_fail;
  332. }
  333. if (esph != NULL) {
  334. crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
  335. if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
  336. crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
  337. else
  338. crp->crp_aad_length = hlen;
  339. csp = crypto_get_params(crp->crp_session);
  340. if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
  341. (sav->replay != NULL) && (sav->replay->wsize != 0)) {
  342. int aad_skip;
  343. crp->crp_aad_length += sizeof(seqh);
  344. crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
  345. if (crp->crp_aad == NULL) {
  346. DPRINTF(("%s: failed to allocate xform_data\n",
  347. __func__));
  348. goto crp_aad_fail;
  349. }
  350. /* SPI */
  351. m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
  352. aad_skip = SPI_SIZE;
  353. /* ESN */
  354. bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
  355. aad_skip += sizeof(seqh);
  356. /* Rest of aad */
  357. if (crp->crp_aad_length - aad_skip > 0)
  358. m_copydata(m, skip + SPI_SIZE,
  359. crp->crp_aad_length - aad_skip,
  360. (char *)crp->crp_aad + aad_skip);
  361. } else
  362. crp->crp_aad_start = skip;
  363. if (csp->csp_flags & CSP_F_ESN &&
  364. sav->replay != NULL && sav->replay->wsize != 0)
  365. memcpy(crp->crp_esn, &seqh, sizeof(seqh));
  366. crp->crp_digest_start = m->m_pkthdr.len - alen;
  367. }
  368. /* Crypto operation descriptor */
  369. crp->crp_flags = CRYPTO_F_CBIFSYNC;
  370. crypto_use_mbuf(crp, m);
  371. crp->crp_callback = esp_input_cb;
  372. crp->crp_opaque = xd;
  373. /* These are passed as-is to the callback */
  374. xd->sav = sav;
  375. xd->protoff = protoff;
  376. xd->skip = skip;
  377. xd->cryptoid = cryptoid;
  378. xd->vnet = curvnet;
  379. /* Decryption descriptor */
  380. crp->crp_op |= CRYPTO_OP_DECRYPT;
  381. crp->crp_payload_start = skip + hlen;
  382. crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
  383. /* Generate or read cipher IV. */
  384. if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
  385. ivp = &crp->crp_iv[0];
  386. /*
  387. * AES-GCM and AES-CTR use similar cipher IV formats
  388. * defined in RFC 4106 section 4 and RFC 3686 section
  389. * 4, respectively.
  390. *
  391. * The first 4 bytes of the cipher IV contain an
  392. * implicit salt, or nonce, obtained from the last 4
  393. * bytes of the encryption key. The next 8 bytes hold
  394. * an explicit IV unique to each packet. This
  395. * explicit IV is used as the ESP IV for the packet.
  396. * The last 4 bytes hold a big-endian block counter
  397. * incremented for each block. For AES-GCM, the block
  398. * counter's initial value is defined as part of the
  399. * algorithm. For AES-CTR, the block counter's
  400. * initial value for each packet is defined as 1 by
  401. * RFC 3686.
  402. *
  403. * ------------------------------------------
  404. * | Salt | Explicit ESP IV | Block Counter |
  405. * ------------------------------------------
  406. * 4 bytes 8 bytes 4 bytes
  407. */
  408. memcpy(ivp, sav->key_enc->key_data +
  409. _KEYLEN(sav->key_enc) - 4, 4);
  410. m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
  411. if (SAV_ISCTR(sav)) {
  412. be32enc(&ivp[sav->ivlen + 4], 1);
  413. }
  414. crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
  415. } else if (sav->ivlen != 0)
  416. crp->crp_iv_start = skip + hlen - sav->ivlen;
  417. if (V_async_crypto)
  418. return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
  419. else
  420. return (crypto_dispatch(crp));
  421. crp_aad_fail:
  422. free(xd, M_ESP);
  423. xd_fail:
  424. crypto_freereq(crp);
  425. ESPSTAT_INC(esps_crypto);
  426. error = ENOBUFS;
  427. bad:
  428. m_freem(m);
  429. key_freesav(&sav);
  430. return (error);
  431. }
  432. /*
  433. * ESP input callback from the crypto driver.
  434. */
  435. static int
  436. esp_input_cb(struct cryptop *crp)
  437. {
  438. IPSEC_DEBUG_DECLARE(char buf[128]);
  439. uint8_t lastthree[3];
  440. const struct auth_hash *esph;
  441. struct mbuf *m;
  442. struct xform_data *xd;
  443. struct secasvar *sav;
  444. struct secasindex *saidx;
  445. crypto_session_t cryptoid;
  446. int hlen, skip, protoff, error, alen;
  447. SECASVAR_RLOCK_TRACKER;
  448. m = crp->crp_buf.cb_mbuf;
  449. xd = crp->crp_opaque;
  450. CURVNET_SET(xd->vnet);
  451. sav = xd->sav;
  452. if (sav->state >= SADB_SASTATE_DEAD) {
  453. /* saidx is freed */
  454. DPRINTF(("%s: dead SA %p spi %#x\n", __func__, sav, sav->spi));
  455. ESPSTAT_INC(esps_notdb);
  456. error = ESRCH;
  457. goto bad;
  458. }
  459. skip = xd->skip;
  460. protoff = xd->protoff;
  461. cryptoid = xd->cryptoid;
  462. saidx = &sav->sah->saidx;
  463. esph = sav->tdb_authalgxform;
  464. /* Check for crypto errors */
  465. if (crp->crp_etype) {
  466. if (crp->crp_etype == EAGAIN) {
  467. /* Reset the session ID */
  468. if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
  469. crypto_freesession(cryptoid);
  470. xd->cryptoid = crp->crp_session;
  471. CURVNET_RESTORE();
  472. return (crypto_dispatch(crp));
  473. }
  474. /* EBADMSG indicates authentication failure. */
  475. if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
  476. ESPSTAT_INC(esps_noxform);
  477. DPRINTF(("%s: crypto error %d\n", __func__,
  478. crp->crp_etype));
  479. error = crp->crp_etype;
  480. goto bad;
  481. }
  482. }
  483. /* Shouldn't happen... */
  484. if (m == NULL) {
  485. ESPSTAT_INC(esps_crypto);
  486. DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
  487. error = EINVAL;
  488. goto bad;
  489. }
  490. ESPSTAT_INC(esps_hist[sav->alg_enc]);
  491. /* If authentication was performed, check now. */
  492. if (esph != NULL) {
  493. alen = xform_ah_authsize(esph);
  494. AHSTAT_INC(ahs_hist[sav->alg_auth]);
  495. if (crp->crp_etype == EBADMSG) {
  496. DPRINTF(("%s: authentication hash mismatch for "
  497. "packet in SA %s/%08lx\n", __func__,
  498. ipsec_address(&saidx->dst, buf, sizeof(buf)),
  499. (u_long) ntohl(sav->spi)));
  500. ESPSTAT_INC(esps_badauth);
  501. error = EACCES;
  502. goto bad;
  503. }
  504. m->m_flags |= M_AUTHIPDGM;
  505. /* Remove trailing authenticator */
  506. m_adj(m, -alen);
  507. }
  508. /* Release the crypto descriptors */
  509. free(xd, M_ESP), xd = NULL;
  510. free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
  511. crypto_freereq(crp), crp = NULL;
  512. /*
  513. * Packet is now decrypted.
  514. */
  515. m->m_flags |= M_DECRYPTED;
  516. /*
  517. * Update replay sequence number, if appropriate.
  518. */
  519. if (sav->replay) {
  520. u_int32_t seq;
  521. m_copydata(m, skip + offsetof(struct newesp, esp_seq),
  522. sizeof (seq), (caddr_t) &seq);
  523. SECASVAR_RLOCK(sav);
  524. if (ipsec_updatereplay(ntohl(seq), sav)) {
  525. SECASVAR_RUNLOCK(sav);
  526. DPRINTF(("%s: packet replay check for %s\n", __func__,
  527. ipsec_sa2str(sav, buf, sizeof(buf))));
  528. ESPSTAT_INC(esps_replay);
  529. error = EACCES;
  530. goto bad;
  531. }
  532. SECASVAR_RUNLOCK(sav);
  533. }
  534. /* Determine the ESP header length */
  535. if (sav->flags & SADB_X_EXT_OLD)
  536. hlen = sizeof (struct esp) + sav->ivlen;
  537. else
  538. hlen = sizeof (struct newesp) + sav->ivlen;
  539. /* Remove the ESP header and IV from the mbuf. */
  540. error = m_striphdr(m, skip, hlen);
  541. if (error) {
  542. ESPSTAT_INC(esps_hdrops);
  543. DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
  544. ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
  545. (u_long) ntohl(sav->spi)));
  546. goto bad;
  547. }
  548. /* Save the last three bytes of decrypted data */
  549. m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
  550. /* Verify pad length */
  551. if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
  552. ESPSTAT_INC(esps_badilen);
  553. DPRINTF(("%s: invalid padding length %d for %u byte packet "
  554. "in SA %s/%08lx\n", __func__, lastthree[1],
  555. m->m_pkthdr.len - skip,
  556. ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
  557. (u_long) ntohl(sav->spi)));
  558. error = EINVAL;
  559. goto bad;
  560. }
  561. /* Verify correct decryption by checking the last padding bytes */
  562. if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
  563. if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
  564. ESPSTAT_INC(esps_badenc);
  565. DPRINTF(("%s: decryption failed for packet in "
  566. "SA %s/%08lx\n", __func__, ipsec_address(
  567. &sav->sah->saidx.dst, buf, sizeof(buf)),
  568. (u_long) ntohl(sav->spi)));
  569. error = EINVAL;
  570. goto bad;
  571. }
  572. }
  573. /*
  574. * RFC4303 2.6:
  575. * Silently drop packet if next header field is IPPROTO_NONE.
  576. */
  577. if (lastthree[2] == IPPROTO_NONE)
  578. goto bad;
  579. /* Trim the mbuf chain to remove trailing authenticator and padding */
  580. m_adj(m, -(lastthree[1] + 2));
  581. /* Restore the Next Protocol field */
  582. m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
  583. switch (saidx->dst.sa.sa_family) {
  584. #ifdef INET6
  585. case AF_INET6:
  586. error = ipsec6_common_input_cb(m, sav, skip, protoff);
  587. break;
  588. #endif
  589. #ifdef INET
  590. case AF_INET:
  591. error = ipsec4_common_input_cb(m, sav, skip, protoff);
  592. break;
  593. #endif
  594. default:
  595. panic("%s: Unexpected address family: %d saidx=%p", __func__,
  596. saidx->dst.sa.sa_family, saidx);
  597. }
  598. CURVNET_RESTORE();
  599. return error;
  600. bad:
  601. if (sav != NULL)
  602. key_freesav(&sav);
  603. if (m != NULL)
  604. m_freem(m);
  605. if (xd != NULL)
  606. free(xd, M_ESP);
  607. if (crp != NULL) {
  608. free(crp->crp_aad, M_ESP);
  609. crypto_freereq(crp);
  610. }
  611. CURVNET_RESTORE();
  612. return error;
  613. }
  614. /*
  615. * ESP output routine, called by ipsec[46]_perform_request().
  616. */
  617. static int
  618. esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
  619. u_int idx, int skip, int protoff)
  620. {
  621. IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
  622. struct cryptop *crp;
  623. const struct auth_hash *esph;
  624. const struct enc_xform *espx;
  625. struct mbuf *mo = NULL;
  626. struct xform_data *xd;
  627. struct secasindex *saidx;
  628. unsigned char *pad;
  629. uint8_t *ivp;
  630. uint64_t cntr;
  631. crypto_session_t cryptoid;
  632. int hlen, rlen, padding, blks, alen, i, roff;
  633. int error, maxpacketsize;
  634. uint8_t prot;
  635. uint32_t seqh;
  636. const struct crypto_session_params *csp;
  637. SECASVAR_RLOCK_TRACKER;
  638. IPSEC_ASSERT(sav != NULL, ("null SA"));
  639. esph = sav->tdb_authalgxform;
  640. espx = sav->tdb_encalgxform;
  641. IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
  642. if (sav->flags & SADB_X_EXT_OLD)
  643. hlen = sizeof (struct esp) + sav->ivlen;
  644. else
  645. hlen = sizeof (struct newesp) + sav->ivlen;
  646. rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
  647. /*
  648. * RFC4303 2.4 Requires 4 byte alignment.
  649. * Old versions of FreeBSD can't decrypt partial blocks encrypted
  650. * with AES-CTR. Align payload to native_blocksize (16 bytes)
  651. * in order to preserve compatibility.
  652. */
  653. if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
  654. blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
  655. else
  656. blks = MAX(4, espx->blocksize);
  657. /* XXX clamp padding length a la KAME??? */
  658. padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
  659. alen = xform_ah_authsize(esph);
  660. ESPSTAT_INC(esps_output);
  661. saidx = &sav->sah->saidx;
  662. /* Check for maximum packet size violations. */
  663. switch (saidx->dst.sa.sa_family) {
  664. #ifdef INET
  665. case AF_INET:
  666. maxpacketsize = IP_MAXPACKET;
  667. break;
  668. #endif /* INET */
  669. #ifdef INET6
  670. case AF_INET6:
  671. maxpacketsize = IPV6_MAXPACKET;
  672. break;
  673. #endif /* INET6 */
  674. default:
  675. DPRINTF(("%s: unknown/unsupported protocol "
  676. "family %d, SA %s/%08lx\n", __func__,
  677. saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
  678. buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
  679. ESPSTAT_INC(esps_nopf);
  680. error = EPFNOSUPPORT;
  681. goto bad;
  682. }
  683. /*
  684. DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
  685. __func__, skip, hlen, rlen, padding, alen, blks)); */
  686. if (skip + hlen + rlen + padding + alen > maxpacketsize) {
  687. DPRINTF(("%s: packet in SA %s/%08lx got too big "
  688. "(len %u, max len %u)\n", __func__,
  689. ipsec_address(&saidx->dst, buf, sizeof(buf)),
  690. (u_long) ntohl(sav->spi),
  691. skip + hlen + rlen + padding + alen, maxpacketsize));
  692. ESPSTAT_INC(esps_toobig);
  693. error = EMSGSIZE;
  694. goto bad;
  695. }
  696. /* Update the counters. */
  697. ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
  698. m = m_unshare(m, M_NOWAIT);
  699. if (m == NULL) {
  700. DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
  701. ipsec_address(&saidx->dst, buf, sizeof(buf)),
  702. (u_long) ntohl(sav->spi)));
  703. ESPSTAT_INC(esps_hdrops);
  704. error = ENOBUFS;
  705. goto bad;
  706. }
  707. /* Inject ESP header. */
  708. mo = m_makespace(m, skip, hlen, &roff);
  709. if (mo == NULL) {
  710. DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
  711. __func__, hlen, ipsec_address(&saidx->dst, buf,
  712. sizeof(buf)), (u_long) ntohl(sav->spi)));
  713. ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
  714. error = ENOBUFS;
  715. goto bad;
  716. }
  717. /* Initialize ESP header. */
  718. bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
  719. sizeof(uint32_t));
  720. SECASVAR_RLOCK(sav);
  721. if (sav->replay) {
  722. uint32_t replay;
  723. SECREPLAY_LOCK(sav->replay);
  724. #ifdef REGRESSION
  725. /* Emulate replay attack when ipsec_replay is TRUE. */
  726. if (!V_ipsec_replay)
  727. #endif
  728. sav->replay->count++;
  729. replay = htonl((uint32_t)sav->replay->count);
  730. bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
  731. sizeof(uint32_t), sizeof(uint32_t));
  732. seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
  733. SECREPLAY_UNLOCK(sav->replay);
  734. }
  735. cryptoid = sav->tdb_cryptoid;
  736. if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
  737. cntr = sav->cntr++;
  738. SECASVAR_RUNLOCK(sav);
  739. /*
  740. * Add padding -- better to do it ourselves than use the crypto engine,
  741. * although if/when we support compression, we'd have to do that.
  742. */
  743. pad = (u_char *) m_pad(m, padding + alen);
  744. if (pad == NULL) {
  745. DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
  746. ipsec_address(&saidx->dst, buf, sizeof(buf)),
  747. (u_long) ntohl(sav->spi)));
  748. m = NULL; /* NB: free'd by m_pad */
  749. error = ENOBUFS;
  750. goto bad;
  751. }
  752. /*
  753. * Add padding: random, zero, or self-describing.
  754. * XXX catch unexpected setting
  755. */
  756. switch (sav->flags & SADB_X_EXT_PMASK) {
  757. case SADB_X_EXT_PRAND:
  758. arc4random_buf(pad, padding - 2);
  759. break;
  760. case SADB_X_EXT_PZERO:
  761. bzero(pad, padding - 2);
  762. break;
  763. case SADB_X_EXT_PSEQ:
  764. for (i = 0; i < padding - 2; i++)
  765. pad[i] = i+1;
  766. break;
  767. }
  768. /* Fix padding length and Next Protocol in padding itself. */
  769. pad[padding - 2] = padding - 2;
  770. m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
  771. /* Fix Next Protocol in IPv4/IPv6 header. */
  772. prot = IPPROTO_ESP;
  773. m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
  774. /* Get crypto descriptor. */
  775. crp = crypto_getreq(cryptoid, M_NOWAIT);
  776. if (crp == NULL) {
  777. DPRINTF(("%s: failed to acquire crypto descriptor\n",
  778. __func__));
  779. ESPSTAT_INC(esps_crypto);
  780. error = ENOBUFS;
  781. goto bad;
  782. }
  783. /* IPsec-specific opaque crypto info. */
  784. xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
  785. if (xd == NULL) {
  786. DPRINTF(("%s: failed to allocate xform_data\n", __func__));
  787. goto xd_fail;
  788. }
  789. /* Encryption descriptor. */
  790. crp->crp_payload_start = skip + hlen;
  791. crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
  792. crp->crp_op = CRYPTO_OP_ENCRYPT;
  793. /* Generate cipher and ESP IVs. */
  794. ivp = &crp->crp_iv[0];
  795. if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
  796. /*
  797. * See comment in esp_input() for details on the
  798. * cipher IV. A simple per-SA counter stored in
  799. * 'cntr' is used as the explicit ESP IV.
  800. */
  801. memcpy(ivp, sav->key_enc->key_data +
  802. _KEYLEN(sav->key_enc) - 4, 4);
  803. be64enc(&ivp[4], cntr);
  804. if (SAV_ISCTR(sav)) {
  805. be32enc(&ivp[sav->ivlen + 4], 1);
  806. }
  807. m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
  808. crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
  809. } else if (sav->ivlen != 0) {
  810. arc4rand(ivp, sav->ivlen, 0);
  811. crp->crp_iv_start = skip + hlen - sav->ivlen;
  812. m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
  813. }
  814. /* Callback parameters */
  815. xd->sp = sp;
  816. xd->sav = sav;
  817. xd->idx = idx;
  818. xd->cryptoid = cryptoid;
  819. xd->vnet = curvnet;
  820. /* Crypto operation descriptor. */
  821. crp->crp_flags |= CRYPTO_F_CBIFSYNC;
  822. crypto_use_mbuf(crp, m);
  823. crp->crp_callback = esp_output_cb;
  824. crp->crp_opaque = xd;
  825. if (esph) {
  826. /* Authentication descriptor. */
  827. crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
  828. if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
  829. crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
  830. else
  831. crp->crp_aad_length = hlen;
  832. csp = crypto_get_params(crp->crp_session);
  833. if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
  834. sav->replay != NULL) {
  835. int aad_skip;
  836. crp->crp_aad_length += sizeof(seqh);
  837. crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
  838. if (crp->crp_aad == NULL) {
  839. DPRINTF(("%s: failed to allocate xform_data\n",
  840. __func__));
  841. goto crp_aad_fail;
  842. }
  843. /* SPI */
  844. m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
  845. aad_skip = SPI_SIZE;
  846. /* ESN */
  847. bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
  848. aad_skip += sizeof(seqh);
  849. /* Rest of aad */
  850. if (crp->crp_aad_length - aad_skip > 0)
  851. m_copydata(m, skip + SPI_SIZE,
  852. crp->crp_aad_length - aad_skip,
  853. (char *)crp->crp_aad + aad_skip);
  854. } else
  855. crp->crp_aad_start = skip;
  856. if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
  857. memcpy(crp->crp_esn, &seqh, sizeof(seqh));
  858. crp->crp_digest_start = m->m_pkthdr.len - alen;
  859. }
  860. if (V_async_crypto)
  861. return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
  862. else
  863. return (crypto_dispatch(crp));
  864. crp_aad_fail:
  865. free(xd, M_ESP);
  866. xd_fail:
  867. crypto_freereq(crp);
  868. ESPSTAT_INC(esps_crypto);
  869. error = ENOBUFS;
  870. bad:
  871. if (m)
  872. m_freem(m);
  873. key_freesav(&sav);
  874. key_freesp(&sp);
  875. return (error);
  876. }
  877. /*
  878. * ESP output callback from the crypto driver.
  879. */
  880. static int
  881. esp_output_cb(struct cryptop *crp)
  882. {
  883. struct xform_data *xd;
  884. struct secpolicy *sp;
  885. struct secasvar *sav;
  886. struct mbuf *m;
  887. crypto_session_t cryptoid;
  888. u_int idx;
  889. int error;
  890. xd = (struct xform_data *) crp->crp_opaque;
  891. CURVNET_SET(xd->vnet);
  892. m = crp->crp_buf.cb_mbuf;
  893. sp = xd->sp;
  894. sav = xd->sav;
  895. idx = xd->idx;
  896. cryptoid = xd->cryptoid;
  897. /* Check for crypto errors. */
  898. if (crp->crp_etype) {
  899. if (crp->crp_etype == EAGAIN) {
  900. /* Reset the session ID */
  901. if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
  902. crypto_freesession(cryptoid);
  903. xd->cryptoid = crp->crp_session;
  904. CURVNET_RESTORE();
  905. return (crypto_dispatch(crp));
  906. }
  907. ESPSTAT_INC(esps_noxform);
  908. DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
  909. error = crp->crp_etype;
  910. m_freem(m);
  911. goto bad;
  912. }
  913. /* Shouldn't happen... */
  914. if (m == NULL) {
  915. ESPSTAT_INC(esps_crypto);
  916. DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
  917. error = EINVAL;
  918. goto bad;
  919. }
  920. free(xd, M_ESP);
  921. free(crp->crp_aad, M_ESP);
  922. crypto_freereq(crp);
  923. ESPSTAT_INC(esps_hist[sav->alg_enc]);
  924. if (sav->tdb_authalgxform != NULL)
  925. AHSTAT_INC(ahs_hist[sav->alg_auth]);
  926. #ifdef REGRESSION
  927. /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
  928. if (V_ipsec_integrity) {
  929. static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
  930. const struct auth_hash *esph;
  931. /*
  932. * Corrupt HMAC if we want to test integrity verification of
  933. * the other side.
  934. */
  935. esph = sav->tdb_authalgxform;
  936. if (esph != NULL) {
  937. int alen;
  938. alen = xform_ah_authsize(esph);
  939. m_copyback(m, m->m_pkthdr.len - alen,
  940. alen, ipseczeroes);
  941. }
  942. }
  943. #endif
  944. /* NB: m is reclaimed by ipsec_process_done. */
  945. error = ipsec_process_done(m, sp, sav, idx);
  946. CURVNET_RESTORE();
  947. return (error);
  948. bad:
  949. free(xd, M_ESP);
  950. free(crp->crp_aad, M_ESP);
  951. crypto_freereq(crp);
  952. key_freesav(&sav);
  953. key_freesp(&sp);
  954. CURVNET_RESTORE();
  955. return (error);
  956. }
  957. static struct xformsw esp_xformsw = {
  958. .xf_type = XF_ESP,
  959. .xf_name = "IPsec ESP",
  960. .xf_init = esp_init,
  961. .xf_cleanup = esp_cleanup,
  962. .xf_input = esp_input,
  963. .xf_output = esp_output,
  964. };
  965. SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
  966. xform_attach, &esp_xformsw);
  967. SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
  968. xform_detach, &esp_xformsw);