PageRenderTime 37ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/ntp/ntpd/ntp_crypto.c

https://bitbucket.org/freebsd/freebsd-head/
C | 4189 lines | 2414 code | 326 blank | 1449 comment | 577 complexity | 24628f797239e75d9f4988848ef9a38c MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, AGPL-1.0, GPL-2.0
  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 (peer->ident_pkey != NULL)
  1631. return (CRYPTO_MV);
  1632. }
  1633. /*
  1634. * No compatible identity scheme is available. Life is hard.
  1635. */
  1636. msyslog(LOG_INFO,
  1637. "crypto_ident: no compatible identity scheme found");
  1638. return (0);
  1639. }
  1640. /*
  1641. * crypto_args - construct extension field from arguments
  1642. *
  1643. * This routine creates an extension field with current timestamps and
  1644. * specified opcode, association ID and optional string. Note that the
  1645. * extension field is created here, but freed after the crypto_xmit()
  1646. * call in the protocol module.
  1647. *
  1648. * Returns extension field pointer (no errors).
  1649. */
  1650. struct exten *
  1651. crypto_args(
  1652. struct peer *peer, /* peer structure pointer */
  1653. u_int opcode, /* operation code */
  1654. char *str /* argument string */
  1655. )
  1656. {
  1657. tstamp_t tstamp; /* NTP timestamp */
  1658. struct exten *ep; /* extension field pointer */
  1659. u_int len; /* extension field length */
  1660. tstamp = crypto_time();
  1661. len = sizeof(struct exten);
  1662. if (str != NULL)
  1663. len += strlen(str);
  1664. ep = emalloc(len);
  1665. memset(ep, 0, len);
  1666. if (opcode == 0)
  1667. return (ep);
  1668. ep->opcode = htonl(opcode + len);
  1669. /*
  1670. * If a response, send our ID; if a request, send the
  1671. * responder's ID.
  1672. */
  1673. if (opcode & CRYPTO_RESP)
  1674. ep->associd = htonl(peer->associd);
  1675. else
  1676. ep->associd = htonl(peer->assoc);
  1677. ep->tstamp = htonl(tstamp);
  1678. ep->fstamp = hostval.tstamp;
  1679. ep->vallen = 0;
  1680. if (str != NULL) {
  1681. ep->vallen = htonl(strlen(str));
  1682. memcpy((char *)ep->pkt, str, strlen(str));
  1683. } else {
  1684. ep->pkt[0] = peer->associd;
  1685. }
  1686. return (ep);
  1687. }
  1688. /*
  1689. * crypto_send - construct extension field from value components
  1690. *
  1691. * Returns extension field length. Note: it is not polite to send a
  1692. * nonempty signature with zero timestamp or a nonzero timestamp with
  1693. * empty signature, but these rules are not enforced here.
  1694. */
  1695. u_int
  1696. crypto_send(
  1697. struct exten *ep, /* extension field pointer */
  1698. struct value *vp /* value pointer */
  1699. )
  1700. {
  1701. u_int len, temp32;
  1702. int i;
  1703. /*
  1704. * Copy data. If the data field is empty or zero length, encode
  1705. * an empty value with length zero.
  1706. */
  1707. ep->tstamp = vp->tstamp;
  1708. ep->fstamp = vp->fstamp;
  1709. ep->vallen = vp->vallen;
  1710. len = 12;
  1711. temp32 = ntohl(vp->vallen);
  1712. if (temp32 > 0 && vp->ptr != NULL)
  1713. memcpy(ep->pkt, vp->ptr, temp32);
  1714. /*
  1715. * Copy signature. If the signature field is empty or zero
  1716. * length, encode an empty signature with length zero.
  1717. */
  1718. i = (temp32 + 3) / 4;
  1719. len += i * 4 + 4;
  1720. ep->pkt[i++] = vp->siglen;
  1721. temp32 = ntohl(vp->siglen);
  1722. if (temp32 > 0 && vp->sig != NULL)
  1723. memcpy(&ep->pkt[i], vp->sig, temp32);
  1724. len += temp32;
  1725. return (len);
  1726. }
  1727. /*
  1728. * crypto_update - compute new public value and sign extension fields
  1729. *
  1730. * This routine runs periodically, like once a day, and when something
  1731. * changes. It updates the timestamps on three value structures and one
  1732. * value structure list, then signs all the structures:
  1733. *
  1734. * hostval host name (not signed)
  1735. * pubkey public key
  1736. * cinfo certificate info/value list
  1737. * tai_leap leapseconds file
  1738. *
  1739. * Filestamps are proventicated data, so this routine is run only when
  1740. * the host has been synchronized to a proventicated source. Thus, the
  1741. * timestamp is proventicated, too, and can be used to deflect
  1742. * clogging attacks and even cook breakfast.
  1743. *
  1744. * Returns void (no errors)
  1745. */
  1746. void
  1747. crypto_update(void)
  1748. {
  1749. EVP_MD_CTX ctx; /* message digest context */
  1750. struct cert_info *cp, *cpn; /* certificate info/value */
  1751. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  1752. tstamp_t tstamp; /* NTP timestamp */
  1753. u_int len;
  1754. if ((tstamp = crypto_time()) == 0)
  1755. return;
  1756. hostval.tstamp = htonl(tstamp);
  1757. /*
  1758. * Sign public key and timestamps. The filestamp is derived from
  1759. * the host key file extension from wherever the file was
  1760. * generated.
  1761. */
  1762. if (pubkey.vallen != 0) {
  1763. pubkey.tstamp = hostval.tstamp;
  1764. pubkey.siglen = 0;
  1765. if (pubkey.sig == NULL)
  1766. pubkey.sig = emalloc(sign_siglen);
  1767. EVP_SignInit(&ctx, sign_digest);
  1768. EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
  1769. EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
  1770. if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
  1771. pubkey.siglen = htonl(len);
  1772. }
  1773. /*
  1774. * Sign certificates and timestamps. The filestamp is derived
  1775. * from the certificate file extension from wherever the file
  1776. * was generated. Note we do not throw expired certificates
  1777. * away; they may have signed younger ones.
  1778. */
  1779. for (cp = cinfo; cp != NULL; cp = cpn) {
  1780. cpn = cp->link;
  1781. cp->cert.tstamp = hostval.tstamp;
  1782. cp->cert.siglen = 0;
  1783. if (cp->cert.sig == NULL)
  1784. cp->cert.sig = emalloc(sign_siglen);
  1785. EVP_SignInit(&ctx, sign_digest);
  1786. EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
  1787. EVP_SignUpdate(&ctx, cp->cert.ptr,
  1788. ntohl(cp->cert.vallen));
  1789. if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey))
  1790. cp->cert.siglen = htonl(len);
  1791. }
  1792. /*
  1793. * Sign leapseconds table and timestamps. The filestamp is
  1794. * derived from the leapsecond file extension from wherever the
  1795. * file was generated.
  1796. */
  1797. if (tai_leap.vallen != 0) {
  1798. tai_leap.tstamp = hostval.tstamp;
  1799. tai_leap.siglen = 0;
  1800. if (tai_leap.sig == NULL)
  1801. tai_leap.sig = emalloc(sign_siglen);
  1802. EVP_SignInit(&ctx, sign_digest);
  1803. EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
  1804. EVP_SignUpdate(&ctx, tai_leap.ptr,
  1805. ntohl(tai_leap.vallen));
  1806. if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
  1807. tai_leap.siglen = htonl(len);
  1808. }
  1809. snprintf(statstr, NTP_MAXSTRLEN,
  1810. "update ts %u", ntohl(hostval.tstamp));
  1811. record_crypto_stats(NULL, statstr);
  1812. #ifdef DEBUG
  1813. if (debug)
  1814. printf("crypto_update: %s\n", statstr);
  1815. #endif
  1816. }
  1817. /*
  1818. * value_free - free value structure components.
  1819. *
  1820. * Returns void (no errors)
  1821. */
  1822. void
  1823. value_free(
  1824. struct value *vp /* value structure */
  1825. )
  1826. {
  1827. if (vp->ptr != NULL)
  1828. free(vp->ptr);
  1829. if (vp->sig != NULL)
  1830. free(vp->sig);
  1831. memset(vp, 0, sizeof(struct value));
  1832. }
  1833. /*
  1834. * crypto_time - returns current NTP time in seconds.
  1835. */
  1836. tstamp_t
  1837. crypto_time()
  1838. {
  1839. l_fp tstamp; /* NTP time */ L_CLR(&tstamp);
  1840. L_CLR(&tstamp);
  1841. if (sys_leap != LEAP_NOTINSYNC)
  1842. get_systime(&tstamp);
  1843. return (tstamp.l_ui);
  1844. }
  1845. /*
  1846. * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
  1847. */
  1848. u_long
  1849. asn2ntp (
  1850. ASN1_TIME *asn1time /* pointer to ASN1_TIME structure */
  1851. )
  1852. {
  1853. char *v; /* pointer to ASN1_TIME string */
  1854. struct tm tm; /* used to convert to NTP time */
  1855. /*
  1856. * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
  1857. * Note that the YY, MM, DD fields start with one, the HH, MM,
  1858. * SS fiels start with zero and the Z character should be 'Z'
  1859. * for UTC. Also note that years less than 50 map to years
  1860. * greater than 100. Dontcha love ASN.1? Better than MIL-188.
  1861. */
  1862. if (asn1time->length > 13)
  1863. return ((u_long)(~0)); /* We can't use -1 here. It's invalid */
  1864. v = (char *)asn1time->data;
  1865. tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
  1866. if (tm.tm_year < 50)
  1867. tm.tm_year += 100;
  1868. tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
  1869. tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
  1870. tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
  1871. tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
  1872. tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
  1873. tm.tm_wday = 0;
  1874. tm.tm_yday = 0;
  1875. tm.tm_isdst = 0;
  1876. return (timegm(&tm) + JAN_1970);
  1877. }
  1878. /*
  1879. * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
  1880. */
  1881. static int
  1882. bighash(
  1883. BIGNUM *bn, /* BIGNUM * from */
  1884. BIGNUM *bk /* BIGNUM * to */
  1885. )
  1886. {
  1887. EVP_MD_CTX ctx; /* message digest context */
  1888. u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
  1889. u_char *ptr; /* a BIGNUM as binary string */
  1890. u_int len;
  1891. len = BN_num_bytes(bn);
  1892. ptr = emalloc(len);
  1893. BN_bn2bin(bn, ptr);
  1894. EVP_DigestInit(&ctx, EVP_md5());
  1895. EVP_DigestUpdate(&ctx, ptr, len);
  1896. EVP_DigestFinal(&ctx, dgst, &len);
  1897. BN_bin2bn(dgst, len, bk);
  1898. /* XXX MEMLEAK? free ptr? */
  1899. return (1);
  1900. }
  1901. /*
  1902. ***********************************************************************
  1903. * *
  1904. * The following routines implement the Schnorr (IFF) identity scheme *
  1905. * *
  1906. ***********************************************************************
  1907. *
  1908. * The Schnorr (IFF) identity scheme is intended for use when
  1909. * the ntp-genkeys program does not generate the certificates used in
  1910. * the protocol and the group key cannot be conveyed in the certificate
  1911. * itself. For this purpose, new generations of IFF values must be
  1912. * securely transmitted to all members of the group before use. The
  1913. * scheme is self contained and independent of new generations of host
  1914. * keys, sign keys and certificates.
  1915. *
  1916. * The IFF identity scheme is based on DSA cryptography and algorithms
  1917. * described in Stinson p. 285. The IFF values hide in a DSA cuckoo
  1918. * structure, but only the primes and generator are used. The p is a
  1919. * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
  1920. * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
  1921. * group key b disguised as a DSA structure member, then computes public
  1922. * key g^(q - b). These values are shared only among group members and
  1923. * never revealed in messages. Alice challenges Bob to confirm identity
  1924. * using the protocol described below.
  1925. *
  1926. * How it works
  1927. *
  1928. * The scheme goes like this. Both Alice and Bob have the public primes
  1929. * p, q and generator g. The TA gives private key b to Bob and public
  1930. * key v = g^(q - a) mod p to Alice.
  1931. *
  1932. * Alice rolls new random challenge r and sends to Bob in the IFF
  1933. * request message. Bob rolls new random k, then computes y = k + b r
  1934. * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
  1935. * response message. Besides making the response shorter, the hash makes
  1936. * it effectivey impossible for an intruder to solve for b by observing
  1937. * a number of these messages.
  1938. *
  1939. * Alice receives the response and computes g^y v^r mod p. After a bit
  1940. * of algebra, this simplifies to g^k. If the hash of this result
  1941. * matches hash(x), Alice knows that Bob has the group key b. The signed
  1942. * response binds this knowledge to Bob's private key and the public key
  1943. * previously received in his certificate.
  1944. *
  1945. * crypto_alice - construct Alice's challenge in IFF scheme
  1946. *
  1947. * Returns
  1948. * XEVNT_OK success
  1949. * XEVNT_PUB bad or missing public key
  1950. * XEVNT_ID bad or missing group key
  1951. */
  1952. static int
  1953. crypto_alice(
  1954. struct peer *peer, /* peer pointer */
  1955. struct value *vp /* value pointer */
  1956. )
  1957. {
  1958. DSA *dsa; /* IFF parameters */
  1959. BN_CTX *bctx; /* BIGNUM context */
  1960. EVP_MD_CTX ctx; /* signature context */
  1961. tstamp_t tstamp;
  1962. u_int len;
  1963. /*
  1964. * The identity parameters must have correct format and content.
  1965. */
  1966. if (peer->ident_pkey == NULL)
  1967. return (XEVNT_ID);
  1968. if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
  1969. msyslog(LOG_INFO, "crypto_alice: defective key");
  1970. return (XEVNT_PUB);
  1971. }
  1972. /*
  1973. * Roll new random r (0 < r < q). The OpenSSL library has a bug
  1974. * omitting BN_rand_range, so we have to do it the hard way.
  1975. */
  1976. bctx = BN_CTX_new();
  1977. len = BN_num_bytes(dsa->q);
  1978. if (peer->iffval != NULL)
  1979. BN_free(peer->iffval);
  1980. peer->iffval = BN_new();
  1981. BN_rand(peer->iffval, len * 8, -1, 1); /* r */
  1982. BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
  1983. BN_CTX_free(bctx);
  1984. /*
  1985. * Sign and send to Bob. The filestamp is from the local file.
  1986. */
  1987. tstamp = crypto_time();
  1988. memset(vp, 0, sizeof(struct value));
  1989. vp->tstamp = htonl(tstamp);
  1990. vp->fstamp = htonl(peer->fstamp);
  1991. vp->vallen = htonl(len);
  1992. vp->ptr = emalloc(len);
  1993. BN_bn2bin(peer->iffval, vp->ptr);
  1994. vp->siglen = 0;
  1995. if (tstamp == 0)
  1996. return (XEVNT_OK);
  1997. if (tstamp < cinfo->first || tstamp > cinfo->last)
  1998. return (XEVNT_PER);
  1999. vp->sig = emalloc(sign_siglen);
  2000. EVP_SignInit(&ctx, sign_digest);
  2001. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2002. EVP_SignUpdate(&ctx, vp->ptr, len);
  2003. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2004. vp->siglen = htonl(len);
  2005. return (XEVNT_OK);
  2006. }
  2007. /*
  2008. * crypto_bob - construct Bob's response to Alice's challenge
  2009. *
  2010. * Returns
  2011. * XEVNT_OK success
  2012. * XEVNT_ID bad or missing group key
  2013. * XEVNT_ERR protocol error
  2014. * XEVNT_PER host expired certificate
  2015. */
  2016. static int
  2017. crypto_bob(
  2018. struct exten *ep, /* extension pointer */
  2019. struct value *vp /* value pointer */
  2020. )
  2021. {
  2022. DSA *dsa; /* IFF parameters */
  2023. DSA_SIG *sdsa; /* DSA signature context fake */
  2024. BN_CTX *bctx; /* BIGNUM context */
  2025. EVP_MD_CTX ctx; /* signature context */
  2026. tstamp_t tstamp; /* NTP timestamp */
  2027. BIGNUM *bn, *bk, *r;
  2028. u_char *ptr;
  2029. u_int len;
  2030. /*
  2031. * If the IFF parameters are not valid, something awful
  2032. * happened or we are being tormented.
  2033. */
  2034. if (iffpar_pkey == NULL) {
  2035. msyslog(LOG_INFO, "crypto_bob: scheme unavailable");
  2036. return (XEVNT_ID);
  2037. }
  2038. dsa = iffpar_pkey->pkey.dsa;
  2039. /*
  2040. * Extract r from the challenge.
  2041. */
  2042. len = ntohl(ep->vallen);
  2043. if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
  2044. msyslog(LOG_ERR, "crypto_bob %s\n",
  2045. ERR_error_string(ERR_get_error(), NULL));
  2046. return (XEVNT_ERR);
  2047. }
  2048. /*
  2049. * Bob rolls random k (0 < k < q), computes y = k + b r mod q
  2050. * and x = g^k mod p, then sends (y, hash(x)) to Alice.
  2051. */
  2052. bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
  2053. sdsa = DSA_SIG_new();
  2054. BN_rand(bk, len * 8, -1, 1); /* k */
  2055. BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
  2056. BN_add(bn, bn, bk);
  2057. BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
  2058. sdsa->r = BN_dup(bn);
  2059. BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
  2060. bighash(bk, bk);
  2061. sdsa->s = BN_dup(bk);
  2062. BN_CTX_free(bctx);
  2063. BN_free(r); BN_free(bn); BN_free(bk);
  2064. /*
  2065. * Encode the values in ASN.1 and sign.
  2066. */
  2067. tstamp = crypto_time();
  2068. memset(vp, 0, sizeof(struct value));
  2069. vp->tstamp = htonl(tstamp);
  2070. vp->fstamp = htonl(if_fstamp);
  2071. len = i2d_DSA_SIG(sdsa, NULL);
  2072. if (len <= 0) {
  2073. msyslog(LOG_ERR, "crypto_bob %s\n",
  2074. ERR_error_string(ERR_get_error(), NULL));
  2075. DSA_SIG_free(sdsa);
  2076. return (XEVNT_ERR);
  2077. }
  2078. vp->vallen = htonl(len);
  2079. ptr = emalloc(len);
  2080. vp->ptr = ptr;
  2081. i2d_DSA_SIG(sdsa, &ptr);
  2082. DSA_SIG_free(sdsa);
  2083. vp->siglen = 0;
  2084. if (tstamp == 0)
  2085. return (XEVNT_OK);
  2086. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2087. return (XEVNT_PER);
  2088. vp->sig = emalloc(sign_siglen);
  2089. EVP_SignInit(&ctx, sign_digest);
  2090. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2091. EVP_SignUpdate(&ctx, vp->ptr, len);
  2092. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2093. vp->siglen = htonl(len);
  2094. return (XEVNT_OK);
  2095. }
  2096. /*
  2097. * crypto_iff - verify Bob's response to Alice's challenge
  2098. *
  2099. * Returns
  2100. * XEVNT_OK success
  2101. * XEVNT_PUB bad or missing public key
  2102. * XEVNT_ID bad or missing group key
  2103. * XEVNT_FSP bad filestamp
  2104. */
  2105. int
  2106. crypto_iff(
  2107. struct exten *ep, /* extension pointer */
  2108. struct peer *peer /* peer structure pointer */
  2109. )
  2110. {
  2111. DSA *dsa; /* IFF parameters */
  2112. BN_CTX *bctx; /* BIGNUM context */
  2113. DSA_SIG *sdsa; /* DSA parameters */
  2114. BIGNUM *bn, *bk;
  2115. u_int len;
  2116. const u_char *ptr;
  2117. int temp;
  2118. /*
  2119. * If the IFF parameters are not valid or no challenge was sent,
  2120. * something awful happened or we are being tormented.
  2121. */
  2122. if (peer->ident_pkey == NULL) {
  2123. msyslog(LOG_INFO, "crypto_iff: scheme unavailable");
  2124. return (XEVNT_ID);
  2125. }
  2126. if (ntohl(ep->fstamp) != peer->fstamp) {
  2127. msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u",
  2128. ntohl(ep->fstamp));
  2129. return (XEVNT_FSP);
  2130. }
  2131. if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
  2132. msyslog(LOG_INFO, "crypto_iff: defective key");
  2133. return (XEVNT_PUB);
  2134. }
  2135. if (peer->iffval == NULL) {
  2136. msyslog(LOG_INFO, "crypto_iff: missing challenge");
  2137. return (XEVNT_ID);
  2138. }
  2139. /*
  2140. * Extract the k + b r and g^k values from the response.
  2141. */
  2142. bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
  2143. len = ntohl(ep->vallen);
  2144. ptr = (const u_char *)ep->pkt;
  2145. if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
  2146. msyslog(LOG_ERR, "crypto_iff %s\n",
  2147. ERR_error_string(ERR_get_error(), NULL));
  2148. return (XEVNT_ERR);
  2149. }
  2150. /*
  2151. * Compute g^(k + b r) g^(q - b)r mod p.
  2152. */
  2153. BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
  2154. BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
  2155. BN_mod_mul(bn, bn, bk, dsa->p, bctx);
  2156. /*
  2157. * Verify the hash of the result matches hash(x).
  2158. */
  2159. bighash(bn, bn);
  2160. temp = BN_cmp(bn, sdsa->s);
  2161. BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
  2162. BN_free(peer->iffval);
  2163. peer->iffval = NULL;
  2164. DSA_SIG_free(sdsa);
  2165. if (temp == 0)
  2166. return (XEVNT_OK);
  2167. else
  2168. return (XEVNT_ID);
  2169. }
  2170. /*
  2171. ***********************************************************************
  2172. * *
  2173. * The following routines implement the Guillou-Quisquater (GQ) *
  2174. * identity scheme *
  2175. * *
  2176. ***********************************************************************
  2177. *
  2178. * The Guillou-Quisquater (GQ) identity scheme is intended for use when
  2179. * the ntp-genkeys program generates the certificates used in the
  2180. * protocol and the group key can be conveyed in a certificate extension
  2181. * field. The scheme is self contained and independent of new
  2182. * generations of host keys, sign keys and certificates.
  2183. *
  2184. * The GQ identity scheme is based on RSA cryptography and algorithms
  2185. * described in Stinson p. 300 (with errors). The GQ values hide in a
  2186. * RSA cuckoo structure, but only the modulus is used. The 512-bit
  2187. * public modulus is n = p q, where p and q are secret large primes. The
  2188. * TA rolls random group key b disguised as a RSA structure member.
  2189. * Except for the public key, these values are shared only among group
  2190. * members and never revealed in messages.
  2191. *
  2192. * When rolling new certificates, Bob recomputes the private and
  2193. * public keys. The private key u is a random roll, while the public key
  2194. * is the inverse obscured by the group key v = (u^-1)^b. These values
  2195. * replace the private and public keys normally generated by the RSA
  2196. * scheme. Alice challenges Bob to confirm identity using the protocol
  2197. * described below.
  2198. *
  2199. * How it works
  2200. *
  2201. * The scheme goes like this. Both Alice and Bob have the same modulus n
  2202. * and some random b as the group key. These values are computed and
  2203. * distributed in advance via secret means, although only the group key
  2204. * b is truly secret. Each has a private random private key u and public
  2205. * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
  2206. * can regenerate the key pair from time to time without affecting
  2207. * operations. The public key is conveyed on the certificate in an
  2208. * extension field; the private key is never revealed.
  2209. *
  2210. * Alice rolls new random challenge r and sends to Bob in the GQ
  2211. * request message. Bob rolls new random k, then computes y = k u^r mod
  2212. * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
  2213. * message. Besides making the response shorter, the hash makes it
  2214. * effectivey impossible for an intruder to solve for b by observing
  2215. * a number of these messages.
  2216. *
  2217. * Alice receives the response and computes y^b v^r mod n. After a bit
  2218. * of algebra, this simplifies to k^b. If the hash of this result
  2219. * matches hash(x), Alice knows that Bob has the group key b. The signed
  2220. * response binds this knowledge to Bob's private key and the public key
  2221. * previously received in his certificate.
  2222. *
  2223. * crypto_alice2 - construct Alice's challenge in GQ scheme
  2224. *
  2225. * Returns
  2226. * XEVNT_OK success
  2227. * XEVNT_PUB bad or missing public key
  2228. * XEVNT_ID bad or missing group key
  2229. * XEVNT_PER host certificate expired
  2230. */
  2231. static int
  2232. crypto_alice2(
  2233. struct peer *peer, /* peer pointer */
  2234. struct value *vp /* value pointer */
  2235. )
  2236. {
  2237. RSA *rsa; /* GQ parameters */
  2238. BN_CTX *bctx; /* BIGNUM context */
  2239. EVP_MD_CTX ctx; /* signature context */
  2240. tstamp_t tstamp;
  2241. u_int len;
  2242. /*
  2243. * The identity parameters must have correct format and content.
  2244. */
  2245. if (peer->ident_pkey == NULL)
  2246. return (XEVNT_ID);
  2247. if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
  2248. msyslog(LOG_INFO, "crypto_alice2: defective key");
  2249. return (XEVNT_PUB);
  2250. }
  2251. /*
  2252. * Roll new random r (0 < r < n). The OpenSSL library has a bug
  2253. * omitting BN_rand_range, so we have to do it the hard way.
  2254. */
  2255. bctx = BN_CTX_new();
  2256. len = BN_num_bytes(rsa->n);
  2257. if (peer->iffval != NULL)
  2258. BN_free(peer->iffval);
  2259. peer->iffval = BN_new();
  2260. BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
  2261. BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
  2262. BN_CTX_free(bctx);
  2263. /*
  2264. * Sign and send to Bob. The filestamp is from the local file.
  2265. */
  2266. tstamp = crypto_time();
  2267. memset(vp, 0, sizeof(struct value));
  2268. vp->tstamp = htonl(tstamp);
  2269. vp->fstamp = htonl(peer->fstamp);
  2270. vp->vallen = htonl(len);
  2271. vp->ptr = emalloc(len);
  2272. BN_bn2bin(peer->iffval, vp->ptr);
  2273. vp->siglen = 0;
  2274. if (tstamp == 0)
  2275. return (XEVNT_OK);
  2276. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2277. return (XEVNT_PER);
  2278. vp->sig = emalloc(sign_siglen);
  2279. EVP_SignInit(&ctx, sign_digest);
  2280. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2281. EVP_SignUpdate(&ctx, vp->ptr, len);
  2282. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2283. vp->siglen = htonl(len);
  2284. return (XEVNT_OK);
  2285. }
  2286. /*
  2287. * crypto_bob2 - construct Bob's response to Alice's challenge
  2288. *
  2289. * Returns
  2290. * XEVNT_OK success
  2291. * XEVNT_ID bad or missing group key
  2292. * XEVNT_ERR protocol error
  2293. * XEVNT_PER host certificate expired
  2294. */
  2295. static int
  2296. crypto_bob2(
  2297. struct exten *ep, /* extension pointer */
  2298. struct value *vp /* value pointer */
  2299. )
  2300. {
  2301. RSA *rsa; /* GQ parameters */
  2302. DSA_SIG *sdsa; /* DSA parameters */
  2303. BN_CTX *bctx; /* BIGNUM context */
  2304. EVP_MD_CTX ctx; /* signature context */
  2305. tstamp_t tstamp; /* NTP timestamp */
  2306. BIGNUM *r, *k, *g, *y;
  2307. u_char *ptr;
  2308. u_int len;
  2309. /*
  2310. * If the GQ parameters are not valid, something awful
  2311. * happened or we are being tormented.
  2312. */
  2313. if (gqpar_pkey == NULL) {
  2314. msyslog(LOG_INFO, "crypto_bob2: scheme unavailable");
  2315. return (XEVNT_ID);
  2316. }
  2317. rsa = gqpar_pkey->pkey.rsa;
  2318. /*
  2319. * Extract r from the challenge.
  2320. */
  2321. len = ntohl(ep->vallen);
  2322. if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
  2323. msyslog(LOG_ERR, "crypto_bob2 %s\n",
  2324. ERR_error_string(ERR_get_error(), NULL));
  2325. return (XEVNT_ERR);
  2326. }
  2327. /*
  2328. * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
  2329. * x = k^b mod n, then sends (y, hash(x)) to Alice.
  2330. */
  2331. bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
  2332. sdsa = DSA_SIG_new();
  2333. BN_rand(k, len * 8, -1, 1); /* k */
  2334. BN_mod(k, k, rsa->n, bctx);
  2335. BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
  2336. BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
  2337. sdsa->r = BN_dup(y);
  2338. BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
  2339. bighash(g, g);
  2340. sdsa->s = BN_dup(g);
  2341. BN_CTX_free(bctx);
  2342. BN_free(r); BN_free(k); BN_free(g); BN_free(y);
  2343. /*
  2344. * Encode the values in ASN.1 and sign.
  2345. */
  2346. tstamp = crypto_time();
  2347. memset(vp, 0, sizeof(struct value));
  2348. vp->tstamp = htonl(tstamp);
  2349. vp->fstamp = htonl(gq_fstamp);
  2350. len = i2d_DSA_SIG(sdsa, NULL);
  2351. if (len <= 0) {
  2352. msyslog(LOG_ERR, "crypto_bob2 %s\n",
  2353. ERR_error_string(ERR_get_error(), NULL));
  2354. DSA_SIG_free(sdsa);
  2355. return (XEVNT_ERR);
  2356. }
  2357. vp->vallen = htonl(len);
  2358. ptr = emalloc(len);
  2359. vp->ptr = ptr;
  2360. i2d_DSA_SIG(sdsa, &ptr);
  2361. DSA_SIG_free(sdsa);
  2362. vp->siglen = 0;
  2363. if (tstamp == 0)
  2364. return (XEVNT_OK);
  2365. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2366. return (XEVNT_PER);
  2367. vp->sig = emalloc(sign_siglen);
  2368. EVP_SignInit(&ctx, sign_digest);
  2369. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2370. EVP_SignUpdate(&ctx, vp->ptr, len);
  2371. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2372. vp->siglen = htonl(len);
  2373. return (XEVNT_OK);
  2374. }
  2375. /*
  2376. * crypto_gq - verify Bob's response to Alice's challenge
  2377. *
  2378. * Returns
  2379. * XEVNT_OK success
  2380. * XEVNT_PUB bad or missing public key
  2381. * XEVNT_ID bad or missing group keys
  2382. * XEVNT_ERR protocol error
  2383. * XEVNT_FSP bad filestamp
  2384. */
  2385. int
  2386. crypto_gq(
  2387. struct exten *ep, /* extension pointer */
  2388. struct peer *peer /* peer structure pointer */
  2389. )
  2390. {
  2391. RSA *rsa; /* GQ parameters */
  2392. BN_CTX *bctx; /* BIGNUM context */
  2393. DSA_SIG *sdsa; /* RSA signature context fake */
  2394. BIGNUM *y, *v;
  2395. const u_char *ptr;
  2396. u_int len;
  2397. int temp;
  2398. /*
  2399. * If the GQ parameters are not valid or no challenge was sent,
  2400. * something awful happened or we are being tormented.
  2401. */
  2402. if (peer->ident_pkey == NULL) {
  2403. msyslog(LOG_INFO, "crypto_gq: scheme unavailable");
  2404. return (XEVNT_ID);
  2405. }
  2406. if (ntohl(ep->fstamp) != peer->fstamp) {
  2407. msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u",
  2408. ntohl(ep->fstamp));
  2409. return (XEVNT_FSP);
  2410. }
  2411. if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
  2412. msyslog(LOG_INFO, "crypto_gq: defective key");
  2413. return (XEVNT_PUB);
  2414. }
  2415. if (peer->iffval == NULL) {
  2416. msyslog(LOG_INFO, "crypto_gq: missing challenge");
  2417. return (XEVNT_ID);
  2418. }
  2419. /*
  2420. * Extract the y = k u^r and hash(x = k^b) values from the
  2421. * response.
  2422. */
  2423. bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
  2424. len = ntohl(ep->vallen);
  2425. ptr = (const u_char *)ep->pkt;
  2426. if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
  2427. msyslog(LOG_ERR, "crypto_gq %s\n",
  2428. ERR_error_string(ERR_get_error(), NULL));
  2429. return (XEVNT_ERR);
  2430. }
  2431. /*
  2432. * Compute v^r y^b mod n.
  2433. */
  2434. BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
  2435. /* v^r mod n */
  2436. BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
  2437. BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
  2438. /*
  2439. * Verify the hash of the result matches hash(x).
  2440. */
  2441. bighash(y, y);
  2442. temp = BN_cmp(y, sdsa->s);
  2443. BN_CTX_free(bctx); BN_free(y); BN_free(v);
  2444. BN_free(peer->iffval);
  2445. peer->iffval = NULL;
  2446. DSA_SIG_free(sdsa);
  2447. if (temp == 0)
  2448. return (XEVNT_OK);
  2449. else
  2450. return (XEVNT_ID);
  2451. }
  2452. /*
  2453. ***********************************************************************
  2454. * *
  2455. * The following routines implement the Mu-Varadharajan (MV) identity *
  2456. * scheme *
  2457. * *
  2458. ***********************************************************************
  2459. */
  2460. /*
  2461. * The Mu-Varadharajan (MV) cryptosystem was originally intended when
  2462. * servers broadcast messages to clients, but clients never send
  2463. * messages to servers. There is one encryption key for the server and a
  2464. * separate decryption key for each client. It operated something like a
  2465. * pay-per-view satellite broadcasting system where the session key is
  2466. * encrypted by the broadcaster and the decryption keys are held in a
  2467. * tamperproof set-top box.
  2468. *
  2469. * The MV parameters and private encryption key hide in a DSA cuckoo
  2470. * structure which uses the same parameters, but generated in a
  2471. * different way. The values are used in an encryption scheme similar to
  2472. * El Gamal cryptography and a polynomial formed from the expansion of
  2473. * product terms (x - x[j]), as described in Mu, Y., and V.
  2474. * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
  2475. * 223-231. The paper has significant errors and serious omissions.
  2476. *
  2477. * Let q be the product of n distinct primes s'[j] (j = 1...n), where
  2478. * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
  2479. * that q and each s'[j] divide p - 1 and p has M = n * m + 1
  2480. * significant bits. The elements x mod q of Zq with the elements 2 and
  2481. * the primes removed form a field Zq* valid for polynomial arithetic.
  2482. * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
  2483. * mod p. We expect M to be in the 500-bit range and n relatively small,
  2484. * like 25, so the likelihood of a randomly generated element of x mod q
  2485. * of Zq colliding with a factor of p - 1 is very small and can be
  2486. * avoided. Associated with each s'[j] is an element s[j] such that s[j]
  2487. * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
  2488. * s'[j]. These are the parameters of the scheme and they are expensive
  2489. * to compute.
  2490. *
  2491. * We set up an instance of the scheme as follows. A set of random
  2492. * values x[j] mod q (j = 1...n), are generated as the zeros of a
  2493. * polynomial of order n. The product terms (x - x[j]) are expanded to
  2494. * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
  2495. * used as exponents of the generator g mod p to generate the private
  2496. * encryption key A. The pair (gbar, ghat) of public server keys and the
  2497. * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
  2498. * to construct the decryption keys. The devil is in the details.
  2499. *
  2500. * The distinguishing characteristic of this scheme is the capability to
  2501. * revoke keys. Included in the calculation of E, gbar and ghat is the
  2502. * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
  2503. * subsequently removed from the product and E, gbar and ghat
  2504. * recomputed, the jth client will no longer be able to compute E^-1 and
  2505. * thus unable to decrypt the block.
  2506. *
  2507. * How it works
  2508. *
  2509. * The scheme goes like this. Bob has the server values (p, A, q, gbar,
  2510. * ghat) and Alice the client values (p, xbar, xhat).
  2511. *
  2512. * Alice rolls new random challenge r (0 < r < p) and sends to Bob in
  2513. * the MV request message. Bob rolls new random k (0 < k < q), encrypts
  2514. * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
  2515. * Alice.
  2516. *
  2517. * Alice receives the response and computes the decryption key (the
  2518. * inverse permutation) from previously obtained (xbar, xhat) and
  2519. * (gbar^k, ghat^k) in the message. She computes the inverse, which is
  2520. * unique by reasons explained in the ntp-keygen.c program sources. If
  2521. * the hash of this result matches hash(y), Alice knows that Bob has the
  2522. * group key b. The signed response binds this knowledge to Bob's
  2523. * private key and the public key previously received in his
  2524. * certificate.
  2525. *
  2526. * crypto_alice3 - construct Alice's challenge in MV scheme
  2527. *
  2528. * Returns
  2529. * XEVNT_OK success
  2530. * XEVNT_PUB bad or missing public key
  2531. * XEVNT_ID bad or missing group key
  2532. * XEVNT_PER host certificate expired
  2533. */
  2534. static int
  2535. crypto_alice3(
  2536. struct peer *peer, /* peer pointer */
  2537. struct value *vp /* value pointer */
  2538. )
  2539. {
  2540. DSA *dsa; /* MV parameters */
  2541. BN_CTX *bctx; /* BIGNUM context */
  2542. EVP_MD_CTX ctx; /* signature context */
  2543. tstamp_t tstamp;
  2544. u_int len;
  2545. /*
  2546. * The identity parameters must have correct format and content.
  2547. */
  2548. if (peer->ident_pkey == NULL)
  2549. return (XEVNT_ID);
  2550. if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
  2551. msyslog(LOG_INFO, "crypto_alice3: defective key");
  2552. return (XEVNT_PUB);
  2553. }
  2554. /*
  2555. * Roll new random r (0 < r < q). The OpenSSL library has a bug
  2556. * omitting BN_rand_range, so we have to do it the hard way.
  2557. */
  2558. bctx = BN_CTX_new();
  2559. len = BN_num_bytes(dsa->p);
  2560. if (peer->iffval != NULL)
  2561. BN_free(peer->iffval);
  2562. peer->iffval = BN_new();
  2563. BN_rand(peer->iffval, len * 8, -1, 1); /* r */
  2564. BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
  2565. BN_CTX_free(bctx);
  2566. /*
  2567. * Sign and send to Bob. The filestamp is from the local file.
  2568. */
  2569. tstamp = crypto_time();
  2570. memset(vp, 0, sizeof(struct value));
  2571. vp->tstamp = htonl(tstamp);
  2572. vp->fstamp = htonl(peer->fstamp);
  2573. vp->vallen = htonl(len);
  2574. vp->ptr = emalloc(len);
  2575. BN_bn2bin(peer->iffval, vp->ptr);
  2576. vp->siglen = 0;
  2577. if (tstamp == 0)
  2578. return (XEVNT_OK);
  2579. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2580. return (XEVNT_PER);
  2581. vp->sig = emalloc(sign_siglen);
  2582. EVP_SignInit(&ctx, sign_digest);
  2583. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2584. EVP_SignUpdate(&ctx, vp->ptr, len);
  2585. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2586. vp->siglen = htonl(len);
  2587. return (XEVNT_OK);
  2588. }
  2589. /*
  2590. * crypto_bob3 - construct Bob's response to Alice's challenge
  2591. *
  2592. * Returns
  2593. * XEVNT_OK success
  2594. * XEVNT_ERR protocol error
  2595. * XEVNT_PER host certificate expired
  2596. */
  2597. static int
  2598. crypto_bob3(
  2599. struct exten *ep, /* extension pointer */
  2600. struct value *vp /* value pointer */
  2601. )
  2602. {
  2603. DSA *dsa; /* MV parameters */
  2604. DSA *sdsa; /* DSA signature context fake */
  2605. BN_CTX *bctx; /* BIGNUM context */
  2606. EVP_MD_CTX ctx; /* signature context */
  2607. tstamp_t tstamp; /* NTP timestamp */
  2608. BIGNUM *r, *k, *u;
  2609. u_char *ptr;
  2610. u_int len;
  2611. /*
  2612. * If the MV parameters are not valid, something awful
  2613. * happened or we are being tormented.
  2614. */
  2615. if (mvpar_pkey == NULL) {
  2616. msyslog(LOG_INFO, "crypto_bob3: scheme unavailable");
  2617. return (XEVNT_ID);
  2618. }
  2619. dsa = mvpar_pkey->pkey.dsa;
  2620. /*
  2621. * Extract r from the challenge.
  2622. */
  2623. len = ntohl(ep->vallen);
  2624. if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
  2625. msyslog(LOG_ERR, "crypto_bob3 %s\n",
  2626. ERR_error_string(ERR_get_error(), NULL));
  2627. return (XEVNT_ERR);
  2628. }
  2629. /*
  2630. * Bob rolls random k (0 < k < q), making sure it is not a
  2631. * factor of q. He then computes y = A^k r and sends (hash(y),
  2632. * gbar^k, ghat^k) to Alice.
  2633. */
  2634. bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
  2635. sdsa = DSA_new();
  2636. sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
  2637. while (1) {
  2638. BN_rand(k, BN_num_bits(dsa->q), 0, 0);
  2639. BN_mod(k, k, dsa->q, bctx);
  2640. BN_gcd(u, k, dsa->q, bctx);
  2641. if (BN_is_one(u))
  2642. break;
  2643. }
  2644. BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */
  2645. BN_mod_mul(u, u, r, dsa->p, bctx);
  2646. bighash(u, sdsa->p);
  2647. BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
  2648. BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
  2649. BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
  2650. /*
  2651. * Encode the values in ASN.1 and sign.
  2652. */
  2653. tstamp = crypto_time();
  2654. memset(vp, 0, sizeof(struct value));
  2655. vp->tstamp = htonl(tstamp);
  2656. vp->fstamp = htonl(mv_fstamp);
  2657. len = i2d_DSAparams(sdsa, NULL);
  2658. if (len <= 0) {
  2659. msyslog(LOG_ERR, "crypto_bob3 %s\n",
  2660. ERR_error_string(ERR_get_error(), NULL));
  2661. DSA_free(sdsa);
  2662. return (XEVNT_ERR);
  2663. }
  2664. vp->vallen = htonl(len);
  2665. ptr = emalloc(len);
  2666. vp->ptr = ptr;
  2667. i2d_DSAparams(sdsa, &ptr);
  2668. DSA_free(sdsa);
  2669. vp->siglen = 0;
  2670. if (tstamp == 0)
  2671. return (XEVNT_OK);
  2672. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2673. return (XEVNT_PER);
  2674. vp->sig = emalloc(sign_siglen);
  2675. EVP_SignInit(&ctx, sign_digest);
  2676. EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
  2677. EVP_SignUpdate(&ctx, vp->ptr, len);
  2678. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  2679. vp->siglen = htonl(len);
  2680. return (XEVNT_OK);
  2681. }
  2682. /*
  2683. * crypto_mv - verify Bob's response to Alice's challenge
  2684. *
  2685. * Returns
  2686. * XEVNT_OK success
  2687. * XEVNT_PUB bad or missing public key
  2688. * XEVNT_ID bad or missing group key
  2689. * XEVNT_ERR protocol error
  2690. * XEVNT_FSP bad filestamp
  2691. */
  2692. int
  2693. crypto_mv(
  2694. struct exten *ep, /* extension pointer */
  2695. struct peer *peer /* peer structure pointer */
  2696. )
  2697. {
  2698. DSA *dsa; /* MV parameters */
  2699. DSA *sdsa; /* DSA parameters */
  2700. BN_CTX *bctx; /* BIGNUM context */
  2701. BIGNUM *k, *u, *v;
  2702. u_int len;
  2703. const u_char *ptr;
  2704. int temp;
  2705. /*
  2706. * If the MV parameters are not valid or no challenge was sent,
  2707. * something awful happened or we are being tormented.
  2708. */
  2709. if (peer->ident_pkey == NULL) {
  2710. msyslog(LOG_INFO, "crypto_mv: scheme unavailable");
  2711. return (XEVNT_ID);
  2712. }
  2713. if (ntohl(ep->fstamp) != peer->fstamp) {
  2714. msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u",
  2715. ntohl(ep->fstamp));
  2716. return (XEVNT_FSP);
  2717. }
  2718. if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
  2719. msyslog(LOG_INFO, "crypto_mv: defective key");
  2720. return (XEVNT_PUB);
  2721. }
  2722. if (peer->iffval == NULL) {
  2723. msyslog(LOG_INFO, "crypto_mv: missing challenge");
  2724. return (XEVNT_ID);
  2725. }
  2726. /*
  2727. * Extract the (hash(y), gbar, ghat) values from the response.
  2728. */
  2729. bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
  2730. len = ntohl(ep->vallen);
  2731. ptr = (const u_char *)ep->pkt;
  2732. if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
  2733. msyslog(LOG_ERR, "crypto_mv %s\n",
  2734. ERR_error_string(ERR_get_error(), NULL));
  2735. return (XEVNT_ERR);
  2736. }
  2737. /*
  2738. * Compute (gbar^xhat ghat^xbar)^-1 mod p.
  2739. */
  2740. BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
  2741. BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
  2742. BN_mod_mul(u, u, v, dsa->p, bctx);
  2743. BN_mod_inverse(u, u, dsa->p, bctx);
  2744. BN_mod_mul(v, u, peer->iffval, dsa->p, bctx);
  2745. /*
  2746. * The result should match the hash of r mod p.
  2747. */
  2748. bighash(v, v);
  2749. temp = BN_cmp(v, sdsa->p);
  2750. BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
  2751. BN_free(peer->iffval);
  2752. peer->iffval = NULL;
  2753. DSA_free(sdsa);
  2754. if (temp == 0)
  2755. return (XEVNT_OK);
  2756. else
  2757. return (XEVNT_ID);
  2758. }
  2759. /*
  2760. ***********************************************************************
  2761. * *
  2762. * The following routines are used to manipulate certificates *
  2763. * *
  2764. ***********************************************************************
  2765. */
  2766. /*
  2767. * cert_parse - parse x509 certificate and create info/value structures.
  2768. *
  2769. * The server certificate includes the version number, issuer name,
  2770. * subject name, public key and valid date interval. If the issuer name
  2771. * is the same as the subject name, the certificate is self signed and
  2772. * valid only if the server is configured as trustable. If the names are
  2773. * different, another issuer has signed the server certificate and
  2774. * vouched for it. In this case the server certificate is valid if
  2775. * verified by the issuer public key.
  2776. *
  2777. * Returns certificate info/value pointer if valid, NULL if not.
  2778. */
  2779. struct cert_info * /* certificate information structure */
  2780. cert_parse(
  2781. u_char *asn1cert, /* X509 certificate */
  2782. u_int len, /* certificate length */
  2783. tstamp_t fstamp /* filestamp */
  2784. )
  2785. {
  2786. X509 *cert; /* X509 certificate */
  2787. X509_EXTENSION *ext; /* X509v3 extension */
  2788. struct cert_info *ret; /* certificate info/value */
  2789. BIO *bp;
  2790. X509V3_EXT_METHOD *method;
  2791. char pathbuf[MAXFILENAME];
  2792. u_char *uptr;
  2793. char *ptr;
  2794. int temp, cnt, i;
  2795. /*
  2796. * Decode ASN.1 objects and construct certificate structure.
  2797. */
  2798. uptr = asn1cert;
  2799. if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) {
  2800. msyslog(LOG_ERR, "cert_parse %s\n",
  2801. ERR_error_string(ERR_get_error(), NULL));
  2802. return (NULL);
  2803. }
  2804. /*
  2805. * Extract version, subject name and public key.
  2806. */
  2807. ret = emalloc(sizeof(struct cert_info));
  2808. memset(ret, 0, sizeof(struct cert_info));
  2809. if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
  2810. msyslog(LOG_ERR, "cert_parse %s\n",
  2811. ERR_error_string(ERR_get_error(), NULL));
  2812. cert_free(ret);
  2813. X509_free(cert);
  2814. return (NULL);
  2815. }
  2816. ret->version = X509_get_version(cert);
  2817. X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
  2818. MAXFILENAME - 1);
  2819. ptr = strstr(pathbuf, "CN=");
  2820. if (ptr == NULL) {
  2821. msyslog(LOG_INFO, "cert_parse: invalid subject %s",
  2822. pathbuf);
  2823. cert_free(ret);
  2824. X509_free(cert);
  2825. return (NULL);
  2826. }
  2827. ret->subject = emalloc(strlen(ptr) + 1);
  2828. strcpy(ret->subject, ptr + 3);
  2829. /*
  2830. * Extract remaining objects. Note that the NTP serial number is
  2831. * the NTP seconds at the time of signing, but this might not be
  2832. * the case for other authority. We don't bother to check the
  2833. * objects at this time, since the real crunch can happen only
  2834. * when the time is valid but not yet certificated.
  2835. */
  2836. ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
  2837. ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
  2838. ret->serial =
  2839. (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
  2840. X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
  2841. MAXFILENAME);
  2842. if ((ptr = strstr(pathbuf, "CN=")) == NULL) {
  2843. msyslog(LOG_INFO, "cert_parse: invalid issuer %s",
  2844. pathbuf);
  2845. cert_free(ret);
  2846. X509_free(cert);
  2847. return (NULL);
  2848. }
  2849. ret->issuer = emalloc(strlen(ptr) + 1);
  2850. strcpy(ret->issuer, ptr + 3);
  2851. ret->first = asn2ntp(X509_get_notBefore(cert));
  2852. ret->last = asn2ntp(X509_get_notAfter(cert));
  2853. /*
  2854. * Extract extension fields. These are ad hoc ripoffs of
  2855. * currently assigned functions and will certainly be changed
  2856. * before prime time.
  2857. */
  2858. cnt = X509_get_ext_count(cert);
  2859. for (i = 0; i < cnt; i++) {
  2860. ext = X509_get_ext(cert, i);
  2861. method = X509V3_EXT_get(ext);
  2862. temp = OBJ_obj2nid(ext->object);
  2863. switch (temp) {
  2864. /*
  2865. * If a key_usage field is present, we decode whether
  2866. * this is a trusted or private certificate. This is
  2867. * dorky; all we want is to compare NIDs, but OpenSSL
  2868. * insists on BIO text strings.
  2869. */
  2870. case NID_ext_key_usage:
  2871. bp = BIO_new(BIO_s_mem());
  2872. X509V3_EXT_print(bp, ext, 0, 0);
  2873. BIO_gets(bp, pathbuf, MAXFILENAME);
  2874. BIO_free(bp);
  2875. #if DEBUG
  2876. if (debug)
  2877. printf("cert_parse: %s: %s\n",
  2878. OBJ_nid2ln(temp), pathbuf);
  2879. #endif
  2880. if (strcmp(pathbuf, "Trust Root") == 0)
  2881. ret->flags |= CERT_TRUST;
  2882. else if (strcmp(pathbuf, "Private") == 0)
  2883. ret->flags |= CERT_PRIV;
  2884. break;
  2885. /*
  2886. * If a NID_subject_key_identifier field is present, it
  2887. * contains the GQ public key.
  2888. */
  2889. case NID_subject_key_identifier:
  2890. ret->grplen = ext->value->length - 2;
  2891. ret->grpkey = emalloc(ret->grplen);
  2892. memcpy(ret->grpkey, &ext->value->data[2],
  2893. ret->grplen);
  2894. break;
  2895. }
  2896. }
  2897. /*
  2898. * If certificate is self signed, verify signature.
  2899. */
  2900. if (strcmp(ret->subject, ret->issuer) == 0) {
  2901. if (!X509_verify(cert, ret->pkey)) {
  2902. msyslog(LOG_INFO,
  2903. "cert_parse: signature not verified %s",
  2904. pathbuf);
  2905. cert_free(ret);
  2906. X509_free(cert);
  2907. return (NULL);
  2908. }
  2909. }
  2910. /*
  2911. * Verify certificate valid times. Note that certificates cannot
  2912. * be retroactive.
  2913. */
  2914. if (ret->first > ret->last || ret->first < fstamp) {
  2915. msyslog(LOG_INFO,
  2916. "cert_parse: invalid certificate %s first %u last %u fstamp %u",
  2917. ret->subject, ret->first, ret->last, fstamp);
  2918. cert_free(ret);
  2919. X509_free(cert);
  2920. return (NULL);
  2921. }
  2922. /*
  2923. * Build the value structure to sign and send later.
  2924. */
  2925. ret->cert.fstamp = htonl(fstamp);
  2926. ret->cert.vallen = htonl(len);
  2927. ret->cert.ptr = emalloc(len);
  2928. memcpy(ret->cert.ptr, asn1cert, len);
  2929. #ifdef DEBUG
  2930. if (debug > 1)
  2931. X509_print_fp(stdout, cert);
  2932. #endif
  2933. X509_free(cert);
  2934. return (ret);
  2935. }
  2936. /*
  2937. * cert_sign - sign x509 certificate equest and update value structure.
  2938. *
  2939. * The certificate request includes a copy of the host certificate,
  2940. * which includes the version number, subject name and public key of the
  2941. * host. The resulting certificate includes these values plus the
  2942. * serial number, issuer name and valid interval of the server. The
  2943. * valid interval extends from the current time to the same time one
  2944. * year hence. This may extend the life of the signed certificate beyond
  2945. * that of the signer certificate.
  2946. *
  2947. * It is convenient to use the NTP seconds of the current time as the
  2948. * serial number. In the value structure the timestamp is the current
  2949. * time and the filestamp is taken from the extension field. Note this
  2950. * routine is called only when the client clock is synchronized to a
  2951. * proventic source, so timestamp comparisons are valid.
  2952. *
  2953. * The host certificate is valid from the time it was generated for a
  2954. * period of one year. A signed certificate is valid from the time of
  2955. * signature for a period of one year, but only the host certificate (or
  2956. * sign certificate if used) is actually used to encrypt and decrypt
  2957. * signatures. The signature trail is built from the client via the
  2958. * intermediate servers to the trusted server. Each signature on the
  2959. * trail must be valid at the time of signature, but it could happen
  2960. * that a signer certificate expire before the signed certificate, which
  2961. * remains valid until its expiration.
  2962. *
  2963. * Returns
  2964. * XEVNT_OK success
  2965. * XEVNT_PUB bad or missing public key
  2966. * XEVNT_CRT bad or missing certificate
  2967. * XEVNT_VFY certificate not verified
  2968. * XEVNT_PER host certificate expired
  2969. */
  2970. static int
  2971. cert_sign(
  2972. struct exten *ep, /* extension field pointer */
  2973. struct value *vp /* value pointer */
  2974. )
  2975. {
  2976. X509 *req; /* X509 certificate request */
  2977. X509 *cert; /* X509 certificate */
  2978. X509_EXTENSION *ext; /* certificate extension */
  2979. ASN1_INTEGER *serial; /* serial number */
  2980. X509_NAME *subj; /* distinguished (common) name */
  2981. EVP_PKEY *pkey; /* public key */
  2982. EVP_MD_CTX ctx; /* message digest context */
  2983. tstamp_t tstamp; /* NTP timestamp */
  2984. u_int len;
  2985. u_char *ptr;
  2986. int i, temp;
  2987. /*
  2988. * Decode ASN.1 objects and construct certificate structure.
  2989. * Make sure the system clock is synchronized to a proventic
  2990. * source.
  2991. */
  2992. tstamp = crypto_time();
  2993. if (tstamp == 0)
  2994. return (XEVNT_TSP);
  2995. if (tstamp < cinfo->first || tstamp > cinfo->last)
  2996. return (XEVNT_PER);
  2997. ptr = (u_char *)ep->pkt;
  2998. if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) {
  2999. msyslog(LOG_ERR, "cert_sign %s\n",
  3000. ERR_error_string(ERR_get_error(), NULL));
  3001. return (XEVNT_CRT);
  3002. }
  3003. /*
  3004. * Extract public key and check for errors.
  3005. */
  3006. if ((pkey = X509_get_pubkey(req)) == NULL) {
  3007. msyslog(LOG_ERR, "cert_sign %s\n",
  3008. ERR_error_string(ERR_get_error(), NULL));
  3009. X509_free(req);
  3010. return (XEVNT_PUB);
  3011. }
  3012. /*
  3013. * Generate X509 certificate signed by this server. For this
  3014. * purpose the issuer name is the server name. Also copy any
  3015. * extensions that might be present.
  3016. */
  3017. cert = X509_new();
  3018. X509_set_version(cert, X509_get_version(req));
  3019. serial = ASN1_INTEGER_new();
  3020. ASN1_INTEGER_set(serial, tstamp);
  3021. X509_set_serialNumber(cert, serial);
  3022. X509_gmtime_adj(X509_get_notBefore(cert), 0L);
  3023. X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
  3024. subj = X509_get_issuer_name(cert);
  3025. X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
  3026. (u_char *)sys_hostname, strlen(sys_hostname), -1, 0);
  3027. subj = X509_get_subject_name(req);
  3028. X509_set_subject_name(cert, subj);
  3029. X509_set_pubkey(cert, pkey);
  3030. ext = X509_get_ext(req, 0);
  3031. temp = X509_get_ext_count(req);
  3032. for (i = 0; i < temp; i++) {
  3033. ext = X509_get_ext(req, i);
  3034. X509_add_ext(cert, ext, -1);
  3035. }
  3036. X509_free(req);
  3037. /*
  3038. * Sign and verify the certificate.
  3039. */
  3040. X509_sign(cert, sign_pkey, sign_digest);
  3041. if (!X509_verify(cert, sign_pkey)) {
  3042. printf("cert_sign\n%s\n",
  3043. ERR_error_string(ERR_get_error(), NULL));
  3044. X509_free(cert);
  3045. return (XEVNT_VFY);
  3046. }
  3047. len = i2d_X509(cert, NULL);
  3048. /*
  3049. * Build and sign the value structure. We have to sign it here,
  3050. * since the response has to be returned right away. This is a
  3051. * clogging hazard.
  3052. */
  3053. memset(vp, 0, sizeof(struct value));
  3054. vp->tstamp = htonl(tstamp);
  3055. vp->fstamp = ep->fstamp;
  3056. vp->vallen = htonl(len);
  3057. vp->ptr = emalloc(len);
  3058. ptr = vp->ptr;
  3059. i2d_X509(cert, &ptr);
  3060. vp->siglen = 0;
  3061. vp->sig = emalloc(sign_siglen);
  3062. EVP_SignInit(&ctx, sign_digest);
  3063. EVP_SignUpdate(&ctx, (u_char *)vp, 12);
  3064. EVP_SignUpdate(&ctx, vp->ptr, len);
  3065. if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
  3066. vp->siglen = htonl(len);
  3067. #ifdef DEBUG
  3068. if (debug > 1)
  3069. X509_print_fp(stdout, cert);
  3070. #endif
  3071. X509_free(cert);
  3072. return (XEVNT_OK);
  3073. }
  3074. /*
  3075. * cert_valid - verify certificate with given public key
  3076. *
  3077. * This is pretty ugly, as the certificate has to be verified in the
  3078. * OpenSSL X509 structure, not in the DER format in the info/value
  3079. * structure.
  3080. *
  3081. * Returns
  3082. * XEVNT_OK success
  3083. * XEVNT_VFY certificate not verified
  3084. */
  3085. int
  3086. cert_valid(
  3087. struct cert_info *cinf, /* certificate information structure */
  3088. EVP_PKEY *pkey /* public key */
  3089. )
  3090. {
  3091. X509 *cert; /* X509 certificate */
  3092. u_char *ptr;
  3093. if (cinf->flags & CERT_SIGN)
  3094. return (XEVNT_OK);
  3095. ptr = (u_char *)cinf->cert.ptr;
  3096. cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen));
  3097. if (cert == NULL || !X509_verify(cert, pkey))
  3098. return (XEVNT_VFY);
  3099. X509_free(cert);
  3100. return (XEVNT_OK);
  3101. }
  3102. /*
  3103. * cert - install certificate in certificate list
  3104. *
  3105. * This routine encodes an extension field into a certificate info/value
  3106. * structure. It searches the certificate list for duplicates and
  3107. * expunges whichever is older. It then searches the list for other
  3108. * certificates that might be verified by this latest one. Finally, it
  3109. * inserts this certificate first on the list.
  3110. *
  3111. * Returns
  3112. * XEVNT_OK success
  3113. * XEVNT_FSP bad or missing filestamp
  3114. * XEVNT_CRT bad or missing certificate
  3115. */
  3116. int
  3117. cert_install(
  3118. struct exten *ep, /* cert info/value */
  3119. struct peer *peer /* peer structure */
  3120. )
  3121. {
  3122. struct cert_info *cp, *xp, *yp, **zp;
  3123. /*
  3124. * Parse and validate the signed certificate. If valid,
  3125. * construct the info/value structure; otherwise, scamper home.
  3126. */
  3127. if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen),
  3128. ntohl(ep->fstamp))) == NULL)
  3129. return (XEVNT_CRT);
  3130. /*
  3131. * Scan certificate list looking for another certificate with
  3132. * the same subject and issuer. If another is found with the
  3133. * same or older filestamp, unlink it and return the goodies to
  3134. * the heap. If another is found with a later filestamp, discard
  3135. * the new one and leave the building.
  3136. *
  3137. * Make a note to study this issue again. An earlier certificate
  3138. * with a long lifetime might be overtaken by a later
  3139. * certificate with a short lifetime, thus invalidating the
  3140. * earlier signature. However, we gotta find a way to leak old
  3141. * stuff from the cache, so we do it anyway.
  3142. */
  3143. yp = cp;
  3144. zp = &cinfo;
  3145. for (xp = cinfo; xp != NULL; xp = xp->link) {
  3146. if (strcmp(cp->subject, xp->subject) == 0 &&
  3147. strcmp(cp->issuer, xp->issuer) == 0) {
  3148. if (ntohl(cp->cert.fstamp) <=
  3149. ntohl(xp->cert.fstamp)) {
  3150. *zp = xp->link;;
  3151. cert_free(xp);
  3152. } else {
  3153. cert_free(cp);
  3154. return (XEVNT_FSP);
  3155. }
  3156. break;
  3157. }
  3158. zp = &xp->link;
  3159. }
  3160. yp->link = cinfo;
  3161. cinfo = yp;
  3162. /*
  3163. * Scan the certificate list to see if Y is signed by X. This is
  3164. * independent of order.
  3165. */
  3166. for (yp = cinfo; yp != NULL; yp = yp->link) {
  3167. for (xp = cinfo; xp != NULL; xp = xp->link) {
  3168. /*
  3169. * If the issuer of certificate Y matches the
  3170. * subject of certificate X, verify the
  3171. * signature of Y using the public key of X. If
  3172. * so, X signs Y.
  3173. */
  3174. if (strcmp(yp->issuer, xp->subject) != 0 ||
  3175. xp->flags & CERT_ERROR)
  3176. continue;
  3177. if (cert_valid(yp, xp->pkey) != XEVNT_OK) {
  3178. yp->flags |= CERT_ERROR;
  3179. continue;
  3180. }
  3181. /*
  3182. * The signature Y is valid only if it begins
  3183. * during the lifetime of X; however, it is not
  3184. * necessarily an error, since some other
  3185. * certificate might sign Y.
  3186. */
  3187. if (yp->first < xp->first || yp->first >
  3188. xp->last)
  3189. continue;
  3190. yp->flags |= CERT_SIGN;
  3191. /*
  3192. * If X is trusted, then Y is trusted. Note that
  3193. * we might stumble over a self-signed
  3194. * certificate that is not trusted, at least
  3195. * temporarily. This can happen when a dude
  3196. * first comes up, but has not synchronized the
  3197. * clock and had its certificate signed by its
  3198. * server. In case of broken certificate trail,
  3199. * this might result in a loop that could
  3200. * persist until timeout.
  3201. */
  3202. if (!(xp->flags & (CERT_TRUST | CERT_VALID)))
  3203. continue;
  3204. yp->flags |= CERT_VALID;
  3205. /*
  3206. * If subject Y matches the server subject name,
  3207. * then Y has completed the certificate trail.
  3208. * Save the group key and light the valid bit.
  3209. */
  3210. if (strcmp(yp->subject, peer->subject) != 0)
  3211. continue;
  3212. if (yp->grpkey != NULL) {
  3213. if (peer->grpkey != NULL)
  3214. BN_free(peer->grpkey);
  3215. peer->grpkey = BN_bin2bn(yp->grpkey,
  3216. yp->grplen, NULL);
  3217. }
  3218. peer->crypto |= CRYPTO_FLAG_VALID;
  3219. /*
  3220. * If the server has an an identity scheme,
  3221. * fetch the identity credentials. If not, the
  3222. * identity is verified only by the trusted
  3223. * certificate. The next signature will set the
  3224. * server proventic.
  3225. */
  3226. if (peer->crypto & (CRYPTO_FLAG_GQ |
  3227. CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV))
  3228. continue;
  3229. peer->crypto |= CRYPTO_FLAG_VRFY;
  3230. }
  3231. }
  3232. /*
  3233. * That was awesome. Now update the timestamps and signatures.
  3234. */
  3235. crypto_update();
  3236. return (XEVNT_OK);
  3237. }
  3238. /*
  3239. * cert_free - free certificate information structure
  3240. */
  3241. void
  3242. cert_free(
  3243. struct cert_info *cinf /* certificate info/value structure */
  3244. )
  3245. {
  3246. if (cinf->pkey != NULL)
  3247. EVP_PKEY_free(cinf->pkey);
  3248. if (cinf->subject != NULL)
  3249. free(cinf->subject);
  3250. if (cinf->issuer != NULL)
  3251. free(cinf->issuer);
  3252. if (cinf->grpkey != NULL)
  3253. free(cinf->grpkey);
  3254. value_free(&cinf->cert);
  3255. free(cinf);
  3256. }
  3257. /*
  3258. ***********************************************************************
  3259. * *
  3260. * The following routines are used only at initialization time *
  3261. * *
  3262. ***********************************************************************
  3263. */
  3264. /*
  3265. * crypto_key - load cryptographic parameters and keys from files
  3266. *
  3267. * This routine loads a PEM-encoded public/private key pair and extracts
  3268. * the filestamp from the file name.
  3269. *
  3270. * Returns public key pointer if valid, NULL if not. Side effect updates
  3271. * the filestamp if valid.
  3272. */
  3273. static EVP_PKEY *
  3274. crypto_key(
  3275. char *cp, /* file name */
  3276. tstamp_t *fstamp /* filestamp */
  3277. )
  3278. {
  3279. FILE *str; /* file handle */
  3280. EVP_PKEY *pkey = NULL; /* public/private key */
  3281. char filename[MAXFILENAME]; /* name of key file */
  3282. char linkname[MAXFILENAME]; /* filestamp buffer) */
  3283. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  3284. char *ptr;
  3285. /*
  3286. * Open the key file. If the first character of the file name is
  3287. * not '/', prepend the keys directory string. If something goes
  3288. * wrong, abandon ship.
  3289. */
  3290. if (*cp == '/')
  3291. strcpy(filename, cp);
  3292. else
  3293. snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
  3294. str = fopen(filename, "r");
  3295. if (str == NULL)
  3296. return (NULL);
  3297. /*
  3298. * Read the filestamp, which is contained in the first line.
  3299. */
  3300. if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
  3301. msyslog(LOG_ERR, "crypto_key: no data %s\n",
  3302. filename);
  3303. (void)fclose(str);
  3304. return (NULL);
  3305. }
  3306. if ((ptr = strrchr(ptr, '.')) == NULL) {
  3307. msyslog(LOG_ERR, "crypto_key: no filestamp %s\n",
  3308. filename);
  3309. (void)fclose(str);
  3310. return (NULL);
  3311. }
  3312. if (sscanf(++ptr, "%u", fstamp) != 1) {
  3313. msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n",
  3314. filename);
  3315. (void)fclose(str);
  3316. return (NULL);
  3317. }
  3318. /*
  3319. * Read and decrypt PEM-encoded private key.
  3320. */
  3321. pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
  3322. fclose(str);
  3323. if (pkey == NULL) {
  3324. msyslog(LOG_ERR, "crypto_key %s\n",
  3325. ERR_error_string(ERR_get_error(), NULL));
  3326. return (NULL);
  3327. }
  3328. /*
  3329. * Leave tracks in the cryptostats.
  3330. */
  3331. if ((ptr = strrchr(linkname, '\n')) != NULL)
  3332. *ptr = '\0';
  3333. snprintf(statstr, NTP_MAXSTRLEN, "%s mod %d", &linkname[2],
  3334. EVP_PKEY_size(pkey) * 8);
  3335. record_crypto_stats(NULL, statstr);
  3336. #ifdef DEBUG
  3337. if (debug)
  3338. printf("crypto_key: %s\n", statstr);
  3339. if (debug > 1) {
  3340. if (pkey->type == EVP_PKEY_DSA)
  3341. DSA_print_fp(stdout, pkey->pkey.dsa, 0);
  3342. else
  3343. RSA_print_fp(stdout, pkey->pkey.rsa, 0);
  3344. }
  3345. #endif
  3346. return (pkey);
  3347. }
  3348. /*
  3349. * crypto_cert - load certificate from file
  3350. *
  3351. * This routine loads a X.509 RSA or DSA certificate from a file and
  3352. * constructs a info/cert value structure for this machine. The
  3353. * structure includes a filestamp extracted from the file name. Later
  3354. * the certificate can be sent to another machine by request.
  3355. *
  3356. * Returns certificate info/value pointer if valid, NULL if not.
  3357. */
  3358. static struct cert_info * /* certificate information */
  3359. crypto_cert(
  3360. char *cp /* file name */
  3361. )
  3362. {
  3363. struct cert_info *ret; /* certificate information */
  3364. FILE *str; /* file handle */
  3365. char filename[MAXFILENAME]; /* name of certificate file */
  3366. char linkname[MAXFILENAME]; /* filestamp buffer */
  3367. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  3368. tstamp_t fstamp; /* filestamp */
  3369. long len;
  3370. char *ptr;
  3371. char *name, *header;
  3372. u_char *data;
  3373. /*
  3374. * Open the certificate file. If the first character of the file
  3375. * name is not '/', prepend the keys directory string. If
  3376. * something goes wrong, abandon ship.
  3377. */
  3378. if (*cp == '/')
  3379. strcpy(filename, cp);
  3380. else
  3381. snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
  3382. str = fopen(filename, "r");
  3383. if (str == NULL)
  3384. return (NULL);
  3385. /*
  3386. * Read the filestamp, which is contained in the first line.
  3387. */
  3388. if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
  3389. msyslog(LOG_ERR, "crypto_cert: no data %s\n",
  3390. filename);
  3391. (void)fclose(str);
  3392. return (NULL);
  3393. }
  3394. if ((ptr = strrchr(ptr, '.')) == NULL) {
  3395. msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n",
  3396. filename);
  3397. (void)fclose(str);
  3398. return (NULL);
  3399. }
  3400. if (sscanf(++ptr, "%u", &fstamp) != 1) {
  3401. msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n",
  3402. filename);
  3403. (void)fclose(str);
  3404. return (NULL);
  3405. }
  3406. /*
  3407. * Read PEM-encoded certificate and install.
  3408. */
  3409. if (!PEM_read(str, &name, &header, &data, &len)) {
  3410. msyslog(LOG_ERR, "crypto_cert %s\n",
  3411. ERR_error_string(ERR_get_error(), NULL));
  3412. (void)fclose(str);
  3413. return (NULL);
  3414. }
  3415. free(header);
  3416. if (strcmp(name, "CERTIFICATE") !=0) {
  3417. msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s",
  3418. name);
  3419. free(name);
  3420. free(data);
  3421. (void)fclose(str);
  3422. return (NULL);
  3423. }
  3424. free(name);
  3425. /*
  3426. * Parse certificate and generate info/value structure.
  3427. */
  3428. ret = cert_parse(data, len, fstamp);
  3429. free(data);
  3430. (void)fclose(str);
  3431. if (ret == NULL)
  3432. return (NULL);
  3433. if ((ptr = strrchr(linkname, '\n')) != NULL)
  3434. *ptr = '\0';
  3435. snprintf(statstr, NTP_MAXSTRLEN,
  3436. "%s 0x%x len %lu", &linkname[2], ret->flags, len);
  3437. record_crypto_stats(NULL, statstr);
  3438. #ifdef DEBUG
  3439. if (debug)
  3440. printf("crypto_cert: %s\n", statstr);
  3441. #endif
  3442. return (ret);
  3443. }
  3444. /*
  3445. * crypto_tai - load leapseconds table from file
  3446. *
  3447. * This routine loads the ERTS leapsecond file in NIST text format,
  3448. * converts to a value structure and extracts a filestamp from the file
  3449. * name. The data are used to establish the TAI offset from UTC, which
  3450. * is provided to the kernel if supported. Later the data can be sent to
  3451. * another machine on request.
  3452. */
  3453. static void
  3454. crypto_tai(
  3455. char *cp /* file name */
  3456. )
  3457. {
  3458. FILE *str; /* file handle */
  3459. char buf[NTP_MAXSTRLEN]; /* file line buffer */
  3460. u_int32 leapsec[MAX_LEAP]; /* NTP time at leaps */
  3461. int offset; /* offset at leap (s) */
  3462. char filename[MAXFILENAME]; /* name of leapseconds file */
  3463. char linkname[MAXFILENAME]; /* file link (for filestamp) */
  3464. char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
  3465. tstamp_t fstamp; /* filestamp */
  3466. u_int len;
  3467. u_int32 *ptr;
  3468. char *dp;
  3469. int rval, i, j;
  3470. /*
  3471. * Open the file and discard comment lines. If the first
  3472. * character of the file name is not '/', prepend the keys
  3473. * directory string. If the file is not found, not to worry; it
  3474. * can be retrieved over the net. But, if it is found with
  3475. * errors, we crash and burn.
  3476. */
  3477. if (*cp == '/')
  3478. strcpy(filename, cp);
  3479. else
  3480. snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
  3481. if ((str = fopen(filename, "r")) == NULL)
  3482. return;
  3483. /*
  3484. * Extract filestamp if present.
  3485. */
  3486. rval = readlink(filename, linkname, MAXFILENAME - 1);
  3487. if (rval > 0) {
  3488. linkname[rval] = '\0';
  3489. dp = strrchr(linkname, '.');
  3490. } else {
  3491. dp = strrchr(filename, '.');
  3492. }
  3493. if (dp != NULL)
  3494. sscanf(++dp, "%u", &fstamp);
  3495. else
  3496. fstamp = 0;
  3497. tai_leap.fstamp = htonl(fstamp);
  3498. /*
  3499. * We are rather paranoid here, since an intruder might cause a
  3500. * coredump by infiltrating naughty values. Empty lines and
  3501. * comments are ignored. Other lines must begin with two
  3502. * integers followed by junk or comments. The first integer is
  3503. * the NTP seconds of leap insertion, the second is the offset
  3504. * of TAI relative to UTC after that insertion. The second word
  3505. * must equal the initial insertion of ten seconds on 1 January
  3506. * 1972 plus one second for each succeeding insertion.
  3507. */
  3508. i = 0;
  3509. while (i < MAX_LEAP) {
  3510. dp = fgets(buf, NTP_MAXSTRLEN - 1, str);
  3511. if (dp == NULL)
  3512. break;
  3513. if (strlen(buf) < 1)
  3514. continue;
  3515. if (*buf == '#')
  3516. continue;
  3517. if (sscanf(buf, "%u %d", &leapsec[i], &offset) != 2)
  3518. continue;
  3519. if (i != offset - TAI_1972)
  3520. break;
  3521. i++;
  3522. }
  3523. fclose(str);
  3524. if (dp != NULL) {
  3525. msyslog(LOG_INFO,
  3526. "crypto_tai: leapseconds file %s error %d", cp,
  3527. rval);
  3528. exit (-1);
  3529. }
  3530. /*
  3531. * The extension field table entries consists of the NTP seconds
  3532. * of leap insertion in network byte order.
  3533. */
  3534. len = i * sizeof(u_int32);
  3535. tai_leap.vallen = htonl(len);
  3536. ptr = emalloc(len);
  3537. tai_leap.ptr = (u_char *)ptr;
  3538. for (j = 0; j < i; j++)
  3539. *ptr++ = htonl(leapsec[j]);
  3540. crypto_flags |= CRYPTO_FLAG_TAI;
  3541. snprintf(statstr, NTP_MAXSTRLEN, "%s fs %u leap %u len %u", cp, fstamp,
  3542. leapsec[--j], len);
  3543. record_crypto_stats(NULL, statstr);
  3544. #ifdef DEBUG
  3545. if (debug)
  3546. printf("crypto_tai: %s\n", statstr);
  3547. #endif
  3548. }
  3549. /*
  3550. * crypto_setup - load keys, certificate and leapseconds table
  3551. *
  3552. * This routine loads the public/private host key and certificate. If
  3553. * available, it loads the public/private sign key, which defaults to
  3554. * the host key, and leapseconds table. The host key must be RSA, but
  3555. * the sign key can be either RSA or DSA. In either case, the public key
  3556. * on the certificate must agree with the sign key.
  3557. */
  3558. void
  3559. crypto_setup(void)
  3560. {
  3561. EVP_PKEY *pkey; /* private/public key pair */
  3562. char filename[MAXFILENAME]; /* file name buffer */
  3563. l_fp seed; /* crypto PRNG seed as NTP timestamp */
  3564. tstamp_t fstamp; /* filestamp */
  3565. tstamp_t sstamp; /* sign filestamp */
  3566. u_int len, bytes;
  3567. u_char *ptr;
  3568. /*
  3569. * Initialize structures.
  3570. */
  3571. if (!crypto_flags)
  3572. return;
  3573. gethostname(filename, MAXFILENAME);
  3574. bytes = strlen(filename) + 1;
  3575. sys_hostname = emalloc(bytes);
  3576. memcpy(sys_hostname, filename, bytes);
  3577. if (passwd == NULL)
  3578. passwd = sys_hostname;
  3579. memset(&hostval, 0, sizeof(hostval));
  3580. memset(&pubkey, 0, sizeof(pubkey));
  3581. memset(&tai_leap, 0, sizeof(tai_leap));
  3582. /*
  3583. * Load required random seed file and seed the random number
  3584. * generator. Be default, it is found in the user home
  3585. * directory. The root home directory may be / or /root,
  3586. * depending on the system. Wiggle the contents a bit and write
  3587. * it back so the sequence does not repeat when we next restart.
  3588. */
  3589. ERR_load_crypto_strings();
  3590. if (rand_file == NULL) {
  3591. if ((RAND_file_name(filename, MAXFILENAME)) != NULL) {
  3592. rand_file = emalloc(strlen(filename) + 1);
  3593. strcpy(rand_file, filename);
  3594. }
  3595. } else if (*rand_file != '/') {
  3596. snprintf(filename, MAXFILENAME, "%s/%s", keysdir,
  3597. rand_file);
  3598. free(rand_file);
  3599. rand_file = emalloc(strlen(filename) + 1);
  3600. strcpy(rand_file, filename);
  3601. }
  3602. if (rand_file == NULL) {
  3603. msyslog(LOG_ERR,
  3604. "crypto_setup: random seed file not specified");
  3605. exit (-1);
  3606. }
  3607. if ((bytes = RAND_load_file(rand_file, -1)) == 0) {
  3608. msyslog(LOG_ERR,
  3609. "crypto_setup: random seed file %s not found\n",
  3610. rand_file);
  3611. exit (-1);
  3612. }
  3613. get_systime(&seed);
  3614. RAND_seed(&seed, sizeof(l_fp));
  3615. RAND_write_file(rand_file);
  3616. OpenSSL_add_all_algorithms();
  3617. #ifdef DEBUG
  3618. if (debug)
  3619. printf(
  3620. "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
  3621. SSLeay(), rand_file, bytes);
  3622. #endif
  3623. /*
  3624. * Load required host key from file "ntpkey_host_<hostname>". It
  3625. * also becomes the default sign key.
  3626. */
  3627. if (host_file == NULL) {
  3628. snprintf(filename, MAXFILENAME, "ntpkey_host_%s",
  3629. sys_hostname);
  3630. host_file = emalloc(strlen(filename) + 1);
  3631. strcpy(host_file, filename);
  3632. }
  3633. pkey = crypto_key(host_file, &fstamp);
  3634. if (pkey == NULL) {
  3635. msyslog(LOG_ERR,
  3636. "crypto_setup: host key file %s not found or corrupt",
  3637. host_file);
  3638. exit (-1);
  3639. }
  3640. host_pkey = pkey;
  3641. sign_pkey = pkey;
  3642. sstamp = fstamp;
  3643. hostval.fstamp = htonl(fstamp);
  3644. if (host_pkey->type != EVP_PKEY_RSA) {
  3645. msyslog(LOG_ERR,
  3646. "crypto_setup: host key is not RSA key type");
  3647. exit (-1);
  3648. }
  3649. hostval.vallen = htonl(strlen(sys_hostname));
  3650. hostval.ptr = (u_char *)sys_hostname;
  3651. /*
  3652. * Construct public key extension field for agreement scheme.
  3653. */
  3654. len = i2d_PublicKey(host_pkey, NULL);
  3655. ptr = emalloc(len);
  3656. pubkey.ptr = ptr;
  3657. i2d_PublicKey(host_pkey, &ptr);
  3658. pubkey.vallen = htonl(len);
  3659. pubkey.fstamp = hostval.fstamp;
  3660. /*
  3661. * Load optional sign key from file "ntpkey_sign_<hostname>". If
  3662. * loaded, it becomes the sign key.
  3663. */
  3664. if (sign_file == NULL) {
  3665. snprintf(filename, MAXFILENAME, "ntpkey_sign_%s",
  3666. sys_hostname);
  3667. sign_file = emalloc(strlen(filename) + 1);
  3668. strcpy(sign_file, filename);
  3669. }
  3670. pkey = crypto_key(sign_file, &fstamp);
  3671. if (pkey != NULL) {
  3672. sign_pkey = pkey;
  3673. sstamp = fstamp;
  3674. }
  3675. sign_siglen = EVP_PKEY_size(sign_pkey);
  3676. /*
  3677. * Load optional IFF parameters from file
  3678. * "ntpkey_iff_<hostname>".
  3679. */
  3680. if (iffpar_file == NULL) {
  3681. snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
  3682. sys_hostname);
  3683. iffpar_file = emalloc(strlen(filename) + 1);
  3684. strcpy(iffpar_file, filename);
  3685. }
  3686. iffpar_pkey = crypto_key(iffpar_file, &if_fstamp);
  3687. if (iffpar_pkey != NULL)
  3688. crypto_flags |= CRYPTO_FLAG_IFF;
  3689. /*
  3690. * Load optional GQ parameters from file "ntpkey_gq_<hostname>".
  3691. */
  3692. if (gqpar_file == NULL) {
  3693. snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
  3694. sys_hostname);
  3695. gqpar_file = emalloc(strlen(filename) + 1);
  3696. strcpy(gqpar_file, filename);
  3697. }
  3698. gqpar_pkey = crypto_key(gqpar_file, &gq_fstamp);
  3699. if (gqpar_pkey != NULL)
  3700. crypto_flags |= CRYPTO_FLAG_GQ;
  3701. /*
  3702. * Load optional MV parameters from file "ntpkey_mv_<hostname>".
  3703. */
  3704. if (mvpar_file == NULL) {
  3705. snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
  3706. sys_hostname);
  3707. mvpar_file = emalloc(strlen(filename) + 1);
  3708. strcpy(mvpar_file, filename);
  3709. }
  3710. mvpar_pkey = crypto_key(mvpar_file, &mv_fstamp);
  3711. if (mvpar_pkey != NULL)
  3712. crypto_flags |= CRYPTO_FLAG_MV;
  3713. /*
  3714. * Load required certificate from file "ntpkey_cert_<hostname>".
  3715. */
  3716. if (cert_file == NULL) {
  3717. snprintf(filename, MAXFILENAME, "ntpkey_cert_%s",
  3718. sys_hostname);
  3719. cert_file = emalloc(strlen(filename) + 1);
  3720. strcpy(cert_file, filename);
  3721. }
  3722. if ((cinfo = crypto_cert(cert_file)) == NULL) {
  3723. msyslog(LOG_ERR,
  3724. "certificate file %s not found or corrupt",
  3725. cert_file);
  3726. exit (-1);
  3727. }
  3728. /*
  3729. * The subject name must be the same as the host name, unless
  3730. * the certificate is private, in which case it may have come
  3731. * from another host.
  3732. */
  3733. if (!(cinfo->flags & CERT_PRIV) && strcmp(cinfo->subject,
  3734. sys_hostname) != 0) {
  3735. msyslog(LOG_ERR,
  3736. "crypto_setup: certificate %s not for this host",
  3737. cert_file);
  3738. cert_free(cinfo);
  3739. exit (-1);
  3740. }
  3741. /*
  3742. * It the certificate is trusted, the subject must be the same
  3743. * as the issuer, in other words it must be self signed.
  3744. */
  3745. if (cinfo->flags & CERT_TRUST && strcmp(cinfo->subject,
  3746. cinfo->issuer) != 0) {
  3747. if (cert_valid(cinfo, sign_pkey) != XEVNT_OK) {
  3748. msyslog(LOG_ERR,
  3749. "crypto_setup: certificate %s is trusted, but not self signed.",
  3750. cert_file);
  3751. cert_free(cinfo);
  3752. exit (-1);
  3753. }
  3754. }
  3755. sign_digest = cinfo->digest;
  3756. if (cinfo->flags & CERT_PRIV)
  3757. crypto_flags |= CRYPTO_FLAG_PRIV;
  3758. crypto_flags |= cinfo->nid << 16;
  3759. /*
  3760. * Load optional leapseconds table from file "ntpkey_leap". If
  3761. * the file is missing or defective, the values can later be
  3762. * retrieved from a server.
  3763. */
  3764. if (leap_file == NULL)
  3765. leap_file = "ntpkey_leap";
  3766. crypto_tai(leap_file);
  3767. #ifdef DEBUG
  3768. if (debug)
  3769. printf(
  3770. "crypto_setup: flags 0x%x host %s signature %s\n",
  3771. crypto_flags, sys_hostname, OBJ_nid2ln(cinfo->nid));
  3772. #endif
  3773. }
  3774. /*
  3775. * crypto_config - configure data from crypto configuration command.
  3776. */
  3777. void
  3778. crypto_config(
  3779. int item, /* configuration item */
  3780. char *cp /* file name */
  3781. )
  3782. {
  3783. switch (item) {
  3784. /*
  3785. * Set random seed file name.
  3786. */
  3787. case CRYPTO_CONF_RAND:
  3788. rand_file = emalloc(strlen(cp) + 1);
  3789. strcpy(rand_file, cp);
  3790. break;
  3791. /*
  3792. * Set private key password.
  3793. */
  3794. case CRYPTO_CONF_PW:
  3795. passwd = emalloc(strlen(cp) + 1);
  3796. strcpy(passwd, cp);
  3797. break;
  3798. /*
  3799. * Set host file name.
  3800. */
  3801. case CRYPTO_CONF_PRIV:
  3802. host_file = emalloc(strlen(cp) + 1);
  3803. strcpy(host_file, cp);
  3804. break;
  3805. /*
  3806. * Set sign key file name.
  3807. */
  3808. case CRYPTO_CONF_SIGN:
  3809. sign_file = emalloc(strlen(cp) + 1);
  3810. strcpy(sign_file, cp);
  3811. break;
  3812. /*
  3813. * Set iff parameters file name.
  3814. */
  3815. case CRYPTO_CONF_IFFPAR:
  3816. iffpar_file = emalloc(strlen(cp) + 1);
  3817. strcpy(iffpar_file, cp);
  3818. break;
  3819. /*
  3820. * Set gq parameters file name.
  3821. */
  3822. case CRYPTO_CONF_GQPAR:
  3823. gqpar_file = emalloc(strlen(cp) + 1);
  3824. strcpy(gqpar_file, cp);
  3825. break;
  3826. /*
  3827. * Set mv parameters file name.
  3828. */
  3829. case CRYPTO_CONF_MVPAR:
  3830. mvpar_file = emalloc(strlen(cp) + 1);
  3831. strcpy(mvpar_file, cp);
  3832. break;
  3833. /*
  3834. * Set identity scheme.
  3835. */
  3836. case CRYPTO_CONF_IDENT:
  3837. if (!strcasecmp(cp, "iff"))
  3838. ident_scheme |= CRYPTO_FLAG_IFF;
  3839. else if (!strcasecmp(cp, "gq"))
  3840. ident_scheme |= CRYPTO_FLAG_GQ;
  3841. else if (!strcasecmp(cp, "mv"))
  3842. ident_scheme |= CRYPTO_FLAG_MV;
  3843. break;
  3844. /*
  3845. * Set certificate file name.
  3846. */
  3847. case CRYPTO_CONF_CERT:
  3848. cert_file = emalloc(strlen(cp) + 1);
  3849. strcpy(cert_file, cp);
  3850. break;
  3851. /*
  3852. * Set leapseconds file name.
  3853. */
  3854. case CRYPTO_CONF_LEAP:
  3855. leap_file = emalloc(strlen(cp) + 1);
  3856. strcpy(leap_file, cp);
  3857. break;
  3858. }
  3859. crypto_flags |= CRYPTO_FLAG_ENAB;
  3860. }
  3861. # else
  3862. int ntp_crypto_bs_pubkey;
  3863. # endif /* OPENSSL */