1 /*
   2  * This file and its contents are supplied under the terms of the
   3  * Common Development and Distribution License ("CDDL"), version 1.0.
   4  * You may only use this file in accordance with the terms of version
   5  * 1.0 of the CDDL.
   6  *
   7  * A full copy of the text of the CDDL should have accompanied this
   8  * source.  A copy of the CDDL is also available via the Internet at
   9  * http://www.illumos.org/license/CDDL.
  10  */
  11 
  12 /*
  13  * Copyright 2017 Jason King.
  14  * Copyright (c) 2017, Joyent, Inc.
  15  */
  16 
  17 #include <stddef.h>
  18 #include <assert.h>
  19 #include <umem.h>
  20 #include <string.h>
  21 #include <errno.h>
  22 #include <sys/types.h>
  23 #include <sys/byteorder.h>
  24 #include <netinet/in.h>
  25 #include <security/cryptoki.h>
  26 #include <errno.h>
  27 #include <sys/socket.h>
  28 #include <pthread.h>
  29 #include <sys/debug.h>
  30 #include <note.h>
  31 #include <stdarg.h>
  32 #include <alloca.h>
  33 #include "defs.h"
  34 #include "pkt_impl.h"
  35 #include "ikev2.h"
  36 #include "ikev2_sa.h"
  37 #include "ikev2_pkt.h"
  38 #include "ikev2_enum.h"
  39 #include "pkcs11.h"
  40 #include "random.h"
  41 
  42 #define PKT_IS_V2(p) \
  43         (IKE_GET_MAJORV((p)->header.version) == IKE_GET_MAJORV(IKEV2_VERSION))
  44 
  45 /* Allocate an outbound IKEv2 pkt for an initiator of the given exchange type */
  46 pkt_t *
  47 ikev2_pkt_new_initiator(ikev2_sa_t *i2sa, ikev2_exch_t exch_type)
  48 {
  49         pkt_t *pkt;
  50 
  51         pkt = pkt_out_alloc(I2SA_LOCAL_SPI(i2sa),
  52             I2SA_REMOTE_SPI(i2sa),
  53             IKEV2_VERSION,
  54             exch_type, 0);
  55         if (pkt == NULL)
  56                 return (NULL);
  57 
  58         pkt->pkt_header.flags = IKEV2_FLAG_INITIATOR;
  59         return (pkt);
  60 }
  61 
  62 /* Allocate a ikev2_pkt_t for an IKEv2 outbound response */
  63 pkt_t *
  64 ikev2_pkt_new_response(const pkt_t *init)
  65 {
  66         pkt_t *pkt;
  67 
  68         ASSERT(PKT_IS_V2(init));
  69 
  70         pkt = pkt_out_alloc(init->pkt_header.initiator_spi,
  71             init->pkt_header.responder_spi,
  72             IKEV2_VERSION,
  73             init->pkt_header.exch_type,
  74             init->pkt_header.msgid);
  75         if (pkt == NULL)
  76                 return (NULL);
  77 
  78         pkt->pkt_header.flags = IKEV2_FLAG_RESPONSE;
  79         return (pkt);
  80 }
  81 
  82 struct validate_data {
  83         pkt_t           *pkt;
  84         size_t          notify_count;
  85         size_t          payload_count[IKEV2_NUM_PAYLOADS];
  86         boolean_t       initiator;
  87         uint8_t         exch_type;
  88 };
  89 
  90 static pkt_walk_ret_t check_payload(uint8_t, uint8_t, uchar_t *restrict,
  91     size_t, void *restrict);
  92 static boolean_t check_sa_init_payloads(boolean_t, const size_t *);
  93 
  94 /* Allocate a ikev2_pkt_t for an inbound datagram in raw */
  95 pkt_t *
  96 ikev2_pkt_new_inbound(uchar_t *buf, size_t buflen)
  97 {
  98         const ike_header_t      *hdr = NULL;
  99         pkt_t                   *pkt = NULL;
 100         size_t                  *counts = NULL;
 101         struct validate_data    arg = { 0 };
 102         size_t                  i = 0;
 103 
 104         ASSERT(IS_P2ALIGNED(buf, sizeof (uint64_t)));
 105 
 106         hdr = (const ike_header_t *)buf;
 107 
 108         ASSERT(IKE_GET_MAJORV(hdr->version) == IKE_GET_MAJORV(IKEV2_VERSION));
 109 
 110         /*
 111          * Make sure either the initiator or response flag is set, but
 112          * not both.
 113          */
 114         uint8_t flags = hdr->flags & (IKEV2_FLAG_INITIATOR|IKEV2_FLAG_RESPONSE);
 115         if ((flags ^ (IKEV2_FLAG_INITIATOR|IKEV2_FLAG_RESPONSE)) == 0) {
 116                 /* XXX: log msg? */
 117                 return (NULL);
 118         }
 119 
 120         if ((pkt = pkt_in_alloc(buf, buflen)) == NULL) {
 121                 /* XXX: log msg */
 122                 return (NULL);
 123         }
 124 
 125         arg.pkt = pkt;
 126         arg.exch_type = hdr->exch_type;
 127         arg.initiator = !!(hdr->flags & IKEV2_FLAG_INITIATOR);
 128 
 129         if (pkt_payload_walk((uchar_t *)(hdr + 1),
 130             buflen - sizeof (ike_header_t), check_payload, hdr->next_payload,
 131             &arg) != PKT_WALK_OK)
 132                 goto discard;
 133 
 134         counts = arg.payload_count;
 135 
 136 #define PAYCOUNT(totals, paytype) totals[(paytype) - IKEV2_PAYLOAD_MIN]
 137 
 138         switch (arg.exch_type) {
 139         case IKEV2_EXCH_IKE_AUTH:
 140         case IKEV2_EXCH_CREATE_CHILD_SA:
 141         case IKEV2_EXCH_INFORMATIONAL:
 142                 /* check_payload() already made sure we only have SK payloads */
 143                 if (PAYCOUNT(counts, IKEV2_PAYLOAD_SK) == 1)
 144                         return (pkt);
 145 
 146                 /* XXX: log */
 147                 goto discard;
 148         case IKEV2_EXCH_IKE_SA_INIT:
 149                 break;
 150         case IKEV2_EXCH_IKE_SESSION_RESUME:
 151                 INVALID("arg->exch_type");
 152                 break;
 153         }
 154 
 155 #define HAS_NOTIFY(totals) (!!(PAYCOUNT(totals, IKEV2_PAYLOAD_NOTIFY) > 0))
 156 
 157         for (i = IKEV2_PAYLOAD_MIN; i <= IKEV2_PAYLOAD_MAX; i++) {
 158                 size_t count = PAYCOUNT(counts, i);
 159 
 160                 switch (i) {
 161                 /* Never allowed in an SA_INIT exchange */
 162                 case IKEV2_PAYLOAD_IDi:
 163                 case IKEV2_PAYLOAD_IDr:
 164                 case IKEV2_PAYLOAD_CERT:
 165                 case IKEV2_PAYLOAD_AUTH:
 166                 case IKEV2_PAYLOAD_DELETE:
 167                 case IKEV2_PAYLOAD_TSi:
 168                 case IKEV2_PAYLOAD_TSr:
 169                 case IKEV2_PAYLOAD_SK:
 170                 case IKEV2_PAYLOAD_CP:
 171                 case IKEV2_PAYLOAD_EAP:
 172                 case IKEV2_PAYLOAD_GSPM:
 173                         if (count > 0) {
 174                                 /* XXX: log */
 175                                 goto discard;
 176                         }
 177                         break;
 178 
 179                 /* can appear 0 or more times */
 180                 case IKEV2_PAYLOAD_NOTIFY:
 181                 case IKEV2_PAYLOAD_CERTREQ:
 182                         break;
 183 
 184                 case IKEV2_PAYLOAD_VENDOR:
 185                         if (PAYCOUNT(counts, IKEV2_PAYLOAD_SA) > 0 ||
 186                             PAYCOUNT(counts, IKEV2_PAYLOAD_NOTIFY) > 0)
 187                                 break;
 188 
 189                 case IKEV2_PAYLOAD_SA:
 190                         if (count != 1 && !HAS_NOTIFY(counts)) {
 191                                 /* XXX: log */
 192                                 goto discard;
 193                         }
 194                         break;
 195 
 196                 case IKEV2_PAYLOAD_KE:
 197                 case IKEV2_PAYLOAD_NONCE:
 198                         if (count != 1) {
 199                                 if (!HAS_NOTIFY(counts)) {
 200                                         /* XXX: log */
 201                                         goto discard;
 202                                 }
 203                                 break;
 204                         }
 205                         if (PAYCOUNT(counts, IKEV2_PAYLOAD_SA) != 1) {
 206                                 /* XXX: log */
 207                                 goto discard;
 208                         }
 209                         break;
 210                 }
 211         }
 212 
 213         return (pkt);
 214 
 215 discard:
 216         pkt_free(pkt);
 217         return (NULL);
 218 #undef PAYCOUNT
 219 #undef HAS_NOTIFY
 220 }
 221 
 222 /*
 223  * Cache the payload offsets and do some minimal checking.
 224  * By virtue of walking the payloads, we also validate the payload
 225  * lengths do not overflow or underflow
 226  */
 227 static pkt_walk_ret_t
 228 check_payload(uint8_t paytype, uint8_t resv, uchar_t *restrict buf,
 229     size_t buflen, void *restrict cookie)
 230 {
 231         struct validate_data *arg = (struct validate_data *)cookie;
 232         boolean_t critical = !!(resv & IKEV2_CRITICAL_PAYLOAD);
 233 
 234         /* Skip unknown payloads.  We will check the critical bit later */
 235         if (paytype < IKEV2_PAYLOAD_MIN || paytype > IKEV2_PAYLOAD_MAX)
 236                 return (PKT_WALK_OK);
 237 
 238         switch (arg->exch_type) {
 239         case IKEV2_EXCH_IKE_AUTH:
 240         case IKEV2_EXCH_CREATE_CHILD_SA:
 241         case IKEV2_EXCH_INFORMATIONAL:
 242                 /*
 243                  * All payloads in these exchanges should be encrypted
 244                  * at this early stage.  RFC 5996 isn't quite clear
 245                  * what to do.  There seem to be three possibilities:
 246                  *
 247                  * 1. Drop the packet with no further action.
 248                  * 2. IFF the encrypted payload's integrity check passes,
 249                  *    and the packet is an initiator, send an INVALID_SYNTAX
 250                  *    notification in response.  Otherwise, drop the packet
 251                  * 3. Ignore the unencrypted payloads and only process the
 252                  *    payloads that passed the integrity check.
 253                  *
 254                  * As RFC5996 suggests committing minimal CPU state until
 255                  * a valid request is present (to help mitigate DOS attacks),
 256                  * option 2 would still commit us to performing potentially
 257                  * expensive decryption and authentication calculations.
 258                  * Option 3 would require us to track which payloads were
 259                  * authenticated and which were not.  Since some payloads
 260                  * (e.g. notify) can appear multiple times in a packet
 261                  * (requiring some sort of iteration to deal with them),
 262                  * this seems potentially complicated and prone to potential
 263                  * exploit.  Thus we opt for the simple solution of dropping
 264                  * the packet.
 265                  *
 266                  * NOTE: if we successfully authenticate and decrypt a
 267                  * packet for one of these exchanges and the decrypted
 268                  * and authenticated payloads have range or value issues,
 269                  * we may opt at that point to send an INVALID_SYNTAX
 270                  * notification, but not here.
 271                  */
 272                 if (paytype != IKEV2_PAYLOAD_SK) {
 273                         /* XXX: log message? */
 274                         return (PKT_WALK_ERROR);
 275                 }
 276                 return (PKT_WALK_OK);
 277 
 278         case IKEV2_EXCH_IKE_SA_INIT:
 279                 break;
 280 
 281         default:
 282                 /* Unknown exchange, bail */
 283                 /* XXX: log message? */
 284                 return (PKT_WALK_ERROR);
 285         }
 286 
 287         ASSERT3U(exch_type, ==, IKEV2_EXCH_SA_INIT);
 288 
 289         arg->payload_count[paytype - IKEV2_PAYLOAD_MIN]++;
 290 
 291         if (paytype == IKEV2_PAYLOAD_NOTIFY) {
 292                 pkt_notify_t *ntfyp = pkt_notify(arg->pkt, arg->notify_count++);
 293                 ikev2_notify_t ntfy = { 0 };
 294                 size_t len = sizeof (ntfy);
 295 
 296                 if (buflen < len) {
 297                         /* XXX: log */
 298                         return (PKT_WALK_ERROR);
 299                 }
 300                 (void) memcpy(&ntfy, buf, sizeof (ntfy));
 301                 len += ntfy.n_spisize;
 302                 if (buflen < len) {
 303                         /* XXX: log */
 304                         return (PKT_WALK_ERROR);
 305                 }
 306 
 307                 ntfyp->pn_ptr = buf;
 308                 ntfyp->pn_type = ntohs(ntfy.n_type);
 309                 ntfyp->pn_len = buflen;
 310                 return (PKT_WALK_OK);
 311         }
 312 
 313         return (PKT_WALK_OK);
 314 }
 315 
 316 #define PAYBIT(pay) ((uint32_t)1 << ((pay) - IKEV2_PAYLOAD_MIN))
 317 static const uint32_t multi_payloads =
 318         PAYBIT(IKEV2_PAYLOAD_NOTIFY) |
 319         PAYBIT(IKEV2_PAYLOAD_VENDOR) |
 320         PAYBIT(IKEV2_PAYLOAD_CERTREQ);
 321 #define IS_MULTI(pay) (!!(multi_payloads & PAYBIT(pay)))
 322 
 323 static struct payinfo {
 324         uint32_t        required;
 325         uint32_t        optional;
 326 } sa_init_info[] = {
 327         {
 328                 /* required */
 329                 PAYBIT(IKEV2_PAYLOAD_SA) |
 330                 PAYBIT(IKEV2_PAYLOAD_KE) |
 331                 PAYBIT(IKEV2_PAYLOAD_NONCE),
 332                 /* optional */
 333                 PAYBIT(IKEV2_PAYLOAD_NOTIFY) |
 334                 PAYBIT(IKEV2_PAYLOAD_VENDOR) |
 335                 PAYBIT(IKEV2_PAYLOAD_CERTREQ)
 336         },
 337         {
 338                 /* required */
 339                 PAYBIT(IKEV2_PAYLOAD_NOTIFY),
 340                 /* optional */
 341                 PAYBIT(IKEV2_PAYLOAD_VENDOR)
 342         }
 343 };
 344 
 345 void
 346 ikev2_pkt_free(pkt_t *pkt)
 347 {
 348         pkt_free(pkt);
 349 }
 350 
 351 static void
 352 ikev2_add_payload(pkt_t *pkt, ikev2_pay_type_t ptype, boolean_t critical)
 353 {
 354         uchar_t *payptr;
 355         uint8_t resv = 0;
 356 
 357         ASSERT(IKEV2_VALID_PAYLOAD(ptype));
 358         ASSERT3U(pkt_write_left(pkt), >=, sizeof (ikev2_payload_t));
 359 
 360         if (critical)
 361                 resv |= IKEV2_CRITICAL_PAYLOAD;
 362 
 363         pkt_add_payload(pkt, ptype, resv);
 364 }
 365 
 366 boolean_t
 367 ikev2_add_sa(pkt_t *pkt)
 368 {
 369         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t))
 370                 return (B_FALSE);
 371         ikev2_add_payload(pkt, IKEV2_PAYLOAD_SA, B_FALSE);
 372         return (B_TRUE);
 373 }
 374 
 375 boolean_t
 376 ikev2_add_prop(pkt_t *pkt, uint8_t propnum, ikev2_spi_proto_t proto,
 377     uint64_t spi)
 378 {
 379         size_t spilen;
 380 
 381         switch (proto) {
 382         case IKEV2_PROTO_AH:
 383         case IKEV2_PROTO_ESP:
 384                 spilen = sizeof (uint32_t);
 385                 break;
 386         case IKEV2_PROTO_IKE:
 387                 spilen == (spi == 0) ? 0 : sizeof (uint64_t);
 388                 break;
 389         case IKEV2_PROTO_NONE:
 390         case IKEV2_PROTO_FC_ESP_HEADER:
 391         case IKEV2_PROTO_FC_CT_AUTH:
 392                 INVALID("proto");
 393                 break;
 394         }
 395 
 396         return (pkt_add_prop(pkt, propnum, proto, spilen, spi));
 397 }
 398 
 399 boolean_t
 400 ikev2_add_xform(pkt_t *pkt, ikev2_xf_type_t xftype, int xfid)
 401 {
 402         return (pkt_add_xform(pkt, xftype, xfid));
 403 }
 404 
 405 boolean_t
 406 ikev2_add_xf_attr(pkt_t *pkt, ikev2_xf_attr_type_t xf_attr_type,
 407     uintptr_t arg)
 408 {
 409         switch (xf_attr_type) {
 410         case IKEV2_XF_ATTR_KEYLEN:
 411                 ASSERT3U(arg, <, 0x10000);
 412                 return (pkt_add_xform_attr_tv(pkt, IKEV2_XF_ATTR_KEYLEN,
 413                     (uint16_t)arg));
 414         }
 415 
 416         return (B_FALSE);
 417 }
 418 
 419 boolean_t
 420 ikev2_add_xf_encr(pkt_t *pkt, ikev2_xf_encr_t encr, uint16_t minbits,
 421     uint16_t maxbits)
 422 {
 423         uint16_t incr = 0;
 424         boolean_t ok = B_TRUE;
 425 
 426         switch (encr) {
 427         case IKEV2_ENCR_NONE:
 428         case IKEV2_ENCR_NULL:
 429                 INVALID("encr");
 430                 /*NOTREACHED*/
 431                 return (B_FALSE);
 432 
 433         /* XXX: need to confirm this */
 434         case IKEV2_ENCR_NULL_AES_GMAC:
 435                 return (B_TRUE);
 436 
 437         /* ones that should never include a key size */
 438         case IKEV2_ENCR_DES_IV64:
 439         case IKEV2_ENCR_DES:
 440         case IKEV2_ENCR_3DES:
 441         case IKEV2_ENCR_IDEA:
 442         case IKEV2_ENCR_3IDEA:
 443         case IKEV2_ENCR_DES_IV32:
 444                 VERIFY3U(minbits, ==, 0);
 445                 VERIFY3U(maxbits, ==, 0);
 446                 return (ikev2_add_xform(pkt, IKEV2_XF_ENCR, encr));
 447 
 448         /* optional key size */
 449         case IKEV2_ENCR_RC4:
 450         case IKEV2_ENCR_RC5:
 451         case IKEV2_ENCR_BLOWFISH:
 452         case IKEV2_ENCR_CAST:
 453                 if (minbits == 0 && maxbits == 0)
 454                         return (ikev2_add_xform(pkt, IKEV2_XF_ENCR, encr));
 455                 incr = 1;
 456                 break;
 457 
 458         case IKEV2_ENCR_AES_CBC:
 459         case IKEV2_ENCR_AES_CTR:
 460         case IKEV2_ENCR_AES_CCM_8:
 461         case IKEV2_ENCR_AES_CCM_12:
 462         case IKEV2_ENCR_AES_CCM_16:
 463         case IKEV2_ENCR_AES_GCM_8:
 464         case IKEV2_ENCR_AES_GCM_12:
 465         case IKEV2_ENCR_AES_GCM_16:
 466         case IKEV2_ENCR_XTS_AES:
 467                 incr = 64;
 468                 break;
 469 
 470         case IKEV2_ENCR_CAMELLIA_CBC:
 471         case IKEV2_ENCR_CAMELLIA_CTR:
 472         case IKEV2_ENCR_CAMELLIA_CCM_8:
 473         case IKEV2_ENCR_CAMELLIA_CCM_12:
 474         case IKEV2_ENCR_CAMELLIA_CCM_16:
 475                 VERIFY3U(minbits, >=, 128);
 476                 VERIFY3U(maxbits, <=, 256);
 477                 incr = 64;
 478                 break;
 479         }
 480 
 481         if (incr == 1) {
 482                 /*
 483                  * instead of adding potentially hundreds of transforms for
 484                  * a range of keysizes, for those with arbitrary key sizes
 485                  * we just add the min and max
 486                  */
 487                 if (minbits != maxbits) {
 488                         ok &= ikev2_add_xform(pkt, IKEV2_XF_ENCR, encr);
 489                         ok &= ikev2_add_xf_attr(pkt, IKEV2_XF_ATTR_KEYLEN,
 490                             minbits);
 491                 }
 492                 ok &= ikev2_add_xform(pkt, IKEV2_XF_ENCR, encr);
 493                 ok &= ikev2_add_xf_attr(pkt, IKEV2_XF_ATTR_KEYLEN, maxbits);
 494                 return (ok);
 495         }
 496 
 497         for (size_t bits = minbits; bits <= maxbits; bits += incr) {
 498                 ok &= ikev2_add_xform(pkt, IKEV2_XF_ENCR, encr);
 499                 ok &= ikev2_add_xf_attr(pkt, IKEV2_XF_ATTR_KEYLEN, bits);
 500         }
 501 
 502         return (ok);
 503 }
 504 
 505 boolean_t
 506 ikev2_add_ke(pkt_t *restrict pkt, uint_t group,
 507     const uchar_t *restrict data, size_t len)
 508 {
 509         ikev2_ke_t      ke = { 0 };
 510 
 511         ASSERT3U(group, <, 0x10000);
 512         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + sizeof (ke) + len)
 513                 return (B_FALSE);
 514 
 515         ikev2_add_payload(pkt, IKEV2_PAYLOAD_KE, B_FALSE);
 516         ke.kex_dhgroup = htons((uint16_t)group);
 517         PKT_APPEND_STRUCT(pkt, ke);
 518         PKT_APPEND_DATA(pkt, data, len);
 519         return (B_TRUE);
 520 }
 521 
 522 static boolean_t
 523 ikev2_add_id_common(pkt_t *restrict pkt, boolean_t id_i, ikev2_id_type_t idtype,
 524     va_list ap)
 525 {
 526         ikev2_id_t              id = { 0 };
 527         ikev2_pay_type_t        paytype =
 528             (id_i) ? IKEV2_PAYLOAD_IDi : IKEV2_PAYLOAD_IDr;
 529         const uchar_t           *data;
 530         size_t                  len = 0;
 531 
 532         data = va_arg(ap, const uchar_t *);
 533 
 534         switch (idtype) {
 535         case IKEV2_ID_IPV4_ADDR:
 536                 len = sizeof (in_addr_t);
 537                 break;
 538         case IKEV2_ID_FQDN:
 539         case IKEV2_ID_RFC822_ADDR:
 540                 len = strlen((const char *)data);
 541                 break;
 542         case IKEV2_ID_IPV6_ADDR:
 543                 len = sizeof (in6_addr_t);
 544                 break;
 545         case IKEV2_ID_DER_ASN1_DN:
 546         case IKEV2_ID_DER_ASN1_GN:
 547         case IKEV2_ID_KEY_ID:
 548                 len = va_arg(ap, size_t);
 549                 break;
 550         case IKEV2_ID_FC_NAME:
 551                 INVALID("idtype");
 552                 break;
 553         }
 554 
 555         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + sizeof (id) + len)
 556                 return (B_FALSE);
 557 
 558         ikev2_add_payload(pkt, paytype, B_FALSE);
 559         id.id_type = (uint8_t)idtype;
 560         PKT_APPEND_STRUCT(pkt, id);
 561         PKT_APPEND_DATA(pkt, data, len);
 562         return (B_TRUE);
 563 }
 564 
 565 boolean_t
 566 ikev2_add_id_i(pkt_t *restrict pkt, ikev2_id_type_t idtype, ...)
 567 {
 568         va_list ap;
 569         boolean_t ret;
 570 
 571         va_start(ap, idtype);
 572         ret = ikev2_add_id_common(pkt, B_TRUE, idtype, ap);
 573         va_end(ap);
 574         return (ret);
 575 }
 576 
 577 boolean_t
 578 ikev2_add_id_r(pkt_t *restrict pkt, ikev2_id_type_t idtype, ...)
 579 {
 580         va_list ap;
 581         boolean_t ret;
 582 
 583         va_start(ap, idtype);
 584         ret = ikev2_add_id_common(pkt, B_FALSE, idtype, ap);
 585         va_end(ap);
 586         return (ret);
 587 }
 588 
 589 static boolean_t ikev2_add_cert_common(pkt_t *restrict, boolean_t,
 590     ikev2_cert_t, const uchar_t *, size_t);
 591 
 592 boolean_t
 593 ikev2_add_cert(pkt_t *restrict pkt, ikev2_cert_t cert_type, const uchar_t *cert,
 594     size_t len)
 595 {
 596         return (ikev2_add_cert_common(pkt, B_TRUE, cert_type, cert, len));
 597 }
 598 
 599 boolean_t
 600 ikev2_add_certreq(pkt_t *restrict pkt, ikev2_cert_t cert_type,
 601     const uchar_t *cert, size_t len)
 602 {
 603         return (ikev2_add_cert_common(pkt, B_FALSE, cert_type, cert, len));
 604 }
 605 
 606 static boolean_t
 607 ikev2_add_cert_common(pkt_t *restrict pkt, boolean_t cert, ikev2_cert_t type,
 608     const uchar_t *restrict data, size_t len)
 609 {
 610         ikev2_pay_type_t ptype =
 611             (cert) ? IKEV2_PAYLOAD_CERT : IKEV2_PAYLOAD_CERTREQ;
 612 
 613         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + 1 + len)
 614                 return (B_FALSE);
 615 
 616         ikev2_add_payload(pkt, ptype, B_FALSE);
 617         return (pkt_add_cert(pkt, (uint8_t)type, data, len));
 618 }
 619 
 620 boolean_t
 621 ikev2_add_auth(pkt_t *restrict pkt, ikev2_auth_type_t auth_method,
 622     const uchar_t *restrict data, size_t len)
 623 {
 624         ikev2_auth_t auth = { 0 };
 625 
 626         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + sizeof (auth) +
 627             len)
 628                 return (B_FALSE);
 629 
 630         ikev2_add_payload(pkt, IKEV2_PAYLOAD_AUTH, B_FALSE);
 631         auth.auth_method = (uint8_t)auth_method;
 632         PKT_APPEND_STRUCT(pkt, auth);
 633         PKT_APPEND_DATA(pkt, data, len);
 634         return (B_TRUE);
 635 }
 636 
 637 boolean_t
 638 ikev2_add_nonce(pkt_t *restrict pkt, size_t len)
 639 {
 640         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + len)
 641                 return (B_FALSE);
 642 
 643         ikev2_add_payload(pkt, IKEV2_PAYLOAD_NONCE, B_FALSE);
 644         random_high(pkt->pkt_ptr, len);
 645         pkt->pkt_ptr += len;
 646         return (B_TRUE);
 647 }
 648 
 649 boolean_t
 650 ikev2_add_notify(pkt_t *restrict pkt, ikev2_spi_proto_t proto, uint64_t spi,
 651     ikev2_notify_type_t ntfy_type, const void *restrict data, size_t len)
 652 {
 653         ikev2_notify_t ntfy = { 0 };
 654         size_t spisize = 0;
 655 
 656         switch (proto) {
 657         case IKEV2_PROTO_NONE:
 658         case IKEV2_PROTO_FC_ESP_HEADER:
 659         case IKEV2_PROTO_FC_CT_AUTH:
 660                 INVALID("proto");
 661                 /*NOTREACHED*/
 662                 return (B_FALSE);
 663         case IKEV2_PROTO_IKE:
 664                 if (spi != 0)
 665                         spisize == sizeof (uint64_t);
 666                 break;
 667         case IKEV2_PROTO_AH:
 668         case IKEV2_PROTO_ESP:
 669                 spisize = sizeof (uint32_t);
 670                 VERIFY3U(spi, <=, UINT32_MAX);
 671                 VERIFY3U(spi, !=, 0);
 672                 break;
 673         }
 674 
 675         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + sizeof (ntfy) +
 676             spisize + len)
 677                 return (B_FALSE);
 678 
 679         ikev2_add_payload(pkt, IKEV2_PAYLOAD_NOTIFY, B_FALSE);
 680         ntfy.n_protoid = proto;
 681         ntfy.n_spisize = spisize;
 682         ntfy.n_type = htons((uint16_t)ntfy_type);
 683         PKT_APPEND_STRUCT(pkt, ntfy);
 684 
 685         switch (spisize) {
 686         case 0:
 687                 break;
 688         case sizeof (uint32_t):
 689                 put32(pkt, htonl((uint32_t)spi));
 690                 break;
 691         case sizeof (uint64_t):
 692                 put64(pkt, htonll(spi));
 693                 break;
 694         default:
 695                 INVALID(spisize);
 696         }
 697 
 698         if (data != NULL)
 699                 PKT_APPEND_DATA(pkt, data, len);
 700 
 701         return (B_TRUE);
 702 }
 703 
 704 static boolean_t delete_finish(pkt_t *restrict, uchar_t *restrict, uintptr_t,
 705     size_t);
 706 
 707 boolean_t
 708 ikev2_add_delete(pkt_t *pkt, ikev2_spi_proto_t proto)
 709 {
 710         ikev2_delete_t del = { 0 };
 711 
 712         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) +
 713             sizeof (ikev2_delete_t))
 714                 return (B_FALSE);
 715 
 716         ikev2_add_payload(pkt, IKEV2_PAYLOAD_DELETE, B_FALSE);
 717         pkt_stack_push(pkt, PSI_DEL, delete_finish, 0);
 718 
 719         del.del_protoid = (uint8_t)proto;
 720         switch (proto) {
 721         case IKEV2_PROTO_IKE:
 722                 del.del_spisize = 0;
 723                 break;
 724         case IKEV2_PROTO_AH:
 725         case IKEV2_PROTO_ESP:
 726                 del.del_spisize = sizeof (uint32_t);
 727                 break;
 728         case IKEV2_PROTO_NONE:
 729         case IKEV2_PROTO_FC_ESP_HEADER:
 730         case IKEV2_PROTO_FC_CT_AUTH:
 731                 INVALID("proto");
 732         }
 733 
 734         PKT_APPEND_STRUCT(pkt, del);
 735         return (B_TRUE);
 736 }
 737 
 738 static boolean_t
 739 delete_finish(pkt_t *restrict pkt, uchar_t *restrict buf, uintptr_t swaparg,
 740     size_t numspi)
 741 {
 742         ikev2_delete_t  del = { 0 };
 743 
 744         ASSERT3U(numspi, <, 0x10000);
 745 
 746         (void) memcpy(&del, buf, sizeof (del));
 747         del.del_nspi = htons((uint16_t)numspi);
 748         (void) memcpy(buf, &del, sizeof (del));
 749         return (B_TRUE);
 750 }
 751 
 752 boolean_t
 753 ikev2_add_vendor(pkt_t *restrict pkt, const void *restrict vid, size_t len)
 754 {
 755         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) + len)
 756                 return (B_FALSE);
 757 
 758         ikev2_add_payload(pkt, IKEV2_PAYLOAD_VENDOR, B_FALSE);
 759         PKT_APPEND_DATA(pkt, vid, len);
 760         return (B_TRUE);
 761 }
 762 
 763 static boolean_t add_ts_common(pkt_t *, boolean_t);
 764 
 765 boolean_t
 766 ikev2_add_ts_i(pkt_t *restrict pkt)
 767 {
 768         return (add_ts_common(pkt, B_TRUE));
 769 }
 770 
 771 boolean_t
 772 ikev2_add_ts_r(pkt_t *restrict pkt)
 773 {
 774         return (add_ts_common(pkt, B_FALSE));
 775 }
 776 
 777 static boolean_t ts_finish(pkt_t *restrict, uchar_t *restrict, uintptr_t,
 778     size_t);
 779 
 780 static boolean_t
 781 add_ts_common(pkt_t *pkt, boolean_t ts_i)
 782 {
 783         ikev2_ts_t ts = { 0 };
 784 
 785         if (pkt_write_left(pkt) < sizeof (ikev2_payload_t) +
 786             sizeof (ikev2_ts_t))
 787                 return (B_FALSE);
 788 
 789         ikev2_add_payload(pkt, (ts_i) ? IKEV2_PAYLOAD_TSi : IKEV2_PAYLOAD_TSr,
 790             B_FALSE);
 791         pkt_stack_push(pkt, PSI_TSP, ts_finish, 0);
 792         PKT_APPEND_STRUCT(pkt, ts);
 793         return (B_TRUE);
 794 }
 795 
 796 static boolean_t
 797 ts_finish(pkt_t *restrict pkt, uchar_t *restrict buf, uintptr_t swaparg,
 798     size_t numts)
 799 {
 800         ikev2_tsp_t     ts = { 0 };
 801 
 802         ASSERT3U(numts, <, 0x100);
 803 
 804         (void) memcpy(&ts, buf, sizeof (ts));
 805         ts.tsp_count = (uint8_t)numts;
 806         (void) memcpy(buf, &ts, sizeof (ts));
 807         return (B_TRUE);
 808 }
 809 
 810 boolean_t
 811 ikev2_add_ts(pkt_t *restrict pkt, ikev2_ts_type_t type, uint8_t ip_proto,
 812     const sockaddr_u_t *restrict start, const sockaddr_u_t *restrict end)
 813 {
 814         ikev2_ts_t      ts = { 0 };
 815         void            *startptr = NULL, *endptr = NULL;
 816         size_t          len = 0;
 817 
 818         ASSERT3U(ip_proto, <, 0x100);
 819         ASSERT3U(start->sau_ss->ss_family, ==, end->sau_ss->ss_family);
 820 
 821         pkt_stack_push(pkt, PSI_TS, 0, NULL);
 822 
 823         ts.ts_length = sizeof (ts);
 824         ts.ts_type = (uint8_t)type;
 825 
 826         switch (type) {
 827         case IKEV2_TS_IPV4_ADDR_RANGE:
 828                 ASSERT3U(start->sau_ss->ss_family, ==, AF_INET);
 829                 ASSERT3U(end->sau_ss->ss_family, ==, AF_INET);
 830                 ts.ts_startport = start->sau_sin->sin_port;
 831                 ts.ts_endport = end->sau_sin->sin_port;
 832                 startptr = &start->sau_sin->sin_addr;
 833                 endptr = &end->sau_sin->sin_addr;
 834                 len = sizeof (in_addr_t);
 835                 ts.ts_length += 2 * len;
 836                 break;
 837         case IKEV2_TS_IPV6_ADDR_RANGE:
 838                 ASSERT3U(start->sau_ss->ss_family, ==, AF_INET6);
 839                 ASSERT3U(end->sau_ss->ss_family, ==, AF_INET6);
 840                 ts.ts_startport = start->sau_sin6->sin6_port;
 841                 ts.ts_endport = end->sau_sin6->sin6_port;
 842                 startptr = &start->sau_sin6->sin6_addr;
 843                 endptr = &end->sau_sin6->sin6_addr;
 844                 len = sizeof (in6_addr_t);
 845                 ts.ts_length += 2 * len;
 846                 break;
 847         case IKEV2_TS_FC_ADDR_RANGE:
 848                 INVALID("type");
 849         }
 850 
 851         if (pkt_write_left(pkt) < ts.ts_length)
 852                 return (B_FALSE);
 853 
 854         ts.ts_protoid = ip_proto;
 855         ts.ts_length = htons(ts.ts_length);
 856         PKT_APPEND_STRUCT(pkt, ts);
 857         PKT_APPEND_DATA(pkt, startptr, len);
 858         PKT_APPEND_DATA(pkt, endptr, len);
 859         return (B_TRUE);
 860 }
 861 
 862 static boolean_t encrypt_payloads(pkt_t *restrict, uchar_t *restrict, uintptr_t,
 863     size_t);
 864 static boolean_t cbc_iv(pkt_t *restrict, uchar_t *);
 865 
 866 boolean_t
 867 ikev2_add_sk(pkt_t *restrict pkt)
 868 {
 869         ikev2_sa_t *sa = pkt->pkt_sa;
 870         size_t len = sizeof (ikev2_payload_t);
 871         size_t ivlen = ikev2_encr_iv_size(sa->encr);
 872         boolean_t ret;
 873 
 874         len += ivlen;
 875         len += ikev2_auth_icv_size(sa->encr, sa->auth);
 876         len += ikev2_encr_block_size(sa->encr);
 877 
 878         if (pkt_write_left(pkt) < len)
 879                 return (B_FALSE);
 880 
 881         /*
 882          * This needs to happen first so that subsequent payloads are
 883          * encapsulated by the SK payload
 884          */
 885         pkt_stack_push(pkt, PSI_SK, encrypt_payloads, 0);
 886         ikev2_add_payload(pkt, IKEV2_PAYLOAD_SK, B_FALSE);
 887 
 888         /*
 889          * Skip over space for IV, encrypt_payloads() will fill it in.
 890          * The memset() shouldn't be needed, as the memory should already be
 891          * 0-filled, but erring on the side of caution.
 892          */
 893         (void) memset(pkt->pkt_ptr, 0, ivlen);
 894         pkt->pkt_ptr += ivlen;
 895         return (B_TRUE);
 896 }
 897 
 898 /*
 899  * Based on recommendation from NIST 800-38A, Appendix C, use msgid
 900  * which should be unique, encrypt using SK to generate IV
 901  */
 902 static boolean_t
 903 cbc_iv(pkt_t *restrict pkt, uchar_t *ivp)
 904 {
 905         ikev2_sa_t *sa = pkt->pkt_sa;
 906         CK_SESSION_HANDLE handle = p11h;
 907         CK_MECHANISM mech;
 908         CK_OBJECT_HANDLE key;
 909         CK_RV rv;
 910         CK_ULONG blocklen = 0; /* in bytes */
 911 
 912         if (pkt->pkt_sa->flags & I2SA_INITIATOR)
 913                 key = sa->sk_ei;
 914         else
 915                 key = sa->sk_er;
 916 
 917         switch (pkt->pkt_sa->encr) {
 918         case IKEV2_ENCR_AES_CBC:
 919                 mech.mechanism = CKM_AES_ECB;
 920                 mech.pParameter = NULL_PTR;
 921                 mech.ulParameterLen = 0;
 922                 blocklen = 16;
 923                 break;
 924         case IKEV2_ENCR_CAMELLIA_CBC:
 925                 mech.mechanism = CKM_CAMELLIA_ECB;
 926                 mech.pParameter = NULL_PTR;
 927                 mech.ulParameterLen = 0;
 928                 blocklen = 16;
 929                 break;
 930         default:
 931                 INVALID("encr");
 932                 /*NOTREACHED*/
 933                 return (B_FALSE);
 934         }
 935 
 936         if (pkt_write_left(pkt) < blocklen)
 937                 return (B_FALSE);
 938 
 939         VERIFY3U(blocklen, >=, sizeof (uint32_t));
 940 
 941         CK_ULONG buflen = blocklen;
 942         uchar_t buf[blocklen];
 943 
 944         (void) memset(buf, 0, blocklen);
 945         (void) memcpy(buf, &pkt->pkt_header.msgid,
 946             sizeof (pkt->pkt_header.msgid));
 947 
 948         rv = C_EncryptInit(handle, &mech, key);
 949         if (rv != CKR_OK) {
 950                 PKCS11ERR(error, sa->i2sa_log, "C_EncryptInit", rv);
 951                 return (B_FALSE);
 952         }
 953 
 954         rv = C_Encrypt(handle, buf, blocklen, buf, &blocklen);
 955         if (rv != CKR_OK) {
 956                 PKCS11ERR(error, sa->i2sa_log, "C_Encrypt", rv);
 957                 return (B_FALSE);
 958         }
 959 
 960         (void) memcpy(ivp, buf, ikev2_encr_iv_size(sa->encr));
 961         return (B_TRUE);
 962 }
 963 
 964 static boolean_t
 965 crypt_common(pkt_t *pkt, boolean_t encrypt, uchar_t *iv, CK_ULONG ivlen,
 966     uchar_t *data, CK_ULONG datalen, uchar_t *icv, CK_ULONG icvlen)
 967 {
 968         ikev2_sa_t *sa = pkt->pkt_sa;
 969         const char *fn;
 970         CK_SESSION_HANDLE handle = p11h;
 971         CK_OBJECT_HANDLE key;
 972         CK_MECHANISM mech;
 973         union {
 974                 CK_AES_CTR_PARAMS       aes_ctr;
 975                 CK_CAMELLIA_CTR_PARAMS  cam_ctr;
 976                 CK_GCM_PARAMS           gcm;
 977                 CK_CCM_PARAMS           ccm;
 978         } params;
 979         CK_RV rc = 0;
 980         encr_modes_t mode = ikev2_encr_mode(sa->encr);
 981         uchar_t *nonce = NULL;
 982         CK_ULONG noncelen = 0;
 983 
 984         if (sa->flags & I2SA_INITIATOR)
 985                 key = pkt->pkt_sa->sk_ei;
 986         else
 987                 key = pkt->pkt_sa->sk_er;
 988 
 989         /*
 990          * For GCM and CCM, the nonce/IV used is a combination of both
 991          * the salt (derived from the PRF function along with the key)
 992          * and the transmitted 'IV' value.  This total value should be
 993          * 10-16 bytes at most, so the use of alloca() shouldn't present
 994          * any issues
 995          */
 996         mech.mechanism = ikev2_encr_to_p11(sa->encr);
 997         switch (mode) {
 998         case MODE_NONE:
 999                 break;
1000         case MODE_CBC:
1001                 mech.pParameter = iv;
1002                 mech.ulParameterLen = ivlen;
1003                 break;
1004         case MODE_CTR:
1005                 /* TODO */
1006                 break;
1007         case MODE_CCM:
1008                 noncelen = sa->saltlen + ivlen;
1009                 nonce = alloca(noncelen);
1010                 (void) memcpy(nonce, sa->salt, sa->saltlen);
1011                 (void) memcpy(nonce + sa->saltlen, iv, ivlen);
1012                 params.ccm.pAAD = (CK_BYTE_PTR)&pkt->pkt_raw;
1013                 params.ccm.ulAADLen = (CK_ULONG)(iv - params.ccm.pAAD);
1014                 params.ccm.ulMACLen = icvlen;
1015                 params.ccm.pNonce = nonce;
1016                 params.ccm.ulNonceLen = noncelen;
1017                 mech.pParameter = &params.ccm;
1018                 mech.ulParameterLen = sizeof (CK_CCM_PARAMS);
1019                 break;
1020         case MODE_GCM:
1021                 noncelen = sa->saltlen + ivlen;
1022                 nonce = alloca(noncelen);
1023                 (void) memcpy(nonce, sa->salt, sa->saltlen);
1024                 (void) memcpy(nonce + sa->saltlen, iv, ivlen);
1025                 params.gcm.pIv = nonce;
1026                 params.gcm.ulIvLen = noncelen;
1027                 /*
1028                  * There is a 'ulIvBits' field in CK_GCM_PARAMS.  This comes
1029                  * straight from the published pkcs11t.h file.  However, it
1030                  * does not appear to actually be used for anything, and looks
1031                  * to be a leftover from the unpublished PKCS#11 v2.30 standard.
1032                  * It is currently not set and ignored
1033                  */
1034                 params.gcm.pAAD = (CK_BYTE_PTR)&pkt->pkt_raw;
1035                 params.gcm.ulAADLen = (CK_ULONG)(iv - params.gcm.pAAD);
1036                 params.gcm.ulTagBits = icvlen * 8;
1037                 mech.pParameter = &params.gcm;
1038                 mech.ulParameterLen = sizeof (CK_GCM_PARAMS);
1039                 break;
1040         }
1041 
1042         if (encrypt) {
1043                 rc = C_EncryptInit(handle, &mech, key);
1044                 fn = "C_EncryptInit";
1045         } else {
1046                 rc = C_DecryptInit(handle, &mech, key);
1047                 fn = "C_DecryptInit";
1048         }
1049 
1050         if (rc != CKR_OK) {
1051                 PKCS11ERR(error, sa->i2sa_log, fn, rc);
1052                 goto done;
1053         }
1054 
1055         /*
1056          * XXX: the last parameter might need a separate var
1057          * because of extra room needed for ccm/gcm
1058          * ALSO: probably want a better error message for the combined mode
1059          * failures
1060          */
1061         if (encrypt) {
1062                 rc = C_Encrypt(handle, data, datalen, data, &datalen);
1063                 fn = "C_Encrypt";
1064         } else {
1065                 rc = C_Decrypt(handle, data, datalen, data, &datalen);
1066                 fn = "C_Decrypt";
1067         }
1068         if (rc != CKR_OK)
1069                 PKCS11ERR(error, sa->i2sa_log, fn, rc);
1070 
1071 done:
1072         if (nonce != NULL)
1073                 (void) memset(nonce, 0, sizeof (nonce));
1074         return ((rc == CKR_OK) ? B_TRUE : B_FALSE);
1075 }
1076 
1077 static boolean_t
1078 auth_common(pkt_t *pkt, boolean_t encrypt, uchar_t *icv, size_t icvlen)
1079 {
1080         ikev2_sa_t *sa = pkt->pkt_sa;
1081         const char *fn = NULL;
1082         CK_SESSION_HANDLE handle = p11h;
1083         CK_OBJECT_HANDLE key;
1084         CK_MECHANISM mech = { 0 };
1085         CK_RV rc;
1086         CK_BYTE_PTR data;
1087         CK_ULONG datalen, len = icvlen;
1088 
1089         if (sa->flags & I2SA_INITIATOR)
1090                 key = sa->sk_ai;
1091         else
1092                 key = sa->sk_ar;
1093 
1094         ASSERT3S(sa->auth, !=, IKEV2_XF_AUTH_NONE);
1095         mech.mechanism = ikev2_auth_to_p11(sa->auth);
1096         mech.pParameter = NULL_PTR;
1097         mech.ulParameterLen = 0;
1098 
1099         data = (CK_BYTE_PTR)&pkt->pkt_raw;
1100         datalen = (CK_ULONG)(icv - data);
1101 
1102         if (encrypt) {
1103                 rc = C_SignInit(handle, &mech, key);
1104                 fn = "C_SignInit";
1105         } else {
1106                 rc = C_VerifyInit(handle, &mech, key);
1107                 fn = "C_SignInit";
1108         }
1109 
1110         if (rc != CKR_OK) {
1111                 PKCS11ERR(error, sa->i2sa_log, fn, rc);
1112                 return (B_FALSE);
1113         }
1114 
1115         if (encrypt) {
1116                 rc = C_Sign(handle, data, datalen, icv, &len);
1117                 fn = "C_Sign";
1118         } else {
1119                 rc = C_Verify(handle, data, datalen, icv, len);
1120                 fn = "C_Verify";
1121 
1122                 /* give this one a better message */
1123                 if (rc == CKR_SIGNATURE_INVALID) {
1124                         bunyan_error(sa->i2sa_log, "integrity check failed",
1125                             BUNYAN_T_END);
1126                         return (B_FALSE);
1127                 }
1128         }
1129 
1130         if (rc != CKR_OK)
1131                 PKCS11ERR(error, sa->i2sa_log, fn, rc);
1132 
1133         return ((rc == CKR_OK) ? B_TRUE : B_FALSE);
1134 }
1135 
1136 static boolean_t
1137 encrypt_payloads(pkt_t *restrict pkt, uchar_t *restrict buf, uintptr_t swaparg,
1138     size_t numencr)
1139 {
1140         ikev2_sa_t *sa = pkt->pkt_sa;
1141         CK_BYTE_PTR iv, data, icv, nonce;
1142         CK_ULONG ivlen, datalen, icvlen, noncelen, blocklen;
1143         uint8_t padlen = 0;
1144         encr_modes_t mode = ikev2_encr_mode(sa->encr);
1145         
1146         ivlen = ikev2_encr_iv_size(sa->encr);
1147         icvlen = ikev2_auth_icv_size(sa->encr, sa->auth);
1148         blocklen = ikev2_encr_block_size(sa->encr);
1149 
1150         iv = (CK_BYTE_PTR)buf + sizeof (ike_payload_t);
1151         data = iv + ivlen;
1152 
1153         /* Sanity check */
1154         VERIFY3P(data, >=, (CK_BYTE_PTR)pkt->pkt_ptr);
1155         datalen = (CK_ULONG)((CK_BYTE_PTR)pkt->pkt_ptr - data);
1156 
1157         /*
1158          * Per RFC7296 3.14, the sender can choose any value for the padding.
1159          * We elect to use PKCS#7 style padding (repeat the pad value as the
1160          * padding).  This is well studied and appears to work.  Unfortunately,
1161          * we cannot validate the padding in the general case.  However,
1162          * since we know when we're communicating to other instances of
1163          * ourselves via the vendor ID payload, it is permissible to have
1164          * custom behavior in such instances, as long as we are backwards
1165          * compatible.  As such we DO validate the padding when communicating
1166          * to other instances of ourselves. Based on attacks to
1167          * protocols (e.g. TLS) where validation of the padding wasn't done,
1168          * we think this is prudent to do.
1169          */
1170         if ((datalen + 1) % blocklen != 0)
1171                 padlen = blocklen - ((datalen + 1) % blocklen);
1172 
1173         if (pkt_write_left(pkt) < padlen + 1 + icvlen) {
1174                 bunyan_info(sa->i2sa_log, "not enough space for packet",
1175                     BUNYAN_T_END);
1176                 return (B_FALSE);
1177         }
1178 
1179         /*
1180          * Once we've written the padding out, we need to write out how much
1181          * padding was added.  Since the amount of padding and the value of
1182          * the padding are the same, we can just use <= in the loop test to
1183          * cause one extra iteration of the loop to accomplish that.
1184          */
1185         for (size_t i = 0; i <= padlen; i++) {
1186                 *pkt->pkt_ptr = padlen;
1187                 pkt->pkt_ptr++;
1188         }
1189                 
1190         datalen += padlen;
1191         icv = data + datalen;
1192         *icv = padlen;
1193         icv++;
1194 
1195         /*
1196          * XXX: So far, every encryption mode wants a unique IV per packet.
1197          * For CBC modes, it also needs to be unpredictable.  Other modes do
1198          * not appear to have that requirement.  Since the msgid should be
1199          * unique for a given key (i.e. the msgid never resets for a given
1200          * IKE SA, instead a new IKE SA, with a new key is created).  We
1201          * start with that, and then for CBC modes, use follow the suggestion
1202          * in NIST 800-38A, Appendix C and encrypt the msgid to create the IV.
1203          */
1204         VERIFY3S(ivlen, >=, sizeof (uint32_t));
1205         if (mode == MODE_CBC) {
1206                 if (!cbc_iv(pkt, iv))
1207                         return (B_FALSE);
1208         } else {
1209                 (void) memcpy(iv, &pkt->pkt_header.msgid, sizeof (uint32_t));
1210         }
1211 
1212         pkt->pkt_ptr = icv + icvlen;
1213 
1214         /* Update SK payload length field to reflect padding + ICV */
1215         ike_payload_t pay = { 0 };
1216         (void) memcpy(&pay, buf, sizeof (pay));
1217         pay.pay_length = htons((uint16_t)(pkt->pkt_ptr - buf));
1218         (void) memcpy(buf, &pay, sizeof (pay));
1219 
1220         if (!crypt_common(pkt, B_TRUE, iv, ivlen, data, datalen, icv, icvlen))
1221                 return (B_FALSE);
1222 
1223         if (mode == MODE_CCM || mode == MODE_GCM)
1224                 return (B_TRUE);
1225 
1226         if (!auth_common(pkt, B_TRUE, icv, icvlen))
1227                 return (B_FALSE);
1228 
1229         return (B_TRUE);
1230 }
1231 
1232 boolean_t
1233 ikev2_pkt_decrypt(pkt_t *pkt)
1234 {
1235         ikev2_sa_t *sa = pkt->pkt_sa;
1236         CK_BYTE_PTR iv, data, icv;
1237         CK_ULONG ivlen, datalen, icvlen;
1238         uint8_t padlen = 0;
1239         encr_modes_t mode = ikev2_encr_mode(sa->encr);
1240 
1241         data = NULL;
1242         datalen = 0;
1243         for (size_t i = 0; i < pkt->pkt_payload_count; i++) {
1244                 pkt_payload_t *pay = pkt_payload(pkt, i);
1245 
1246                 if (pay->pp_type != IKEV2_PAYLOAD_SK)
1247                         continue;
1248 
1249                 data = (CK_BYTE_PTR)pay->pp_ptr;
1250                 datalen = pay->pp_len;
1251                 break;
1252         }
1253         ASSERT3P(data, !=, NULL);
1254 
1255         ivlen = ikev2_encr_iv_size(sa->encr);
1256         icvlen = ikev2_auth_icv_size(sa->encr, sa->auth);
1257         if (icvlen + icvlen + 1 >= datalen) {
1258                 bunyan_info(sa->i2sa_log, "SK payload is too small",
1259                     BUNYAN_T_UINT32, "len", (uint32_t)datalen,
1260                     BUNYAN_T_UINT32, "ivlen", (uint32_t)ivlen,
1261                     BUNYAN_T_UINT32, "icvlen", (uint32_t)icvlen,
1262                     BUNYAN_T_END);
1263                 return (B_FALSE);
1264         }
1265 
1266         iv = data;
1267         data += ivlen;
1268         datalen -= ivlen;
1269         datalen -= icvlen;
1270         icv = data + datalen;
1271 
1272         if (mode != MODE_CCM && mode != MODE_GCM &&
1273             sa->encr != IKEV2_XF_AUTH_NONE) {
1274                 if (!auth_common(pkt, B_FALSE, icv, icvlen))
1275                         return (B_FALSE);
1276         }
1277 
1278         if (!crypt_common(pkt, B_FALSE, iv, ivlen, data, datalen, icv, icvlen))
1279                 return (B_FALSE);
1280 
1281         padlen = *(icv - 1);
1282         datalen -= padlen + 1;
1283 
1284         /*
1285          * As described in enrypt_payloads(), when communicating with other
1286          * illumos instances, we opt to validate the contents of the padding.
1287          * Since RFC7296 allows the sender to choose any arbitrary value
1288          * for the padding, we cannot do this in the general case.
1289          */
1290         if (pkt->pkt_sa->vendor == VENDOR_ILLUMOS_1) {
1291                 CK_BYTE_PTR padp = data + datalen;
1292                 for (size_t i = 0; i < padlen; i++) {
1293                         if (*padp == padlen)
1294                                 continue;
1295 
1296                         bunyan_warn(sa->i2sa_log,
1297                             "Padding validation failed",
1298                             BUNYAN_T_UINT32, "padlen", (uint32_t)padlen,
1299                             BUNYAN_T_UINT32, "offset", (uint32_t)i,
1300                             BUNYAN_T_END);
1301                         return (B_FALSE);
1302                 }
1303         }
1304 
1305         ike_payload_t *payp, pay = { 0 };
1306         size_t paycount = 0, ncount = 0;
1307         size_t paystart, nstart;
1308 
1309         payp = (ike_payload_t *)iv;
1310         payp--;
1311         (void) memcpy(&pay, payp, sizeof (ike_payload_t));
1312 
1313         if (!pkt_count_payloads(data, datalen, pay.pay_next, &paycount,
1314             &ncount)) {
1315                 return (B_FALSE);
1316         }
1317 
1318         paystart = pkt->pkt_payload_count;
1319         nstart = pkt->pkt_notify_count;
1320         if (!pkt_size_index(pkt, pkt->pkt_payload_count + paycount,
1321             pkt->pkt_notify_count + ncount))
1322                 return (B_FALSE);
1323 
1324         if (!pkt_index_payloads(pkt, data, datalen, pay.pay_next, paystart))
1325                 return (B_FALSE);
1326 
1327         ncount = nstart;
1328         for (size_t i = 0; i < pkt->pkt_payload_count; i++) {
1329                 pkt_payload_t *pp = pkt_payload(pkt, i);
1330 
1331                 if (pp->pp_type != IKEV2_PAYLOAD_NOTIFY)
1332                         continue;
1333 
1334                 pkt_notify_t *np = NULL;
1335                 ikev2_notify_t n = { 0 };
1336 
1337                 np = pkt_notify(pkt, ncount++);
1338                 ASSERT3U(pp->pp_len, >=, sizeof (n));
1339                 (void) memcpy(&n, pp->pp_ptr, sizeof (n));
1340                 np->pn_ptr = pp->pp_ptr;
1341                 np->pn_len = pp->pp_len;
1342                 np->pn_type = ntohs(n.n_type);
1343         }
1344  
1345         return (B_TRUE);
1346 }
1347 
1348 boolean_t
1349 ikev2_add_config(pkt_t *pkt, ikev2_cfg_type_t cfg_type)
1350 {
1351         return (B_FALSE);
1352         /* TODO */
1353 }
1354 
1355 boolean_t
1356 ikev2_add_config_attr(pkt_t *restrict pkt,
1357     ikev2_cfg_attr_type_t cfg_attr_type, const void *restrict data)
1358 {
1359         return (B_FALSE);
1360         /* TODO */
1361 }
1362 
1363 char *
1364 ikev2_pkt_desc(pkt_t *pkt)
1365 {
1366         char *s = NULL;
1367         size_t len = 0;
1368         uint16_t i;
1369         uint16_t j;
1370 
1371         for (i = j = 0; i < pkt->pkt_payload_count; i++) {
1372                 pkt_payload_t *pay = pkt_payload(pkt, i);
1373                 const char *paystr =
1374                     ikev2_pay_short_str((ikev2_pay_type_t)pay->pp_type);
1375 
1376                 len += strlen(paystr) + 1;
1377                 if (pay->pp_type == IKEV2_PAYLOAD_NOTIFY) {
1378                         pkt_notify_t *n = pkt_notify(pkt, j++);
1379                         const char *nstr =
1380                             ikev2_notify_str((ikev2_notify_type_t)n->pn_type);
1381 
1382                         len += strlen(nstr) + 2;
1383                 }
1384         }
1385 
1386         s = calloc(1, len);
1387         VERIFY3P(s, !=, len);
1388 
1389         for (i = j = 0; i <pkt->pkt_payload_count; i++) {
1390                 pkt_payload_t *pay = pkt_payload(pkt, i);
1391                 const char *paystr =
1392                     ikev2_pay_short_str((ikev2_pay_type_t)pay->pp_type);
1393 
1394                 (void) strlcat(s, paystr, len);
1395                 if (pay->pp_type == IKEV2_PAYLOAD_NOTIFY) {
1396                         pkt_notify_t *n = pkt_notify(pkt, j++);
1397                         const char *nstr =
1398                             ikev2_notify_str((ikev2_notify_type_t)n->pn_type);
1399 
1400                         (void) strlcat(s, "(", len);
1401                         (void) strlcat(s, nstr, len);
1402                         (void) strlcat(s, ")", len);
1403                 }
1404         }
1405 
1406         return (s);
1407 }