/contrib/ntp/ntpd/ntp_crypto.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 4189 lines · 2414 code · 326 blank · 1449 comment · 578 complexity · 24628f797239e75d9f4988848ef9a38c MD5 · raw file

Large files are truncated click here to view the full file

  1. /*
  2. * ntp_crypto.c - NTP version 4 public key routines
  3. */
  4. #ifdef HAVE_CONFIG_H
  5. #include <config.h>
  6. #endif
  7. #ifdef OPENSSL
  8. #include <stdio.h>
  9. #include <sys/types.h>
  10. #include <sys/param.h>
  11. #include <unistd.h>
  12. #include <fcntl.h>
  13. #include "ntpd.h"
  14. #include "ntp_stdlib.h"
  15. #include "ntp_unixtime.h"
  16. #include "ntp_string.h"
  17. #include <ntp_random.h>
  18. #include "openssl/asn1_mac.h"
  19. #include "openssl/bn.h"
  20. #include "openssl/err.h"
  21. #include "openssl/evp.h"
  22. #include "openssl/pem.h"
  23. #include "openssl/rand.h"
  24. #include "openssl/x509v3.h"
  25. #ifdef KERNEL_PLL
  26. #include "ntp_syscall.h"
  27. #endif /* KERNEL_PLL */
  28. /*
  29. * Extension field message format
  30. *
  31. * These are always signed and saved before sending in network byte
  32. * order. They must be converted to and from host byte order for
  33. * processing.
  34. *
  35. * +-------+-------+
  36. * | op | len | <- extension pointer
  37. * +-------+-------+
  38. * | assocID |
  39. * +---------------+
  40. * | timestamp | <- value pointer
  41. * +---------------+
  42. * | filestamp |
  43. * +---------------+
  44. * | value len |
  45. * +---------------+
  46. * | |
  47. * = value =
  48. * | |
  49. * +---------------+
  50. * | signature len |
  51. * +---------------+
  52. * | |
  53. * = signature =
  54. * | |
  55. * +---------------+
  56. *
  57. * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
  58. * Requests carry the association ID of the receiver; responses carry
  59. * the association ID of the sender. Some messages include only the
  60. * operation/length and association ID words and so have length 8
  61. * octets. Ohers include the value structure and associated value and
  62. * signature fields. These messages include the timestamp, filestamp,
  63. * value and signature words and so have length at least 24 octets. The
  64. * signature and/or value fields can be empty, in which case the
  65. * respective length words are zero. An empty value with nonempty
  66. * signature is syntactically valid, but semantically questionable.
  67. *
  68. * The filestamp represents the time when a cryptographic data file such
  69. * as a public/private key pair is created. It follows every reference
  70. * depending on that file and serves as a means to obsolete earlier data
  71. * of the same type. The timestamp represents the time when the
  72. * cryptographic data of the message were last signed. Creation of a
  73. * cryptographic data file or signing a message can occur only when the
  74. * creator or signor is synchronized to an authoritative source and
  75. * proventicated to a trusted authority.
  76. *
  77. * Note there are four conditions required for server trust. First, the
  78. * public key on the certificate must be verified, which involves a
  79. * number of format, content and consistency checks. Next, the server
  80. * identity must be confirmed by one of four schemes: private
  81. * certificate, IFF scheme, GQ scheme or certificate trail hike to a
  82. * self signed trusted certificate. Finally, the server signature must
  83. * be verified.
  84. */
  85. /*
  86. * Cryptodefines
  87. */
  88. #define TAI_1972 10 /* initial TAI offset (s) */
  89. #define MAX_LEAP 100 /* max UTC leapseconds (s) */
  90. #define VALUE_LEN (6 * 4) /* min response field length */
  91. #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
  92. /*
  93. * Global cryptodata in host byte order
  94. */
  95. u_int32 crypto_flags = 0x0; /* status word */
  96. /*
  97. * Global cryptodata in network byte order
  98. */
  99. struct cert_info *cinfo = NULL; /* certificate info/value */
  100. struct value hostval; /* host value */
  101. struct value pubkey; /* public key */
  102. struct value tai_leap; /* leapseconds table */
  103. EVP_PKEY *iffpar_pkey = NULL; /* IFF parameters */
  104. EVP_PKEY *gqpar_pkey = NULL; /* GQ parameters */
  105. EVP_PKEY *mvpar_pkey = NULL; /* MV parameters */
  106. char *iffpar_file = NULL; /* IFF parameters file */
  107. char *gqpar_file = NULL; /* GQ parameters file */
  108. char *mvpar_file = NULL; /* MV parameters file */
  109. /*
  110. * Private cryptodata in host byte order
  111. */
  112. static char *passwd = NULL; /* private key password */
  113. static EVP_PKEY *host_pkey = NULL; /* host key */
  114. static EVP_PKEY *sign_pkey = NULL; /* sign key */
  115. static const EVP_MD *sign_digest = NULL; /* sign digest */
  116. static u_int sign_siglen; /* sign key length */
  117. static char *rand_file = NULL; /* random seed file */
  118. static char *host_file = NULL; /* host key file */
  119. static char *sign_file = NULL; /* sign key file */
  120. static char *cert_file = NULL; /* certificate file */
  121. static char *leap_file = NULL; /* leapseconds file */
  122. static tstamp_t if_fstamp = 0; /* IFF filestamp */
  123. static tstamp_t gq_fstamp = 0; /* GQ file stamp */
  124. static tstamp_t mv_fstamp = 0; /* MV filestamp */
  125. static u_int ident_scheme = 0; /* server identity scheme */
  126. /*
  127. * Cryptotypes
  128. */
  129. static int crypto_verify P((struct exten *, struct value *,
  130. struct peer *));
  131. static int crypto_encrypt P((struct exten *, struct value *,
  132. keyid_t *));
  133. static int crypto_alice P((struct peer *, struct value *));
  134. static int crypto_alice2 P((struct peer *, struct value *));
  135. static int crypto_alice3 P((struct peer *, struct value *));
  136. static int crypto_bob P((struct exten *, struct value *));
  137. static int crypto_bob2 P((struct exten *, struct value *));
  138. static int crypto_bob3 P((struct exten *, struct value *));
  139. static int crypto_iff P((struct exten *, struct peer *));
  140. static int crypto_gq P((struct exten *, struct peer *));
  141. static int crypto_mv P((struct exten *, struct peer *));
  142. static u_int crypto_send P((struct exten *, struct value *));
  143. static tstamp_t crypto_time P((void));
  144. static u_long asn2ntp P((ASN1_TIME *));
  145. static struct cert_info *cert_parse P((u_char *, u_int, tstamp_t));
  146. static int cert_sign P((struct exten *, struct value *));
  147. static int cert_valid P((struct cert_info *, EVP_PKEY *));
  148. static int cert_install P((struct exten *, struct peer *));
  149. static void cert_free P((struct cert_info *));
  150. static EVP_PKEY *crypto_key P((char *, tstamp_t *));
  151. static int bighash P((BIGNUM *, BIGNUM *));
  152. static struct cert_info *crypto_cert P((char *));
  153. static void crypto_tai P((char *));
  154. #ifdef SYS_WINNT
  155. int
  156. readlink(char * link, char * file, int len) {
  157. return (-1);
  158. }
  159. #endif
  160. /*
  161. * session_key - generate session key
  162. *
  163. * This routine generates a session key from the source address,
  164. * destination address, key ID and private value. The value of the
  165. * session key is the MD5 hash of these values, while the next key ID is
  166. * the first four octets of the hash.
  167. *
  168. * Returns the next key ID
  169. */
  170. keyid_t
  171. session_key(
  172. struct sockaddr_storage *srcadr, /* source address */
  173. struct sockaddr_storage *dstadr, /* destination address */
  174. keyid_t keyno, /* key ID */
  175. keyid_t private, /* private value */
  176. u_long lifetime /* key lifetime */
  177. )
  178. {
  179. EVP_MD_CTX ctx; /* message digest context */
  180. u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
  181. keyid_t keyid; /* key identifer */
  182. u_int32 header[10]; /* data in network byte order */
  183. u_int hdlen, len;
  184. if (!dstadr)
  185. return 0;
  186. /*
  187. * Generate the session key and key ID. If the lifetime is
  188. * greater than zero, install the key and call it trusted.
  189. */
  190. hdlen = 0;
  191. switch(srcadr->ss_family) {
  192. case AF_INET:
  193. header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr;
  194. header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr;
  195. header[2] = htonl(keyno);
  196. header[3] = htonl(private);
  197. hdlen = 4 * sizeof(u_int32);
  198. break;
  199. case AF_INET6:
  200. memcpy(&header[0], &GET_INADDR6(*srcadr),
  201. sizeof(struct in6_addr));
  202. memcpy(&header[4], &GET_INADDR6(*dstadr),
  203. sizeof(struct in6_addr));
  204. header[8] = htonl(keyno);
  205. header[9] = htonl(private);
  206. hdlen = 10 * sizeof(u_int32);
  207. break;
  208. }
  209. EVP_DigestInit(&ctx, EVP_md5());
  210. EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
  211. EVP_DigestFinal(&ctx, dgst, &len);
  212. memcpy(&keyid, dgst, 4);
  213. keyid = ntohl(keyid);
  214. if (lifetime != 0) {
  215. MD5auth_setkey(keyno, dgst, len);
  216. authtrust(keyno, lifetime);
  217. }
  218. #ifdef DEBUG
  219. if (debug > 1)
  220. printf(
  221. "session_key: %s > %s %08x %08x hash %08x life %lu\n",
  222. stoa(srcadr), stoa(dstadr), keyno,
  223. private, keyid, lifetime);
  224. #endif
  225. return (keyid);
  226. }
  227. /*
  228. * make_keylist - generate key list
  229. *
  230. * Returns
  231. * XEVNT_OK success
  232. * XEVNT_PER host certificate expired
  233. *
  234. * This routine constructs a pseudo-random sequence by repeatedly
  235. * hashing the session key starting from a given source address,
  236. * destination address, private value and the next key ID of the
  237. * preceeding session key. The last entry on the list is saved along
  238. * with its sequence number and public signature.
  239. */
  240. int
  241. make_keylist(
  242. struct peer *peer, /* peer structure pointer */
  243. struct interface *dstadr /* interface */
  244. )
  245. {
  246. EVP_MD_CTX ctx; /* signature context */
  247. tstamp_t tstamp; /* NTP timestamp */
  248. struct autokey *ap; /* autokey pointer */
  249. struct value *vp; /* value pointer */
  250. keyid_t keyid = 0; /* next key ID */
  251. keyid_t cookie; /* private value */
  252. u_long lifetime;
  253. u_int len, mpoll;
  254. int i;
  255. if (!dstadr)
  256. return XEVNT_OK;
  257. /*
  258. * Allocate the key list if necessary.
  259. */
  260. tstamp = crypto_time();
  261. if (peer->keylist == NULL)
  262. peer->keylist = emalloc(sizeof(keyid_t) *
  263. NTP_MAXSESSION);
  264. /*
  265. * Generate an initial key ID which is unique and greater than
  266. * NTP_MAXKEY.
  267. */
  268. while (1) {
  269. keyid = (ntp_random() + NTP_MAXKEY + 1) & ((1 <<
  270. sizeof(keyid_t)) - 1);
  271. if (authhavekey(keyid))
  272. continue;
  273. break;
  274. }
  275. /*
  276. * Generate up to NTP_MAXSESSION session keys. Stop if the
  277. * next one would not be unique or not a session key ID or if
  278. * it would expire before the next poll. The private value
  279. * included in the hash is zero if broadcast mode, the peer
  280. * cookie if client mode or the host cookie if symmetric modes.
  281. */
  282. mpoll = 1 << min(peer->ppoll, peer->hpoll);
  283. lifetime = min(sys_automax, NTP_MAXSESSION * mpoll);
  284. if (peer->hmode == MODE_BROADCAST)
  285. cookie = 0;
  286. else
  287. cookie = peer->pcookie;
  288. for (i = 0; i < NTP_MAXSESSION; i++) {
  289. peer->keylist[i] = keyid;
  290. peer->keynumber = i;
  291. keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
  292. cookie, lifetime);
  293. lifetime -= mpoll;
  294. if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
  295. lifetime <= mpoll)
  296. break;
  297. }
  298. /*
  299. * Save the last session key ID, sequence number and timestamp,
  300. * then sign these values for later retrieval by the clients. Be
  301. * careful not to use invalid key media. Use the public values
  302. * timestamp as filestamp.
  303. */
  304. vp = &peer->sndval;
  305. if (vp->ptr == NULL)
  306. vp->ptr = emalloc(sizeof(struct autokey));
  307. ap = (struct autokey *)vp->ptr;
  308. ap->seq = htonl(peer->keynumber);
  309. ap->key = htonl(keyid);
  310. vp->tstamp = htonl(tstamp);
  311. vp->fstamp = hostval.tstamp;
  312. vp->vallen = htonl(sizeof(struct autokey));
  313. vp->siglen = 0;
  314. if (tstamp != 0) {
  315. if (tstamp < cinfo->first || tstamp > cinfo->last)
  316. return (XEVNT_PER);
  317. if (vp->sig == NULL)
  318. vp->sig = emalloc(sign_siglen);
  319. EVP_SignInit(&ctx, sign_digest);
  320. EVP_SignUpdate(&ctx, (u_char *)vp, 12);
  321. EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
  322. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  323. vp->siglen = htonl(len);
  324. else
  325. msyslog(LOG_ERR, "make_keys %s\n",
  326. ERR_error_string(ERR_get_error(), NULL));
  327. peer->flags |= FLAG_ASSOC;
  328. }
  329. #ifdef DEBUG
  330. if (debug)
  331. printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
  332. ntohl(ap->seq), ntohl(ap->key), cookie,
  333. ntohl(vp->tstamp), ntohl(vp->fstamp), peer->hpoll);
  334. #endif
  335. return (XEVNT_OK);
  336. }
  337. /*
  338. * crypto_recv - parse extension fields
  339. *
  340. * This routine is called when the packet has been matched to an
  341. * association and passed sanity, format and MAC checks. We believe the
  342. * extension field values only if the field has proper format and
  343. * length, the timestamp and filestamp are valid and the signature has
  344. * valid length and is verified. There are a few cases where some values
  345. * are believed even if the signature fails, but only if the proventic
  346. * bit is not set.
  347. */
  348. int
  349. crypto_recv(
  350. struct peer *peer, /* peer structure pointer */
  351. struct recvbuf *rbufp /* packet buffer pointer */
  352. )
  353. {
  354. const EVP_MD *dp; /* message digest algorithm */
  355. u_int32 *pkt; /* receive packet pointer */
  356. struct autokey *ap, *bp; /* autokey pointer */
  357. struct exten *ep, *fp; /* extension pointers */
  358. int has_mac; /* length of MAC field */
  359. int authlen; /* offset of MAC field */
  360. associd_t associd; /* association ID */
  361. tstamp_t tstamp = 0; /* timestamp */
  362. tstamp_t fstamp = 0; /* filestamp */
  363. u_int len; /* extension field length */
  364. u_int code; /* extension field opcode */
  365. u_int vallen = 0; /* value length */
  366. X509 *cert; /* X509 certificate */
  367. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  368. keyid_t cookie; /* crumbles */
  369. int hismode; /* packet mode */
  370. int rval = XEVNT_OK;
  371. u_char *ptr;
  372. u_int32 temp32;
  373. /*
  374. * Initialize. Note that the packet has already been checked for
  375. * valid format and extension field lengths. First extract the
  376. * field length, command code and association ID in host byte
  377. * order. These are used with all commands and modes. Then check
  378. * the version number, which must be 2, and length, which must
  379. * be at least 8 for requests and VALUE_LEN (24) for responses.
  380. * Packets that fail either test sink without a trace. The
  381. * association ID is saved only if nonzero.
  382. */
  383. authlen = LEN_PKT_NOMAC;
  384. hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
  385. while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
  386. pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
  387. ep = (struct exten *)pkt;
  388. code = ntohl(ep->opcode) & 0xffff0000;
  389. len = ntohl(ep->opcode) & 0x0000ffff;
  390. associd = (associd_t) ntohl(pkt[1]);
  391. rval = XEVNT_OK;
  392. #ifdef DEBUG
  393. if (debug)
  394. printf(
  395. "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
  396. peer->crypto, authlen, len, code >> 16,
  397. associd);
  398. #endif
  399. /*
  400. * Check version number and field length. If bad,
  401. * quietly ignore the packet.
  402. */
  403. if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
  404. sys_unknownversion++;
  405. code |= CRYPTO_ERROR;
  406. }
  407. /*
  408. * Little vulnerability bandage here. If a perp tosses a
  409. * fake association ID over the fence, we better toss it
  410. * out. Only the first one counts.
  411. */
  412. if (code & CRYPTO_RESP) {
  413. if (peer->assoc == 0)
  414. peer->assoc = associd;
  415. else if (peer->assoc != associd)
  416. code |= CRYPTO_ERROR;
  417. }
  418. if (len >= VALUE_LEN) {
  419. tstamp = ntohl(ep->tstamp);
  420. fstamp = ntohl(ep->fstamp);
  421. vallen = ntohl(ep->vallen);
  422. }
  423. switch (code) {
  424. /*
  425. * Install status word, host name, signature scheme and
  426. * association ID. In OpenSSL the signature algorithm is
  427. * bound to the digest algorithm, so the NID completely
  428. * defines the signature scheme. Note the request and
  429. * response are identical, but neither is validated by
  430. * signature. The request is processed here only in
  431. * symmetric modes. The server name field might be
  432. * useful to implement access controls in future.
  433. */
  434. case CRYPTO_ASSOC:
  435. /*
  436. * If the machine is running when this message
  437. * arrives, the other fellow has reset and so
  438. * must we. Otherwise, pass the extension field
  439. * to the transmit side.
  440. */
  441. if (peer->crypto) {
  442. rval = XEVNT_ERR;
  443. break;
  444. }
  445. fp = emalloc(len);
  446. memcpy(fp, ep, len);
  447. temp32 = CRYPTO_RESP;
  448. fp->opcode |= htonl(temp32);
  449. peer->cmmd = fp;
  450. /* fall through */
  451. case CRYPTO_ASSOC | CRYPTO_RESP:
  452. /*
  453. * Discard the message if it has already been
  454. * stored or the message has been amputated.
  455. */
  456. if (peer->crypto)
  457. break;
  458. if (vallen == 0 || vallen > MAXHOSTNAME ||
  459. len < VALUE_LEN + vallen) {
  460. rval = XEVNT_LEN;
  461. break;
  462. }
  463. /*
  464. * Check the identity schemes are compatible. If
  465. * the client has PC, the server must have PC,
  466. * in which case the server public key and
  467. * identity are presumed valid, so we skip the
  468. * certificate and identity exchanges and move
  469. * immediately to the cookie exchange which
  470. * confirms the server signature.
  471. */
  472. #ifdef DEBUG
  473. if (debug)
  474. printf(
  475. "crypto_recv: ident host 0x%x server 0x%x\n",
  476. crypto_flags, fstamp);
  477. #endif
  478. temp32 = (crypto_flags | ident_scheme) &
  479. fstamp & CRYPTO_FLAG_MASK;
  480. if (crypto_flags & CRYPTO_FLAG_PRIV) {
  481. if (!(fstamp & CRYPTO_FLAG_PRIV)) {
  482. rval = XEVNT_KEY;
  483. break;
  484. } else {
  485. fstamp |= CRYPTO_FLAG_VALID |
  486. CRYPTO_FLAG_VRFY |
  487. CRYPTO_FLAG_SIGN;
  488. }
  489. /*
  490. * In symmetric modes it is an error if either
  491. * peer requests identity and the other peer
  492. * does not support it.
  493. */
  494. } else if ((hismode == MODE_ACTIVE || hismode ==
  495. MODE_PASSIVE) && ((crypto_flags | fstamp) &
  496. CRYPTO_FLAG_MASK) && !temp32) {
  497. rval = XEVNT_KEY;
  498. break;
  499. /*
  500. * It is an error if the client requests
  501. * identity and the server does not support it.
  502. */
  503. } else if (hismode == MODE_CLIENT && (fstamp &
  504. CRYPTO_FLAG_MASK) && !temp32) {
  505. rval = XEVNT_KEY;
  506. break;
  507. }
  508. /*
  509. * Otherwise, the identity scheme(s) are those
  510. * that both client and server support.
  511. */
  512. fstamp = temp32 | (fstamp & ~CRYPTO_FLAG_MASK);
  513. /*
  514. * Discard the message if the signature digest
  515. * NID is not supported.
  516. */
  517. temp32 = (fstamp >> 16) & 0xffff;
  518. dp =
  519. (const EVP_MD *)EVP_get_digestbynid(temp32);
  520. if (dp == NULL) {
  521. rval = XEVNT_MD;
  522. break;
  523. }
  524. /*
  525. * Save status word, host name and message
  526. * digest/signature type.
  527. */
  528. peer->crypto = fstamp;
  529. peer->digest = dp;
  530. peer->subject = emalloc(vallen + 1);
  531. memcpy(peer->subject, ep->pkt, vallen);
  532. peer->subject[vallen] = '\0';
  533. peer->issuer = emalloc(vallen + 1);
  534. strcpy(peer->issuer, peer->subject);
  535. temp32 = (fstamp >> 16) & 0xffff;
  536. snprintf(statstr, NTP_MAXSTRLEN,
  537. "flags 0x%x host %s signature %s", fstamp,
  538. peer->subject, OBJ_nid2ln(temp32));
  539. record_crypto_stats(&peer->srcadr, statstr);
  540. #ifdef DEBUG
  541. if (debug)
  542. printf("crypto_recv: %s\n", statstr);
  543. #endif
  544. break;
  545. /*
  546. * Decode X509 certificate in ASN.1 format and extract
  547. * the data containing, among other things, subject
  548. * name and public key. In the default identification
  549. * scheme, the certificate trail is followed to a self
  550. * signed trusted certificate.
  551. */
  552. case CRYPTO_CERT | CRYPTO_RESP:
  553. /*
  554. * Discard the message if invalid.
  555. */
  556. if ((rval = crypto_verify(ep, NULL, peer)) !=
  557. XEVNT_OK)
  558. break;
  559. /*
  560. * Scan the certificate list to delete old
  561. * versions and link the newest version first on
  562. * the list.
  563. */
  564. if ((rval = cert_install(ep, peer)) != XEVNT_OK)
  565. break;
  566. /*
  567. * If we snatch the certificate before the
  568. * server certificate has been signed by its
  569. * server, it will be self signed. When it is,
  570. * we chase the certificate issuer, which the
  571. * server has, and keep going until a self
  572. * signed trusted certificate is found. Be sure
  573. * to update the issuer field, since it may
  574. * change.
  575. */
  576. if (peer->issuer != NULL)
  577. free(peer->issuer);
  578. peer->issuer = emalloc(strlen(cinfo->issuer) +
  579. 1);
  580. strcpy(peer->issuer, cinfo->issuer);
  581. /*
  582. * We plug in the public key and lifetime from
  583. * the first certificate received. However, note
  584. * that this certificate might not be signed by
  585. * the server, so we can't check the
  586. * signature/digest NID.
  587. */
  588. if (peer->pkey == NULL) {
  589. ptr = (u_char *)cinfo->cert.ptr;
  590. cert = d2i_X509(NULL, &ptr,
  591. ntohl(cinfo->cert.vallen));
  592. peer->pkey = X509_get_pubkey(cert);
  593. X509_free(cert);
  594. }
  595. peer->flash &= ~TEST8;
  596. temp32 = cinfo->nid;
  597. snprintf(statstr, NTP_MAXSTRLEN,
  598. "cert %s 0x%x %s (%u) fs %u",
  599. cinfo->subject, cinfo->flags,
  600. OBJ_nid2ln(temp32), temp32,
  601. ntohl(ep->fstamp));
  602. record_crypto_stats(&peer->srcadr, statstr);
  603. #ifdef DEBUG
  604. if (debug)
  605. printf("crypto_recv: %s\n", statstr);
  606. #endif
  607. break;
  608. /*
  609. * Schnorr (IFF)identity scheme. This scheme is designed
  610. * for use with shared secret group keys and where the
  611. * certificate may be generated by a third party. The
  612. * client sends a challenge to the server, which
  613. * performs a calculation and returns the result. A
  614. * positive result is possible only if both client and
  615. * server contain the same secret group key.
  616. */
  617. case CRYPTO_IFF | CRYPTO_RESP:
  618. /*
  619. * Discard the message if invalid or certificate
  620. * trail not trusted.
  621. */
  622. if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
  623. rval = XEVNT_ERR;
  624. break;
  625. }
  626. if ((rval = crypto_verify(ep, NULL, peer)) !=
  627. XEVNT_OK)
  628. break;
  629. /*
  630. * If the the challenge matches the response,
  631. * the certificate public key, as well as the
  632. * server public key, signatyre and identity are
  633. * all verified at the same time. The server is
  634. * declared trusted, so we skip further
  635. * certificate stages and move immediately to
  636. * the cookie stage.
  637. */
  638. if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
  639. break;
  640. peer->crypto |= CRYPTO_FLAG_VRFY |
  641. CRYPTO_FLAG_PROV;
  642. peer->flash &= ~TEST8;
  643. snprintf(statstr, NTP_MAXSTRLEN, "iff fs %u",
  644. ntohl(ep->fstamp));
  645. record_crypto_stats(&peer->srcadr, statstr);
  646. #ifdef DEBUG
  647. if (debug)
  648. printf("crypto_recv: %s\n", statstr);
  649. #endif
  650. break;
  651. /*
  652. * Guillou-Quisquater (GQ) identity scheme. This scheme
  653. * is designed for use with public certificates carrying
  654. * the GQ public key in an extension field. The client
  655. * sends a challenge to the server, which performs a
  656. * calculation and returns the result. A positive result
  657. * is possible only if both client and server contain
  658. * the same group key and the server has the matching GQ
  659. * private key.
  660. */
  661. case CRYPTO_GQ | CRYPTO_RESP:
  662. /*
  663. * Discard the message if invalid or certificate
  664. * trail not trusted.
  665. */
  666. if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
  667. rval = XEVNT_ERR;
  668. break;
  669. }
  670. if ((rval = crypto_verify(ep, NULL, peer)) !=
  671. XEVNT_OK)
  672. break;
  673. /*
  674. * If the the challenge matches the response,
  675. * the certificate public key, as well as the
  676. * server public key, signatyre and identity are
  677. * all verified at the same time. The server is
  678. * declared trusted, so we skip further
  679. * certificate stages and move immediately to
  680. * the cookie stage.
  681. */
  682. if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
  683. break;
  684. peer->crypto |= CRYPTO_FLAG_VRFY |
  685. CRYPTO_FLAG_PROV;
  686. peer->flash &= ~TEST8;
  687. snprintf(statstr, NTP_MAXSTRLEN, "gq fs %u",
  688. ntohl(ep->fstamp));
  689. record_crypto_stats(&peer->srcadr, statstr);
  690. #ifdef DEBUG
  691. if (debug)
  692. printf("crypto_recv: %s\n", statstr);
  693. #endif
  694. break;
  695. /*
  696. * MV
  697. */
  698. case CRYPTO_MV | CRYPTO_RESP:
  699. /*
  700. * Discard the message if invalid or certificate
  701. * trail not trusted.
  702. */
  703. if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
  704. rval = XEVNT_ERR;
  705. break;
  706. }
  707. if ((rval = crypto_verify(ep, NULL, peer)) !=
  708. XEVNT_OK)
  709. break;
  710. /*
  711. * If the the challenge matches the response,
  712. * the certificate public key, as well as the
  713. * server public key, signatyre and identity are
  714. * all verified at the same time. The server is
  715. * declared trusted, so we skip further
  716. * certificate stages and move immediately to
  717. * the cookie stage.
  718. */
  719. if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
  720. break;
  721. peer->crypto |= CRYPTO_FLAG_VRFY |
  722. CRYPTO_FLAG_PROV;
  723. peer->flash &= ~TEST8;
  724. snprintf(statstr, NTP_MAXSTRLEN, "mv fs %u",
  725. ntohl(ep->fstamp));
  726. record_crypto_stats(&peer->srcadr, statstr);
  727. #ifdef DEBUG
  728. if (debug)
  729. printf("crypto_recv: %s\n", statstr);
  730. #endif
  731. break;
  732. /*
  733. * Cookie request in symmetric modes. Roll a random
  734. * cookie and install in symmetric mode. Encrypt for the
  735. * response, which is transmitted later.
  736. */
  737. case CRYPTO_COOK:
  738. /*
  739. * Discard the message if invalid or certificate
  740. * trail not trusted.
  741. */
  742. if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
  743. rval = XEVNT_ERR;
  744. break;
  745. }
  746. if ((rval = crypto_verify(ep, NULL, peer)) !=
  747. XEVNT_OK)
  748. break;
  749. /*
  750. * Pass the extension field to the transmit
  751. * side. If already agreed, walk away.
  752. */
  753. fp = emalloc(len);
  754. memcpy(fp, ep, len);
  755. temp32 = CRYPTO_RESP;
  756. fp->opcode |= htonl(temp32);
  757. peer->cmmd = fp;
  758. if (peer->crypto & CRYPTO_FLAG_AGREE) {
  759. peer->flash &= ~TEST8;
  760. break;
  761. }
  762. /*
  763. * Install cookie values and light the cookie
  764. * bit. The transmit side will pick up and
  765. * encrypt it for the response.
  766. */
  767. key_expire(peer);
  768. peer->cookval.tstamp = ep->tstamp;
  769. peer->cookval.fstamp = ep->fstamp;
  770. RAND_bytes((u_char *)&peer->pcookie, 4);
  771. peer->crypto &= ~CRYPTO_FLAG_AUTO;
  772. peer->crypto |= CRYPTO_FLAG_AGREE;
  773. peer->flash &= ~TEST8;
  774. snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u",
  775. peer->pcookie, ntohl(ep->tstamp),
  776. ntohl(ep->fstamp));
  777. record_crypto_stats(&peer->srcadr, statstr);
  778. #ifdef DEBUG
  779. if (debug)
  780. printf("crypto_recv: %s\n", statstr);
  781. #endif
  782. break;
  783. /*
  784. * Cookie response in client and symmetric modes. If the
  785. * cookie bit is set, the working cookie is the EXOR of
  786. * the current and new values.
  787. */
  788. case CRYPTO_COOK | CRYPTO_RESP:
  789. /*
  790. * Discard the message if invalid or identity
  791. * not confirmed or signature not verified with
  792. * respect to the cookie values.
  793. */
  794. if (!(peer->crypto & CRYPTO_FLAG_VRFY)) {
  795. rval = XEVNT_ERR;
  796. break;
  797. }
  798. if ((rval = crypto_verify(ep, &peer->cookval,
  799. peer)) != XEVNT_OK)
  800. break;
  801. /*
  802. * Decrypt the cookie, hunting all the time for
  803. * errors.
  804. */
  805. if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
  806. RSA_private_decrypt(vallen,
  807. (u_char *)ep->pkt,
  808. (u_char *)&temp32,
  809. host_pkey->pkey.rsa,
  810. RSA_PKCS1_OAEP_PADDING);
  811. cookie = ntohl(temp32);
  812. } else {
  813. rval = XEVNT_CKY;
  814. break;
  815. }
  816. /*
  817. * Install cookie values and light the cookie
  818. * bit. If this is not broadcast client mode, we
  819. * are done here.
  820. */
  821. key_expire(peer);
  822. peer->cookval.tstamp = ep->tstamp;
  823. peer->cookval.fstamp = ep->fstamp;
  824. if (peer->crypto & CRYPTO_FLAG_AGREE)
  825. peer->pcookie ^= cookie;
  826. else
  827. peer->pcookie = cookie;
  828. if (peer->hmode == MODE_CLIENT &&
  829. !(peer->cast_flags & MDF_BCLNT))
  830. peer->crypto |= CRYPTO_FLAG_AUTO;
  831. else
  832. peer->crypto &= ~CRYPTO_FLAG_AUTO;
  833. peer->crypto |= CRYPTO_FLAG_AGREE;
  834. peer->flash &= ~TEST8;
  835. snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u",
  836. peer->pcookie, ntohl(ep->tstamp),
  837. ntohl(ep->fstamp));
  838. record_crypto_stats(&peer->srcadr, statstr);
  839. #ifdef DEBUG
  840. if (debug)
  841. printf("crypto_recv: %s\n", statstr);
  842. #endif
  843. break;
  844. /*
  845. * Install autokey values in broadcast client and
  846. * symmetric modes. We have to do this every time the
  847. * sever/peer cookie changes or a new keylist is
  848. * rolled. Ordinarily, this is automatic as this message
  849. * is piggybacked on the first NTP packet sent upon
  850. * either of these events. Note that a broadcast client
  851. * or symmetric peer can receive this response without a
  852. * matching request.
  853. */
  854. case CRYPTO_AUTO | CRYPTO_RESP:
  855. /*
  856. * Discard the message if invalid or identity
  857. * not confirmed or signature not verified with
  858. * respect to the receive autokey values.
  859. */
  860. if (!(peer->crypto & CRYPTO_FLAG_VRFY)) {
  861. rval = XEVNT_ERR;
  862. break;
  863. }
  864. if ((rval = crypto_verify(ep, &peer->recval,
  865. peer)) != XEVNT_OK)
  866. break;
  867. /*
  868. * Install autokey values and light the
  869. * autokey bit. This is not hard.
  870. */
  871. if (peer->recval.ptr == NULL)
  872. peer->recval.ptr =
  873. emalloc(sizeof(struct autokey));
  874. bp = (struct autokey *)peer->recval.ptr;
  875. peer->recval.tstamp = ep->tstamp;
  876. peer->recval.fstamp = ep->fstamp;
  877. ap = (struct autokey *)ep->pkt;
  878. bp->seq = ntohl(ap->seq);
  879. bp->key = ntohl(ap->key);
  880. peer->pkeyid = bp->key;
  881. peer->crypto |= CRYPTO_FLAG_AUTO;
  882. peer->flash &= ~TEST8;
  883. snprintf(statstr, NTP_MAXSTRLEN,
  884. "auto seq %d key %x ts %u fs %u", bp->seq,
  885. bp->key, ntohl(ep->tstamp),
  886. ntohl(ep->fstamp));
  887. record_crypto_stats(&peer->srcadr, statstr);
  888. #ifdef DEBUG
  889. if (debug)
  890. printf("crypto_recv: %s\n", statstr);
  891. #endif
  892. break;
  893. /*
  894. * X509 certificate sign response. Validate the
  895. * certificate signed by the server and install. Later
  896. * this can be provided to clients of this server in
  897. * lieu of the self signed certificate in order to
  898. * validate the public key.
  899. */
  900. case CRYPTO_SIGN | CRYPTO_RESP:
  901. /*
  902. * Discard the message if invalid or not
  903. * proventic.
  904. */
  905. if (!(peer->crypto & CRYPTO_FLAG_PROV)) {
  906. rval = XEVNT_ERR;
  907. break;
  908. }
  909. if ((rval = crypto_verify(ep, NULL, peer)) !=
  910. XEVNT_OK)
  911. break;
  912. /*
  913. * Scan the certificate list to delete old
  914. * versions and link the newest version first on
  915. * the list.
  916. */
  917. if ((rval = cert_install(ep, peer)) != XEVNT_OK)
  918. break;
  919. peer->crypto |= CRYPTO_FLAG_SIGN;
  920. peer->flash &= ~TEST8;
  921. temp32 = cinfo->nid;
  922. snprintf(statstr, NTP_MAXSTRLEN,
  923. "sign %s 0x%x %s (%u) fs %u",
  924. cinfo->issuer, cinfo->flags,
  925. OBJ_nid2ln(temp32), temp32,
  926. ntohl(ep->fstamp));
  927. record_crypto_stats(&peer->srcadr, statstr);
  928. #ifdef DEBUG
  929. if (debug)
  930. printf("crypto_recv: %s\n", statstr);
  931. #endif
  932. break;
  933. /*
  934. * Install leapseconds table in symmetric modes. This
  935. * table is proventicated to the NIST primary servers,
  936. * either by copying the file containing the table from
  937. * a NIST server to a trusted server or directly using
  938. * this protocol. While the entire table is installed at
  939. * the server, presently only the current TAI offset is
  940. * provided via the kernel to other applications.
  941. */
  942. case CRYPTO_TAI:
  943. /*
  944. * Discard the message if invalid.
  945. */
  946. if ((rval = crypto_verify(ep, NULL, peer)) !=
  947. XEVNT_OK)
  948. break;
  949. /*
  950. * Pass the extension field to the transmit
  951. * side. Continue below if a leapseconds table
  952. * accompanies the message.
  953. */
  954. fp = emalloc(len);
  955. memcpy(fp, ep, len);
  956. temp32 = CRYPTO_RESP;
  957. fp->opcode |= htonl(temp32);
  958. peer->cmmd = fp;
  959. if (len <= VALUE_LEN) {
  960. peer->flash &= ~TEST8;
  961. break;
  962. }
  963. /* fall through */
  964. case CRYPTO_TAI | CRYPTO_RESP:
  965. /*
  966. * If this is a response, discard the message if
  967. * signature not verified with respect to the
  968. * leapsecond table values.
  969. */
  970. if (peer->cmmd == NULL) {
  971. if ((rval = crypto_verify(ep,
  972. &peer->tai_leap, peer)) != XEVNT_OK)
  973. break;
  974. }
  975. /*
  976. * Initialize peer variables with latest update.
  977. */
  978. peer->tai_leap.tstamp = ep->tstamp;
  979. peer->tai_leap.fstamp = ep->fstamp;
  980. peer->tai_leap.vallen = ep->vallen;
  981. /*
  982. * Install the new table if there is no stored
  983. * table or the new table is more recent than
  984. * the stored table. Since a filestamp may have
  985. * changed, recompute the signatures.
  986. */
  987. if (ntohl(peer->tai_leap.fstamp) >
  988. ntohl(tai_leap.fstamp)) {
  989. tai_leap.fstamp = ep->fstamp;
  990. tai_leap.vallen = ep->vallen;
  991. if (tai_leap.ptr != NULL)
  992. free(tai_leap.ptr);
  993. tai_leap.ptr = emalloc(vallen);
  994. memcpy(tai_leap.ptr, ep->pkt, vallen);
  995. crypto_update();
  996. }
  997. crypto_flags |= CRYPTO_FLAG_TAI;
  998. peer->crypto |= CRYPTO_FLAG_LEAP;
  999. peer->flash &= ~TEST8;
  1000. snprintf(statstr, NTP_MAXSTRLEN,
  1001. "leap %u ts %u fs %u", vallen,
  1002. ntohl(ep->tstamp), ntohl(ep->fstamp));
  1003. record_crypto_stats(&peer->srcadr, statstr);
  1004. #ifdef DEBUG
  1005. if (debug)
  1006. printf("crypto_recv: %s\n", statstr);
  1007. #endif
  1008. break;
  1009. /*
  1010. * We come here in symmetric modes for miscellaneous
  1011. * commands that have value fields but are processed on
  1012. * the transmit side. All we need do here is check for
  1013. * valid field length. Remaining checks are below and on
  1014. * the transmit side.
  1015. */
  1016. case CRYPTO_CERT:
  1017. case CRYPTO_IFF:
  1018. case CRYPTO_GQ:
  1019. case CRYPTO_MV:
  1020. case CRYPTO_SIGN:
  1021. if (len < VALUE_LEN) {
  1022. rval = XEVNT_LEN;
  1023. break;
  1024. }
  1025. /* fall through */
  1026. /*
  1027. * We come here for miscellaneous requests and unknown
  1028. * requests and responses. If an unknown response or
  1029. * error, forget it. If a request, save the extension
  1030. * field for later. Unknown requests will be caught on
  1031. * the transmit side.
  1032. */
  1033. default:
  1034. if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
  1035. rval = XEVNT_ERR;
  1036. } else if ((rval = crypto_verify(ep, NULL,
  1037. peer)) == XEVNT_OK) {
  1038. fp = emalloc(len);
  1039. memcpy(fp, ep, len);
  1040. temp32 = CRYPTO_RESP;
  1041. fp->opcode |= htonl(temp32);
  1042. peer->cmmd = fp;
  1043. }
  1044. }
  1045. /*
  1046. * We don't log length/format/timestamp errors and
  1047. * duplicates, which are log clogging vulnerabilities.
  1048. * The first error found terminates the extension field
  1049. * scan and we return the laundry to the caller. A
  1050. * length/format/timestamp error on transmit is
  1051. * cheerfully ignored, as the message is not sent.
  1052. */
  1053. if (rval > XEVNT_TSP) {
  1054. snprintf(statstr, NTP_MAXSTRLEN,
  1055. "error %x opcode %x ts %u fs %u", rval,
  1056. code, tstamp, fstamp);
  1057. record_crypto_stats(&peer->srcadr, statstr);
  1058. report_event(rval, peer);
  1059. #ifdef DEBUG
  1060. if (debug)
  1061. printf("crypto_recv: %s\n", statstr);
  1062. #endif
  1063. break;
  1064. } else if (rval > XEVNT_OK && (code & CRYPTO_RESP)) {
  1065. rval = XEVNT_OK;
  1066. }
  1067. authlen += len;
  1068. }
  1069. return (rval);
  1070. }
  1071. /*
  1072. * crypto_xmit - construct extension fields
  1073. *
  1074. * This routine is called both when an association is configured and
  1075. * when one is not. The only case where this matters is to retrieve the
  1076. * autokey information, in which case the caller has to provide the
  1077. * association ID to match the association.
  1078. *
  1079. * Returns length of extension field.
  1080. */
  1081. int
  1082. crypto_xmit(
  1083. struct pkt *xpkt, /* transmit packet pointer */
  1084. struct sockaddr_storage *srcadr_sin, /* active runway */
  1085. int start, /* offset to extension field */
  1086. struct exten *ep, /* extension pointer */
  1087. keyid_t cookie /* session cookie */
  1088. )
  1089. {
  1090. u_int32 *pkt; /* packet pointer */
  1091. struct peer *peer; /* peer structure pointer */
  1092. u_int opcode; /* extension field opcode */
  1093. struct exten *fp; /* extension pointers */
  1094. struct cert_info *cp, *xp; /* certificate info/value pointer */
  1095. char certname[MAXHOSTNAME + 1]; /* subject name buffer */
  1096. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  1097. tstamp_t tstamp;
  1098. u_int vallen;
  1099. u_int len;
  1100. struct value vtemp;
  1101. associd_t associd;
  1102. int rval;
  1103. keyid_t tcookie;
  1104. /*
  1105. * Generate the requested extension field request code, length
  1106. * and association ID. If this is a response and the host is not
  1107. * synchronized, light the error bit and go home.
  1108. */
  1109. pkt = (u_int32 *)xpkt + start / 4;
  1110. fp = (struct exten *)pkt;
  1111. opcode = ntohl(ep->opcode);
  1112. associd = (associd_t) ntohl(ep->associd);
  1113. fp->associd = htonl(associd);
  1114. len = 8;
  1115. rval = XEVNT_OK;
  1116. tstamp = crypto_time();
  1117. switch (opcode & 0xffff0000) {
  1118. /*
  1119. * Send association request and response with status word and
  1120. * host name. Note, this message is not signed and the filestamp
  1121. * contains only the status word.
  1122. */
  1123. case CRYPTO_ASSOC | CRYPTO_RESP:
  1124. len += crypto_send(fp, &hostval);
  1125. fp->fstamp = htonl(crypto_flags);
  1126. break;
  1127. case CRYPTO_ASSOC:
  1128. len += crypto_send(fp, &hostval);
  1129. fp->fstamp = htonl(crypto_flags | ident_scheme);
  1130. break;
  1131. /*
  1132. * Send certificate request. Use the values from the extension
  1133. * field.
  1134. */
  1135. case CRYPTO_CERT:
  1136. memset(&vtemp, 0, sizeof(vtemp));
  1137. vtemp.tstamp = ep->tstamp;
  1138. vtemp.fstamp = ep->fstamp;
  1139. vtemp.vallen = ep->vallen;
  1140. vtemp.ptr = (u_char *)ep->pkt;
  1141. len += crypto_send(fp, &vtemp);
  1142. break;
  1143. /*
  1144. * Send certificate response or sign request. Use the values
  1145. * from the certificate cache. If the request contains no
  1146. * subject name, assume the name of this host. This is for
  1147. * backwards compatibility. Private certificates are never sent.
  1148. */
  1149. case CRYPTO_SIGN:
  1150. case CRYPTO_CERT | CRYPTO_RESP:
  1151. vallen = ntohl(ep->vallen);
  1152. if (vallen == 8) {
  1153. strcpy(certname, sys_hostname);
  1154. } else if (vallen == 0 || vallen > MAXHOSTNAME) {
  1155. rval = XEVNT_LEN;
  1156. break;
  1157. } else {
  1158. memcpy(certname, ep->pkt, vallen);
  1159. certname[vallen] = '\0';
  1160. }
  1161. /*
  1162. * Find all certificates with matching subject. If a
  1163. * self-signed, trusted certificate is found, use that.
  1164. * If not, use the first one with matching subject. A
  1165. * private certificate is never divulged or signed.
  1166. */
  1167. xp = NULL;
  1168. for (cp = cinfo; cp != NULL; cp = cp->link) {
  1169. if (cp->flags & CERT_PRIV)
  1170. continue;
  1171. if (strcmp(certname, cp->subject) == 0) {
  1172. if (xp == NULL)
  1173. xp = cp;
  1174. if (strcmp(certname, cp->issuer) ==
  1175. 0 && cp->flags & CERT_TRUST) {
  1176. xp = cp;
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. /*
  1182. * Be careful who you trust. If not yet synchronized,
  1183. * give back an empty response. If certificate not found
  1184. * or beyond the lifetime, return an error. This is to
  1185. * avoid a bad dude trying to get an expired certificate
  1186. * re-signed. Otherwise, send it.
  1187. *
  1188. * Note the timestamp and filestamp are taken from the
  1189. * certificate value structure. For all certificates the
  1190. * timestamp is the latest signature update time. For
  1191. * host and imported certificates the filestamp is the
  1192. * creation epoch. For signed certificates the filestamp
  1193. * is the creation epoch of the trusted certificate at
  1194. * the base of the certificate trail. In principle, this
  1195. * allows strong checking for signature masquerade.
  1196. */
  1197. if (tstamp == 0)
  1198. break;
  1199. if (xp == NULL)
  1200. rval = XEVNT_CRT;
  1201. else if (tstamp < xp->first || tstamp > xp->last)
  1202. rval = XEVNT_SRV;
  1203. else
  1204. len += crypto_send(fp, &xp->cert);
  1205. break;
  1206. /*
  1207. * Send challenge in Schnorr (IFF) identity scheme.
  1208. */
  1209. case CRYPTO_IFF:
  1210. if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
  1211. rval = XEVNT_ERR;
  1212. break;
  1213. }
  1214. if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
  1215. len += crypto_send(fp, &vtemp);
  1216. value_free(&vtemp);
  1217. }
  1218. break;
  1219. /*
  1220. * Send response in Schnorr (IFF) identity scheme.
  1221. */
  1222. case CRYPTO_IFF | CRYPTO_RESP:
  1223. if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
  1224. len += crypto_send(fp, &vtemp);
  1225. value_free(&vtemp);
  1226. }
  1227. break;
  1228. /*
  1229. * Send challenge in Guillou-Quisquater (GQ) identity scheme.
  1230. */
  1231. case CRYPTO_GQ:
  1232. if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
  1233. rval = XEVNT_ERR;
  1234. break;
  1235. }
  1236. if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
  1237. len += crypto_send(fp, &vtemp);
  1238. value_free(&vtemp);
  1239. }
  1240. break;
  1241. /*
  1242. * Send response in Guillou-Quisquater (GQ) identity scheme.
  1243. */
  1244. case CRYPTO_GQ | CRYPTO_RESP:
  1245. if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
  1246. len += crypto_send(fp, &vtemp);
  1247. value_free(&vtemp);
  1248. }
  1249. break;
  1250. /*
  1251. * Send challenge in MV identity scheme.
  1252. */
  1253. case CRYPTO_MV:
  1254. if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
  1255. rval = XEVNT_ERR;
  1256. break;
  1257. }
  1258. if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
  1259. len += crypto_send(fp, &vtemp);
  1260. value_free(&vtemp);
  1261. }
  1262. break;
  1263. /*
  1264. * Send response in MV identity scheme.
  1265. */
  1266. case CRYPTO_MV | CRYPTO_RESP:
  1267. if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
  1268. len += crypto_send(fp, &vtemp);
  1269. value_free(&vtemp);
  1270. }
  1271. break;
  1272. /*
  1273. * Send certificate sign response. The integrity of the request
  1274. * certificate has already been verified on the receive side.
  1275. * Sign the response using the local server key. Use the
  1276. * filestamp from the request and use the timestamp as the
  1277. * current time. Light the error bit if the certificate is
  1278. * invalid or contains an unverified signature.
  1279. */
  1280. case CRYPTO_SIGN | CRYPTO_RESP:
  1281. if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK)
  1282. len += crypto_send(fp, &vtemp);
  1283. value_free(&vtemp);
  1284. break;
  1285. /*
  1286. * Send public key and signature. Use the values from the public
  1287. * key.
  1288. */
  1289. case CRYPTO_COOK:
  1290. len += crypto_send(fp, &pubkey);
  1291. break;
  1292. /*
  1293. * Encrypt and send cookie and signature. Light the error bit if
  1294. * anything goes wrong.
  1295. */
  1296. case CRYPTO_COOK | CRYPTO_RESP:
  1297. if ((opcode & 0xffff) < VALUE_LEN) {
  1298. rval = XEVNT_LEN;
  1299. break;
  1300. }
  1301. if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) {
  1302. tcookie = cookie;
  1303. } else {
  1304. if ((peer = findpeerbyassoc(associd)) == NULL) {
  1305. rval = XEVNT_ERR;
  1306. break;
  1307. }
  1308. tcookie = peer->pcookie;
  1309. }
  1310. if ((rval = crypto_encrypt(ep, &vtemp, &tcookie)) ==
  1311. XEVNT_OK)
  1312. len += crypto_send(fp, &vtemp);
  1313. value_free(&vtemp);
  1314. break;
  1315. /*
  1316. * Find peer and send autokey data and signature in broadcast
  1317. * server and symmetric modes. Use the values in the autokey
  1318. * structure. If no association is found, either the server has
  1319. * restarted with new associations or some perp has replayed an
  1320. * old message, in which case light the error bit.
  1321. */
  1322. case CRYPTO_AUTO | CRYPTO_RESP:
  1323. if ((peer = findpeerbyassoc(associd)) == NULL) {
  1324. rval = XEVNT_ERR;
  1325. break;
  1326. }
  1327. peer->flags &= ~FLAG_ASSOC;
  1328. len += crypto_send(fp, &peer->sndval);
  1329. break;
  1330. /*
  1331. * Send leapseconds table and signature. Use the values from the
  1332. * tai structure. If no table has been loaded, just send an
  1333. * empty request.
  1334. */
  1335. case CRYPTO_TAI:
  1336. case CRYPTO_TAI | CRYPTO_RESP:
  1337. if (crypto_flags & CRYPTO_FLAG_TAI)
  1338. len += crypto_send(fp, &tai_leap);
  1339. break;
  1340. /*
  1341. * Default - Fall through for requests; for unknown responses,
  1342. * flag as error.
  1343. */
  1344. default:
  1345. if (opcode & CRYPTO_RESP)
  1346. rval = XEVNT_ERR;
  1347. }
  1348. /*
  1349. * In case of error, flame the log. If a request, toss the
  1350. * puppy; if a response, return so the sender can flame, too.
  1351. */
  1352. if (rval != XEVNT_OK) {
  1353. opcode |= CRYPTO_ERROR;
  1354. snprintf(statstr, NTP_MAXSTRLEN,
  1355. "error %x opcode %x", rval, opcode);
  1356. record_crypto_stats(srcadr_sin, statstr);
  1357. report_event(rval, NULL);
  1358. #ifdef DEBUG
  1359. if (debug)
  1360. printf("crypto_xmit: %s\n", statstr);
  1361. #endif
  1362. if (!(opcode & CRYPTO_RESP))
  1363. return (0);
  1364. }
  1365. /*
  1366. * Round up the field length to a multiple of 8 bytes and save
  1367. * the request code and length.
  1368. */
  1369. len = ((len + 7) / 8) * 8;
  1370. fp->opcode = htonl((opcode & 0xffff0000) | len);
  1371. #ifdef DEBUG
  1372. if (debug)
  1373. printf(
  1374. "crypto_xmit: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
  1375. crypto_flags, start, len, opcode >> 16, associd);
  1376. #endif
  1377. return (len);
  1378. }
  1379. /*
  1380. * crypto_verify - parse and verify the extension field and value
  1381. *
  1382. * Returns
  1383. * XEVNT_OK success
  1384. * XEVNT_LEN bad field format or length
  1385. * XEVNT_TSP bad timestamp
  1386. * XEVNT_FSP bad filestamp
  1387. * XEVNT_PUB bad or missing public key
  1388. * XEVNT_SGL bad signature length
  1389. * XEVNT_SIG signature not verified
  1390. * XEVNT_ERR protocol error
  1391. */
  1392. static int
  1393. crypto_verify(
  1394. struct exten *ep, /* extension pointer */
  1395. struct value *vp, /* value pointer */
  1396. struct peer *peer /* peer structure pointer */
  1397. )
  1398. {
  1399. EVP_PKEY *pkey; /* server public key */
  1400. EVP_MD_CTX ctx; /* signature context */
  1401. tstamp_t tstamp, tstamp1 = 0; /* timestamp */
  1402. tstamp_t fstamp, fstamp1 = 0; /* filestamp */
  1403. u_int vallen; /* value length */
  1404. u_int siglen; /* signature length */
  1405. u_int opcode, len;
  1406. int i;
  1407. /*
  1408. * We require valid opcode and field lengths, timestamp,
  1409. * filestamp, public key, digest, signature length and
  1410. * signature, where relevant. Note that preliminary length
  1411. * checks are done in the main loop.
  1412. */
  1413. len = ntohl(ep->opcode) & 0x0000ffff;
  1414. opcode = ntohl(ep->opcode) & 0xffff0000;
  1415. /*
  1416. * Check for valid operation code and protocol. The opcode must
  1417. * not have the error bit set. If a response, it must have a
  1418. * value header. If a request and does not contain a value
  1419. * header, no need for further checking.
  1420. */
  1421. if (opcode & CRYPTO_ERROR)
  1422. return (XEVNT_ERR);
  1423. if (opcode & CRYPTO_RESP) {
  1424. if (len < VALUE_LEN)
  1425. return (XEVNT_LEN);
  1426. } else {
  1427. if (len < VALUE_LEN)
  1428. return (XEVNT_OK);
  1429. }
  1430. /*
  1431. * We have a value header. Check for valid field lengths. The
  1432. * field length must be long enough to contain the value header,
  1433. * value and signature. Note both the value and signature fields
  1434. * are rounded up to the next word.
  1435. */
  1436. vallen = ntohl(ep->vallen);
  1437. i = (vallen + 3) / 4;
  1438. siglen = ntohl(ep->pkt[i++]);
  1439. if (len < VALUE_LEN + ((vallen + 3) / 4) * 4 + ((siglen + 3) /
  1440. 4) * 4)
  1441. return (XEVNT_LEN);
  1442. /*
  1443. * Punt if this is a response with no data. Punt if this is a
  1444. * request and a previous response is pending.
  1445. */
  1446. if (opcode & CRYPTO_RESP) {
  1447. if (vallen == 0)
  1448. return (XEVNT_LEN);
  1449. } else {
  1450. if (peer->cmmd != NULL)
  1451. return (XEVNT_LEN);
  1452. }
  1453. /*
  1454. * Check for valid timestamp and filestamp. If the timestamp is
  1455. * zero, the sender is not synchronized and signatures are
  1456. * disregarded. If not, the timestamp must not precede the
  1457. * filestamp. The timestamp and filestamp must not precede the
  1458. * corresponding values in the value structure, if present. Once
  1459. * the autokey values have been installed, the timestamp must
  1460. * always be later than the corresponding value in the value
  1461. * structure. Duplicate timestamps are illegal once the cookie
  1462. * has been validated.
  1463. */
  1464. tstamp = ntohl(ep->tstamp);
  1465. fstamp = ntohl(ep->fstamp);
  1466. if (tstamp == 0)
  1467. return (XEVNT_OK);
  1468. if (tstamp < fstamp)
  1469. return (XEVNT_TSP);
  1470. if (vp != NULL) {
  1471. tstamp1 = ntohl(vp->tstamp);
  1472. fstamp1 = ntohl(vp->fstamp);
  1473. if ((tstamp < tstamp1 || (tstamp == tstamp1 &&
  1474. (peer->crypto & CRYPTO_FLAG_AUTO))))
  1475. return (XEVNT_TSP);
  1476. if ((tstamp < fstamp1 || fstamp < fstamp1))
  1477. return (XEVNT_FSP);
  1478. }
  1479. /*
  1480. * Check for valid signature length, public key and digest
  1481. * algorithm.
  1482. */
  1483. if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
  1484. pkey = sign_pkey;
  1485. else
  1486. pkey = peer->pkey;
  1487. if (siglen == 0 || pkey == NULL || peer->digest == NULL)
  1488. return (XEVNT_OK);
  1489. if (siglen != (u_int)EVP_PKEY_size(pkey))
  1490. return (XEVNT_SGL);
  1491. /*
  1492. * Darn, I thought we would never get here. Verify the
  1493. * signature. If the identity exchange is verified, light the
  1494. * proventic bit. If no client identity scheme is specified,
  1495. * avoid doing the sign exchange.
  1496. */
  1497. EVP_VerifyInit(&ctx, peer->digest);
  1498. EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
  1499. if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen, pkey) <= 0)
  1500. return (XEVNT_SIG);
  1501. if (peer->crypto & CRYPTO_FLAG_VRFY) {
  1502. peer->crypto |= CRYPTO_FLAG_PROV;
  1503. if (!(crypto_flags & CRYPTO_FLAG_MASK))
  1504. peer->crypto |= CRYPTO_FLAG_SIGN;
  1505. }
  1506. return (XEVNT_OK);
  1507. }
  1508. /*
  1509. * crypto_encrypt - construct encrypted cookie and signature from
  1510. * extension field and cookie
  1511. *
  1512. * Returns
  1513. * XEVNT_OK success
  1514. * XEVNT_PUB bad or missing public key
  1515. * XEVNT_CKY bad or missing cookie
  1516. * XEVNT_PER host certificate expired
  1517. */
  1518. static int
  1519. crypto_encrypt(
  1520. struct exten *ep, /* extension pointer */
  1521. struct value *vp, /* value pointer */
  1522. keyid_t *cookie /* server cookie */
  1523. )
  1524. {
  1525. EVP_PKEY *pkey; /* public key */
  1526. EVP_MD_CTX ctx; /* signature context */
  1527. tstamp_t tstamp; /* NTP timestamp */
  1528. u_int32 temp32;
  1529. u_int len;
  1530. u_char *ptr;
  1531. /*
  1532. * Extract the public key from the request.
  1533. */
  1534. len = ntohl(ep->vallen);
  1535. ptr = (u_char *)ep->pkt;
  1536. pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
  1537. if (pkey == NULL) {
  1538. msyslog(LOG_ERR, "crypto_encrypt %s\n",
  1539. ERR_error_string(ERR_get_error(), NULL));
  1540. return (XEVNT_PUB);
  1541. }
  1542. /*
  1543. * Encrypt the cookie, encode in ASN.1 and sign.
  1544. */
  1545. tstamp = crypto_time();
  1546. memset(vp, 0, sizeof(struct value));
  1547. vp->tstamp = htonl(tstamp);
  1548. vp->fstamp = hostval.tstamp;
  1549. len = EVP_PKEY_size(pkey);
  1550. vp->vallen = htonl(len);
  1551. vp->ptr = emalloc(len);
  1552. temp32 = htonl(*cookie);
  1553. if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr,
  1554. pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) {
  1555. msyslog(LOG_ERR, "crypto_encrypt %s\n",
  1556. ERR_error_string(ERR_get_error(), NULL));
  1557. EVP_PKEY_free(pkey);
  1558. return (XEVNT_CKY);
  1559. }
  1560. EVP_PKEY_free(pkey);
  1561. vp->siglen = 0;
  1562. if (tstamp == 0)
  1563. return (XEVNT_OK);
  1564. if (tstamp < cinfo->first || tstamp > cinfo->last)
  1565. return (XEVNT_PER);
  1566. vp->sig = emalloc(sign_siglen);
  1567. EVP_SignInit(&ctx, sign_digest);
  1568. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  1569. EVP_SignUpdate(&ctx, vp->ptr, len);
  1570. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  1571. vp->siglen = htonl(len);
  1572. return (XEVNT_OK);
  1573. }
  1574. /*
  1575. * crypto_ident - construct extension field for identity scheme
  1576. *
  1577. * This routine determines which identity scheme is in use and
  1578. * constructs an extension field for that scheme.
  1579. */
  1580. u_int
  1581. crypto_ident(
  1582. struct peer *peer /* peer structure pointer */
  1583. )
  1584. {
  1585. char filename[MAXFILENAME + 1];
  1586. /*
  1587. * If the server identity has already been verified, no further
  1588. * action is necessary. Otherwise, try to load the identity file
  1589. * of the certificate issuer. If the issuer file is not found,
  1590. * try the host file. If nothing found, declare a cryptobust.
  1591. * Note we can't get here unless the trusted certificate has
  1592. * been found and the CRYPTO_FLAG_VALID bit is set, so the
  1593. * certificate issuer is valid.
  1594. */
  1595. if (peer->ident_pkey != NULL)
  1596. EVP_PKEY_free(peer->ident_pkey);
  1597. if (peer->crypto & CRYPTO_FLAG_GQ) {
  1598. snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
  1599. peer->issuer);
  1600. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1601. if (peer->ident_pkey != NULL)
  1602. return (CRYPTO_GQ);
  1603. snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
  1604. sys_hostname);
  1605. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1606. if (peer->ident_pkey != NULL)
  1607. return (CRYPTO_GQ);
  1608. }
  1609. if (peer->crypto & CRYPTO_FLAG_IFF) {
  1610. snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
  1611. peer->issuer);
  1612. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1613. if (peer->ident_pkey != NULL)
  1614. return (CRYPTO_IFF);
  1615. snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
  1616. sys_hostname);
  1617. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1618. if (peer->ident_pkey != NULL)
  1619. return (CRYPTO_IFF);
  1620. }
  1621. if (peer->crypto & CRYPTO_FLAG_MV) {
  1622. snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
  1623. peer->issuer);
  1624. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1625. if (peer->ident_pkey != NULL)
  1626. return (CRYPTO_MV);
  1627. snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
  1628. sys_hostname);
  1629. peer->ident_pkey = crypto_key(filename, &peer->fstamp);
  1630. if (p