303
351
* extension field values only if the field has proper format and
304
352
* length, the timestamp and filestamp are valid and the signature has
305
353
* valid length and is verified. There are a few cases where some values
306
* are believed even if the signature fails, but only if the authentic
354
* are believed even if the signature fails, but only if the proventic
307
355
* bit is not set.
311
359
struct peer *peer, /* peer structure pointer */
312
360
struct recvbuf *rbufp /* packet buffer pointer */
315
u_int32 *pkt; /* packet pointer */
316
struct autokey *ap; /* autokey pointer */
317
struct cookie *cp; /* cookie pointer */
318
int has_mac; /* length of MAC field */
319
int authlen; /* offset of MAC field */
320
int len; /* extension field length */
321
u_int code; /* extension field opcode */
322
tstamp_t tstamp; /* timestamp */
326
R_SIGNATURE_CTX ctx; /* signature context */
327
struct value *vp; /* value pointer */
328
u_char dh_key[MAX_KEYLEN]; /* agreed key */
329
R_RSA_PUBLIC_KEY *kp; /* temporary public key pointer */
330
tstamp_t fstamp; /* filestamp */
331
u_int32 *pp; /* packet pointer */
332
u_int rsalen = sizeof(R_RSA_PUBLIC_KEY) - sizeof(u_int) + 4;
363
const EVP_MD *dp; /* message digest algorithm */
364
u_int32 *pkt; /* receive packet pointer */
365
struct autokey *ap, *bp; /* autokey pointer */
366
struct exten *ep, *fp; /* extension pointers */
367
int has_mac; /* length of MAC field */
368
int authlen; /* offset of MAC field */
369
associd_t associd; /* association ID */
370
tstamp_t tstamp = 0; /* timestamp */
371
tstamp_t fstamp = 0; /* filestamp */
372
u_int len; /* extension field length */
373
u_int code; /* extension field opcode */
374
u_int vallen = 0; /* value length */
375
X509 *cert; /* X509 certificate */
376
char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
377
keyid_t cookie; /* crumbles */
335
381
#ifdef KERNEL_PLL
337
383
struct timex ntv; /* kernel interface structure */
338
384
#endif /* NTP_API */
339
385
#endif /* KERNEL_PLL */
343
388
* Initialize. Note that the packet has already been checked for
344
* valid format and extension field lengths. We first extract
345
* the field length, command code and timestamp in host byte
346
* order. These are used with all commands and modes. We discard
347
* old timestamps and filestamps; but, for duplicate timestamps
348
* we discard only if the authentic bit is set. Cute.
389
* valid format and extension field lengths. First extract the
390
* field length, command code and association ID in host byte
391
* order. These are used with all commands and modes. Then check
392
* the version number, which must be 2, and length, which must
393
* be at least 8 for requests and VALUE_LEN (24) for responses.
394
* Packets that fail either test sink without a trace. The
395
* association ID is saved only if nonzero.
350
pkt = (u_int32 *)&rbufp->recv_pkt;
351
397
authlen = LEN_PKT_NOMAC;
352
398
while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
354
len = ntohl(pkt[i]) & 0xffff;
355
code = (ntohl(pkt[i]) >> 16) & 0xffff;
356
temp = (code >> 8) & 0x3f;
357
if (temp != CRYPTO_VN) {
399
pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
400
ep = (struct exten *)pkt;
401
code = ntohl(ep->opcode) & 0xffff0000;
402
len = ntohl(ep->opcode) & 0x0000ffff;
403
associd = (associd_t) ntohl(pkt[1]);
408
"crypto_recv: flags 0x%x ext offset %d len %u code %x assocID %d\n",
409
peer->crypto, authlen, len, code >> 16,
414
* Check version number and field length. If bad,
415
* quietly ignore the packet.
417
if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8 ||
418
(len < VALUE_LEN && (code & CRYPTO_RESP))) {
358
419
sys_unknownversion++;
362
"crypto_recv: incorrect version %d should be %d\n",
367
tstamp = ntohl(pkt[i + 2]);
371
"crypto_recv: ext offset %d len %d code %x assocID %d\n",
372
authlen, len, code, (u_int32)ntohl(pkt[i +
420
code |= CRYPTO_ERROR;
424
* Little vulnerability bandage here. If a perp tosses a
425
* fake association ID over the fence, we better toss it
426
* out. Only the first one counts.
428
if (code & CRYPTO_RESP) {
429
if (peer->assoc == 0)
430
peer->assoc = associd;
431
else if (peer->assoc != associd)
432
code |= CRYPTO_ERROR;
434
if (len >= VALUE_LEN) {
435
tstamp = ntohl(ep->tstamp);
436
fstamp = ntohl(ep->fstamp);
437
vallen = ntohl(ep->vallen);
378
* Install association ID and status word.
442
* Install status word, host name, signature scheme and
443
* association ID. In OpenSSL the signature algorithm is
444
* bound to the digest algorithm, so the NID completely
445
* defines the signature scheme. Note the request and
446
* response are identical, but neither is validated by
447
* signature. The request is processed here only in
448
* symmetric modes. The server name field would be
449
* useful to implement access controls in future.
454
* Pass the extension field to the transmit
459
temp32 = CRYPTO_RESP;
460
fp->opcode |= htonl(temp32);
380
464
case CRYPTO_ASSOC | CRYPTO_RESP:
381
cp = (struct cookie *)&pkt[i + 2];
382
temp = ntohl(cp->key);
383
if (len < COOKIE_LEN) {
385
} else if (tstamp == 0) {
467
* Discard the message if it has already been
468
* stored or the server is not synchronized.
470
if (peer->crypto || !fstamp)
473
if (len < VALUE_LEN + vallen) {
479
* Check the identity schemes are compatible. If
480
* the client has PC, the server must have PC,
481
* in which case the server public key and
482
* identity are presumed valid, so we skip the
483
* certificate and identity exchanges and move
484
* immediately to the cookie exchange which
485
* confirms the server signature. If the client
486
* has IFF or GC or both, the server must have
487
* the same one or both. Otherwise, the default
490
if (crypto_flags & CRYPTO_FLAG_PRIV) {
491
if (!(fstamp & CRYPTO_FLAG_PRIV))
494
fstamp |= CRYPTO_FLAG_VALID |
496
} else if (crypto_flags & CRYPTO_FLAG_MASK &&
497
!(crypto_flags & fstamp &
503
* Discard the message if identity error.
505
if (rval != XEVNT_OK)
509
* Discard the message if the host name length
510
* is unreasonable or the signature digest NID
513
temp32 = (fstamp >> 16) & 0xffff;
515
(const EVP_MD *)EVP_get_digestbynid(temp32);
516
if (vallen == 0 || vallen > MAXHOSTNAME)
520
if (rval != XEVNT_OK)
524
* Save status word, host name and message
525
* digest/signature type. If PC identity, be
526
* sure not to sign the certificate.
528
if (crypto_flags & CRYPTO_FLAG_PRIV)
529
fstamp |= CRYPTO_FLAG_SIGN;
530
peer->crypto = fstamp;
532
peer->subject = emalloc(vallen + 1);
533
memcpy(peer->subject, ep->pkt, vallen);
534
peer->subject[vallen] = '\0';
535
peer->issuer = emalloc(vallen + 1);
536
strcpy(peer->issuer, peer->subject);
537
temp32 = (fstamp >> 16) & 0xffff;
539
"flags 0x%x host %s signature %s", fstamp,
540
peer->subject, OBJ_nid2ln(temp32));
541
record_crypto_stats(&peer->srcadr, statstr);
544
printf("crypto_recv: %s\n", statstr);
549
* Decode X509 certificate in ASN.1 format and extract
550
* the data containing, among other things, subject
551
* name and public key. In the default identification
552
* scheme, the certificate trail is followed to a self
553
* signed trusted certificate.
555
case CRYPTO_CERT | CRYPTO_RESP:
558
* Discard the message if invalid or identity
561
if (peer->crypto & CRYPTO_FLAG_VRFY)
564
if ((rval = crypto_verify(ep, NULL, peer)) !=
569
* Scan the certificate list to delete old
570
* versions and link the newest version first on
573
if ((rval = cert_install(ep, peer)) != XEVNT_OK)
577
* If we snatch the certificate before the
578
* server certificate has been signed by its
579
* server, it will be self signed. When it is,
580
* we chase the certificate issuer, which the
581
* server has, and keep going until a self
582
* signed trusted certificate is found. Be sure
583
* to update the issuer field, since it may
586
if (peer->issuer != NULL)
588
peer->issuer = emalloc(strlen(cinfo->issuer) +
590
strcpy(peer->issuer, cinfo->issuer);
593
* We plug in the public key and group key in
594
* the first certificate received. However, note
595
* that this certificate might not be signed by
596
* the server, so we can't check the
597
* signature/digest NID.
599
if (peer->pkey == NULL) {
600
ptr = (u_char *)cinfo->cert.ptr;
601
cert = d2i_X509(NULL, &ptr,
602
ntohl(cinfo->cert.vallen));
603
peer->pkey = X509_get_pubkey(cert);
606
peer->flash &= ~TEST10;
608
sprintf(statstr, "cert %s 0x%x %s (%u) fs %u",
609
cinfo->subject, cinfo->flags,
610
OBJ_nid2ln(temp32), temp32,
612
record_crypto_stats(&peer->srcadr, statstr);
615
printf("crypto_recv: %s\n", statstr);
620
* Schnorr (IFF)identity scheme. This scheme is designed
621
* for use with shared secret group keys and where the
622
* certificate may be generated by a third party. The
623
* client sends a challenge to the server, which
624
* performs a calculation and returns the result. A
625
* positive result is possible only if both client and
626
* server contain the same secret group key.
628
case CRYPTO_IFF | CRYPTO_RESP:
631
* Discard the message if invalid or identity
634
if (peer->crypto & CRYPTO_FLAG_VRFY)
637
if ((rval = crypto_verify(ep, NULL, peer)) !=
642
* If the the challenge matches the response,
643
* the certificate public key, as well as the
644
* server public key, signatyre and identity are
645
* all verified at the same time. The server is
646
* declared trusted, so we skip further
647
* certificate stages and move immediately to
650
if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
653
peer->crypto |= CRYPTO_FLAG_VRFY |
655
peer->flash &= ~TEST10;
656
sprintf(statstr, "iff fs %u",
658
record_crypto_stats(&peer->srcadr, statstr);
661
printf("crypto_recv: %s\n", statstr);
666
* Guillou-Quisquater (GQ) identity scheme. This scheme
667
* is designed for use with public certificates carrying
668
* the GQ public key in an extension field. The client
669
* sends a challenge to the server, which performs a
670
* calculation and returns the result. A positive result
671
* is possible only if both client and server contain
672
* the same group key and the server has the matching GQ
675
case CRYPTO_GQ | CRYPTO_RESP:
678
* Discard the message if invalid or identity
681
if (peer->crypto & CRYPTO_FLAG_VRFY)
684
if ((rval = crypto_verify(ep, NULL, peer)) !=
689
* If the the challenge matches the response,
690
* the certificate public key, as well as the
691
* server public key, signatyre and identity are
692
* all verified at the same time. The server is
693
* declared trusted, so we skip further
694
* certificate stages and move immediately to
697
if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
700
peer->crypto |= CRYPTO_FLAG_VRFY |
702
peer->flash &= ~TEST10;
703
sprintf(statstr, "gq fs %u",
705
record_crypto_stats(&peer->srcadr, statstr);
708
printf("crypto_recv: %s\n", statstr);
715
case CRYPTO_MV | CRYPTO_RESP:
718
* Discard the message if invalid or identity
721
if (peer->crypto & CRYPTO_FLAG_VRFY)
724
if ((rval = crypto_verify(ep, NULL, peer)) !=
729
* If the the challenge matches the response,
730
* the certificate public key, as well as the
731
* server public key, signatyre and identity are
732
* all verified at the same time. The server is
733
* declared trusted, so we skip further
734
* certificate stages and move immediately to
737
if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
740
peer->crypto |= CRYPTO_FLAG_VRFY |
742
peer->flash &= ~TEST10;
743
sprintf(statstr, "mv fs %u",
745
record_crypto_stats(&peer->srcadr, statstr);
748
printf("crypto_recv: %s\n", statstr);
753
* X509 certificate sign response. Validate the
754
* certificate signed by the server and install. Later
755
* this can be provided to clients of this server in
756
* lieu of the self signed certificate in order to
757
* validate the public key.
759
case CRYPTO_SIGN | CRYPTO_RESP:
762
* Discard the message if invalid or identity
765
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
768
if ((rval = crypto_verify(ep, NULL, peer)) !=
773
* Scan the certificate list to delete old
774
* versions and link the newest version first on
777
if ((rval = cert_install(ep, peer)) != XEVNT_OK) break;
779
peer->crypto |= CRYPTO_FLAG_SIGN;
780
peer->flash &= ~TEST10;
782
sprintf(statstr, "sign %s 0x%x %s (%u) fs %u",
783
cinfo->issuer, cinfo->flags,
784
OBJ_nid2ln(temp32), temp32,
786
record_crypto_stats(&peer->srcadr, statstr);
789
printf("crypto_recv: %s\n", statstr);
794
* Cookie request in symmetric modes. Roll a random
795
* cookie and install in symmetric mode. Encrypt for the
796
* response, which is transmitted later.
801
* Discard the message if invalid or identity
804
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
807
if ((rval = crypto_verify(ep, NULL, peer)) !=
812
* Pass the extension field to the transmit
813
* side. If already agreed, walk away.
817
temp32 = CRYPTO_RESP;
818
fp->opcode |= htonl(temp32);
820
if (peer->crypto & CRYPTO_FLAG_AGREE) {
821
peer->flash &= ~TEST10;
826
* Install cookie values and light the cookie
827
* bit. The transmit side will pick up and
828
* encrypt it for the response.
831
peer->cookval.tstamp = ep->tstamp;
832
peer->cookval.fstamp = ep->fstamp;
833
RAND_bytes((u_char *)&peer->pcookie, 4);
834
peer->crypto &= ~CRYPTO_FLAG_AUTO;
835
peer->crypto |= CRYPTO_FLAG_AGREE;
836
peer->flash &= ~TEST10;
837
sprintf(statstr, "cook %x ts %u fs %u",
838
peer->pcookie, ntohl(ep->tstamp),
840
record_crypto_stats(&peer->srcadr, statstr);
843
printf("crypto_recv: %s\n", statstr);
848
* Cookie response in client and symmetric modes. If the
849
* cookie bit is set, the working cookie is the EXOR of
850
* the current and new values.
852
case CRYPTO_COOK | CRYPTO_RESP:
855
* Discard the message if invalid or identity
856
* not confirmed or signature not verified with
857
* respect to the cookie values.
859
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
862
if ((rval = crypto_verify(ep, &peer->cookval,
867
* Decrypt the cookie, hunting all the time for
870
if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
871
RSA_private_decrypt(vallen,
875
RSA_PKCS1_OAEP_PADDING);
876
cookie = ntohl(temp32);
390
if (ntohl(pkt[i + 1]) != 0)
391
peer->assoc = ntohl(pkt[i + 1]);
883
* Install cookie values and light the cookie
884
* bit. If this is not broadcast client mode, we
888
peer->cookval.tstamp = ep->tstamp;
889
peer->cookval.fstamp = ep->fstamp;
890
if (peer->crypto & CRYPTO_FLAG_AGREE)
891
peer->pcookie ^= cookie;
893
peer->pcookie = cookie;
894
if (peer->hmode == MODE_CLIENT &&
895
!(peer->cast_flags & MDF_BCLNT))
896
peer->crypto |= CRYPTO_FLAG_AUTO;
898
peer->crypto &= ~CRYPTO_FLAG_AUTO;
899
peer->crypto |= CRYPTO_FLAG_AGREE;
900
peer->flash &= ~TEST10;
901
sprintf(statstr, "cook %x ts %u fs %u",
902
peer->pcookie, ntohl(ep->tstamp),
904
record_crypto_stats(&peer->srcadr, statstr);
397
"crypto_recv: verify %d flags 0x%x ts %u\n",
907
printf("crypto_recv: %s\n", statstr);
403
912
* Install autokey values in broadcast client and
913
* symmetric modes. We have to do this every time the
914
* sever/peer cookie changes or a new keylist is
915
* rolled. Ordinarily, this is automatic as this message
916
* is piggybacked on the first NTP packet sent upon
917
* either of these events. Note that a broadcast client
918
* or symmetric peer can receive this response without a
406
921
case CRYPTO_AUTO | CRYPTO_RESP:
407
if (!(peer->flags & FLAG_AUTOKEY) &&
408
ntohl(pkt[i + 1]) != 0)
409
peer->assoc = ntohl(pkt[i + 1]);
410
ap = (struct autokey *)&pkt[i + 2];
412
temp = ntohl(ap->siglen);
413
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
414
if (len < AUTOKEY_LEN) {
416
} else if (tstamp == 0 || tstamp <
417
peer->recauto.tstamp || (tstamp ==
418
peer->recauto.tstamp && (peer->flags &
421
} else if (!crypto_flags) {
423
} else if (kp == NULL) {
425
} else if (temp != kp->bits / 8) {
428
EVP_VerifyInit(&ctx, DA_MD5);
429
EVP_VerifyUpdate(&ctx, (u_char *)ap,
431
rval = EVP_VerifyFinal(&ctx,
432
(u_char *)ap->pkt, temp, kp);
435
if (tstamp < peer->recauto.tstamp || (tstamp ==
436
peer->recauto.tstamp && (peer->flags &
445
"crypto_recv: verify %x autokey %d %08x ts %u (%u)\n",
446
rval, ntohl(ap->seq),
447
ntohl(ap->key), tstamp,
448
peer->recauto.tstamp);
453
"crypto: %x autokey %d %08x ts %u (%u)\n",
454
rval, ntohl(ap->seq),
455
ntohl(ap->key), tstamp,
456
peer->recauto.tstamp);
459
peer->flags |= FLAG_AUTOKEY;
460
peer->flash &= ~TEST10;
461
peer->assoc = ntohl(pkt[i + 1]);
462
peer->recauto.tstamp = tstamp;
463
peer->recauto.seq = ntohl(ap->seq);
464
peer->recauto.key = ntohl(ap->key);
465
peer->pkeyid = peer->recauto.key;
469
* Install session cookie in client mode. Use this also
470
* in symmetric modes for test when rsaref20 has not
474
peer->cmmd = ntohl(pkt[i]);
477
case CRYPTO_PRIV | CRYPTO_RESP:
478
cp = (struct cookie *)&pkt[i + 2];
480
temp = ntohl(cp->siglen);
481
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
482
if (len < COOKIE_LEN) {
484
} else if (tstamp == 0 || tstamp <
485
peer->pcookie.tstamp || (tstamp ==
486
peer->pcookie.tstamp && (peer->flags &
489
} else if (!crypto_flags) {
491
} else if (kp == NULL) {
493
} else if (temp != kp->bits / 8) {
496
EVP_VerifyInit(&ctx, DA_MD5);
497
EVP_VerifyUpdate(&ctx, (u_char *)cp, 8);
498
rval = EVP_VerifyFinal(&ctx,
499
(u_char *)cp->pkt, temp, kp);
502
if (tstamp <= peer->pcookie.tstamp || (tstamp ==
503
peer->pcookie.tstamp && (peer->flags &
511
* Tricky here. If in client mode, use the
512
* server cookie; otherwise, use EXOR of both
513
* peer cookies. We call this Daffy-Hooligan
516
if (peer->hmode == MODE_CLIENT)
517
temp = ntohl(cp->key);
519
temp = ntohl(cp->key) ^ peer->hcookie;
523
"crypto_recv: verify %x cookie %08x ts %u (%u)\n",
525
peer->pcookie.tstamp);
530
"crypto: %x cookie %08x ts %u (%u)\n",
532
peer->pcookie.tstamp);
533
peer->cmmd |= CRYPTO_ERROR;
536
if (!(peer->cast_flags & MDF_BCLNT))
537
peer->flags |= FLAG_AUTOKEY;
538
peer->flash &= ~TEST10;
539
peer->assoc = ntohl(pkt[i + 1]);
540
peer->pcookie.tstamp = tstamp;
541
if (temp != peer->pcookie.key) {
542
peer->pcookie.key = temp;
548
* The following commands and responses work only when
549
* public-key cryptography has been configured. If
550
* configured, but disabled due to no crypto command in
551
* the configuration file, they are ignored.
555
* Install public key and host name.
557
case CRYPTO_NAME | CRYPTO_RESP:
560
vp = (struct value *)&pkt[i + 2];
561
fstamp = ntohl(vp->fstamp);
562
temp = ntohl(vp->vallen);
563
j = i + 5 + ntohl(vp->vallen) / 4;
564
bits = ntohl(pkt[i + 5]);
565
if (len < VALUE_LEN) {
567
} else if (temp < rsalen || bits <
568
MIN_RSA_MODULUS_BITS || bits >
569
MAX_RSA_MODULUS_BITS) {
571
} else if (ntohl(pkt[j]) != bits / 8) {
573
} else if (tstamp == 0 || tstamp <
574
peer->pubkey.tstamp || (tstamp ==
575
peer->pubkey.tstamp && (peer->flags &
578
} else if (tstamp < peer->pubkey.fstamp ||
579
fstamp < peer->pubkey.fstamp) {
581
} else if (fstamp == peer->pubkey.fstamp &&
582
(peer->flags & FLAG_AUTOKEY)) {
585
EVP_VerifyInit(&ctx, DA_MD5);
586
EVP_VerifyUpdate(&ctx, (u_char *)vp,
588
kp = emalloc(sizeof(R_RSA_PUBLIC_KEY));
590
memcpy(kp->modulus, &pkt[i + 6],
592
rval = EVP_VerifyFinal(&ctx,
593
(u_char *)&pkt[j + 1],
598
j = i + 5 + rsalen / 4;
599
peer->pubkey.ptr = (u_char *)kp;
600
temp = strlen((char *)&pkt[j]);
601
peer->keystr = emalloc(temp +
605
peer->pubkey.tstamp = tstamp;
606
peer->pubkey.fstamp = fstamp;
607
peer->flash &= ~TEST10;
618
"crypto_recv: verify %x host %s ts %u fs %u\n",
619
rval, (char *)&pkt[i + 5 + rsalen /
625
"crypto: %x host %s ts %u fs %u\n",
626
rval, (char *)&pkt[i + 5 +
633
* Install certificate.
635
case CRYPTO_CERT | CRYPTO_RESP:
638
vp = (struct value *)&pkt[i + 2];
639
fstamp = ntohl(vp->fstamp);
640
temp = ntohl(vp->vallen);
641
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
642
j = i + 5 + temp / 4;
643
if (len < VALUE_LEN) {
645
} else if (kp == NULL) {
647
} else if (ntohl(pkt[j]) != kp->bits / 8) {
649
} else if (tstamp == 0) {
652
ntohl(peer->certif.fstamp) || fstamp <
653
ntohl(peer->certif.fstamp)) {
656
ntohl(peer->certif.fstamp) && (peer->flags &
658
peer->crypto &= ~CRYPTO_FLAG_CERT;
661
EVP_VerifyInit(&ctx, DA_MD5);
662
EVP_VerifyUpdate(&ctx, (u_char *)vp,
664
rval = EVP_VerifyFinal(&ctx,
665
(u_char *)&pkt[j + 1],
671
"crypto_recv: verify %x certificate %u ts %u fs %u\n",
672
rval, temp, tstamp, fstamp);
676
* If the peer data are newer than the host
677
* data, replace the host data. Otherwise,
678
* wait for the peer to fetch the host data.
680
if (rval != RV_OK || temp == 0) {
683
"crypto: %x certificate %u ts %u fs %u\n",
684
rval, temp, tstamp, fstamp);
687
peer->flash &= ~TEST10;
688
peer->flags |= FLAG_PROVEN;
689
peer->crypto &= ~CRYPTO_FLAG_CERT;
692
* Initialize agreement parameters and extension
693
* field in network byte order. Note the private
694
* key length is set arbitrarily at half the
697
peer->certif.tstamp = vp->tstamp;
698
peer->certif.fstamp = vp->fstamp;
699
peer->certif.vallen = vp->vallen;
700
if (peer->certif.ptr == NULL)
701
free(peer->certif.ptr);
702
peer->certif.ptr = emalloc(temp);
703
memcpy(peer->certif.ptr, vp->pkt, temp);
708
* Install agreement parameters in symmetric modes.
710
case CRYPTO_DHPAR | CRYPTO_RESP:
713
vp = (struct value *)&pkt[i + 2];
714
fstamp = ntohl(vp->fstamp);
715
temp = ntohl(vp->vallen);
716
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
717
j = i + 5 + temp / 4;
718
if (len < VALUE_LEN) {
720
} else if (kp == NULL) {
722
} else if (ntohl(pkt[j]) != kp->bits / 8) {
724
} else if (tstamp == 0) {
726
} else if (tstamp < ntohl(dhparam.fstamp) ||
727
fstamp < ntohl(dhparam.fstamp)) {
729
} else if (fstamp == ntohl(dhparam.fstamp) &&
730
(peer->flags & FLAG_AUTOKEY)) {
731
peer->crypto &= ~CRYPTO_FLAG_DH;
734
EVP_VerifyInit(&ctx, DA_MD5);
735
EVP_VerifyUpdate(&ctx, (u_char *)vp,
737
rval = EVP_VerifyFinal(&ctx,
738
(u_char *)&pkt[j + 1],
744
"crypto_recv: verify %x parameters %u ts %u fs %u\n",
745
rval, temp, tstamp, fstamp);
749
* If the peer data are newer than the host
750
* data, replace the host data. Otherwise,
751
* wait for the peer to fetch the host data.
753
if (rval != RV_OK || temp == 0) {
756
"crypto: %x parameters %u ts %u fs %u\n",
757
rval, temp, tstamp, fstamp);
760
peer->flash &= ~TEST10;
761
crypto_flags |= CRYPTO_FLAG_DH;
762
peer->crypto &= ~CRYPTO_FLAG_DH;
765
* Initialize agreement parameters and extension
766
* field in network byte order. Note the private
767
* key length is set arbitrarily at half the
770
dhparam.tstamp = vp->tstamp;
771
dhparam.fstamp = vp->fstamp;
772
dhparam.vallen = vp->vallen;
773
if (dhparam.ptr != NULL)
776
dhparam.ptr = (u_char *)pp;
777
memcpy(pp, vp->pkt, temp);
778
dh_params.primeLen = ntohl(*pp++);
779
dh_params.prime = (u_char *)pp;
780
pp += dh_params.primeLen / 4;
781
dh_params.generatorLen = ntohl(*pp++);
782
dh_params.generator = (u_char *)pp;
783
dh_keyLen = dh_params.primeLen / 2;
784
if (dh_private != NULL)
786
dh_private = emalloc(dh_keyLen);
787
if (dhparam.sig == NULL)
788
dhparam.sig = emalloc(private_key.bits /
792
* Initialize public value extension field.
794
dhpub.tstamp = vp->tstamp;
795
dhpub.fstamp = vp->fstamp;
796
dhpub.vallen = htonl(dh_params.primeLen);
797
if (dhpub.ptr != NULL)
799
dhpub.ptr = emalloc(dh_params.primeLen);
800
if (dhpub.sig == NULL)
801
dhpub.sig = emalloc(private_key.bits /
807
* Verify public value and compute agreed key in
811
peer->cmmd = ntohl(pkt[i]);
813
peer->cmmd |= CRYPTO_ERROR;
816
case CRYPTO_DH | CRYPTO_RESP:
819
vp = (struct value *)&pkt[i + 2];
820
fstamp = ntohl(vp->fstamp);
821
temp = ntohl(vp->vallen);
822
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
823
j = i + 5 + temp / 4;
824
if (len < VALUE_LEN) {
826
} else if (temp != dh_params.primeLen) {
828
} else if (kp == NULL) {
830
} else if (ntohl(pkt[j]) != kp->bits / 8) {
832
} else if (tstamp == 0 || tstamp <
833
peer->pcookie.tstamp || (tstamp ==
834
peer->pcookie.tstamp && (peer->flags &
838
EVP_VerifyInit(&ctx, DA_MD5);
839
EVP_VerifyUpdate(&ctx, (u_char *)vp,
841
rval = EVP_VerifyFinal(&ctx,
842
(u_char *)&pkt[j + 1],
847
* Run the agreement algorithm and stash the key
848
* value. We use only the first u_int32 for the
849
* host cookie. Wasteful. If the association ID
850
* is zero, the other guy hasn't seen us as
851
* synchronized, in which case both of us should
852
* be using a zero cookie.
856
} else if (fstamp > dhparam.fstamp) {
857
crypto_flags &= ~CRYPTO_FLAG_DH;
860
rval = R_ComputeDHAgreedKey(dh_key,
861
(u_char *)&pkt[i + 5], dh_private,
862
dh_keyLen, &dh_params);
863
temp = ntohl(*(u_int32 *)dh_key);
868
"crypto_recv: verify %x agreement %08x ts %u (%u) fs %u\n",
870
peer->pcookie.tstamp, fstamp);
875
"crypto: %x agreement %08x ts %u (%u) fs %u\n",
877
peer->pcookie.tstamp,
879
peer->cmmd |= CRYPTO_ERROR;
882
peer->flash &= ~TEST10;
883
peer->flags &= ~FLAG_AUTOKEY;
884
peer->assoc = ntohl(pkt[i + 1]);
885
peer->pcookie.tstamp = tstamp;
886
if (temp != peer->pcookie.key) {
887
peer->pcookie.key = temp;
893
* Install leapseconds table.
924
* Discard the message if invalid or identity
925
* not confirmed or signature not verified with
926
* respect to the receive autokey values.
928
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
931
if ((rval = crypto_verify(ep, &peer->recval,
936
* Install autokey values and light the
937
* autokey bit. This is not hard.
939
if (peer->recval.ptr == NULL)
941
emalloc(sizeof(struct autokey));
942
bp = (struct autokey *)peer->recval.ptr;
943
peer->recval.tstamp = ep->tstamp;
944
peer->recval.fstamp = ep->fstamp;
945
ap = (struct autokey *)ep->pkt;
946
bp->seq = ntohl(ap->seq);
947
bp->key = ntohl(ap->key);
948
peer->pkeyid = bp->key;
949
peer->crypto |= CRYPTO_FLAG_AUTO;
950
peer->flash &= ~TEST10;
952
"auto seq %d key %x ts %u fs %u", bp->seq,
953
bp->key, ntohl(ep->tstamp),
955
record_crypto_stats(&peer->srcadr, statstr);
958
printf("crypto_recv: %s\n", statstr);
963
* Install leapseconds table in symmetric modes. This
964
* table is proventicated to the NIST primary servers,
965
* either by copying the file containing the table from
966
* a NIST server to a trusted server or directly using
967
* this protocol. While the entire table is installed at
968
* the server, presently only the current TAI offset is
969
* provided via the kernel to other applications.
974
* Discard the message if invalid or identity
977
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
980
if ((rval = crypto_verify(ep, NULL, peer)) !=
985
* Pass the extension field to the transmit
986
* side. Continue below if a leapseconds table
987
* accompanies the message.
991
temp32 = CRYPTO_RESP;
992
fp->opcode |= htonl(temp32);
994
if (len <= VALUE_LEN) {
995
peer->flash &= ~TEST10;
895
1000
case CRYPTO_TAI | CRYPTO_RESP:
898
vp = (struct value *)&pkt[i + 2];
899
fstamp = ntohl(vp->fstamp);
900
temp = ntohl(vp->vallen);
901
kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
902
j = i + 5 + temp / 4;
903
if (len < VALUE_LEN) {
907
} else if (ntohl(pkt[j]) != kp->bits / 8) {
909
} else if (tstamp == 0) {
911
} else if (tstamp < ntohl(tai_leap.fstamp) ||
912
fstamp < ntohl(tai_leap.fstamp)) {
914
} else if (fstamp == ntohl(tai_leap.fstamp) &&
915
(peer->flags & FLAG_AUTOKEY)) {
916
peer->crypto &= ~CRYPTO_FLAG_TAI;
919
EVP_VerifyInit(&ctx, DA_MD5);
920
EVP_VerifyUpdate(&ctx, (u_char *)vp,
922
rval = EVP_VerifyFinal(&ctx,
923
(u_char *)&pkt[j + 1],
929
"crypto_recv: verify %x leapseconds %u ts %u fs %u\n",
930
rval, temp, tstamp, fstamp);
934
* If the peer data are newer than the host
935
* data, replace the host data. Otherwise,
936
* wait for the peer to fetch the host data.
938
if (rval != RV_OK || temp == 0) {
941
"crypto: %x leapseconds %u ts %u fs %u\n",
942
rval, temp, tstamp, fstamp);
945
peer->flash &= ~TEST10;
1003
* Discard the message if invalid or identity
1004
* not confirmed or signature not verified with
1005
* respect to the leapsecond table values.
1007
if (!(peer->crypto & CRYPTO_FLAG_VRFY))
1010
if ((rval = crypto_verify(ep, &peer->tai_leap,
1015
* Initialize peer variables, leapseconds
1016
* structure and extension field in network byte
1017
* order. Since a filestamp may have changed,
1018
* recompute the signatures.
1020
peer->tai_leap.tstamp = ep->tstamp;
1021
peer->tai_leap.fstamp = ep->fstamp;
1022
peer->tai_leap.vallen = ep->vallen;
1025
* Install the new table if there is no stored
1026
* table or the new table is more recent than
1027
* the stored table. Since a filestamp may have
1028
* changed, recompute the signatures.
1030
if (ntohl(peer->tai_leap.fstamp) >
1031
ntohl(tai_leap.fstamp)) {
1032
tai_leap.fstamp = ep->fstamp;
1033
tai_leap.vallen = ep->vallen;
1034
if (tai_leap.ptr != NULL)
1036
tai_leap.ptr = emalloc(vallen);
1037
memcpy(tai_leap.ptr, ep->pkt, vallen);
1039
sys_tai = vallen / 4 + TAI_1972 - 1;
946
1041
crypto_flags |= CRYPTO_FLAG_TAI;
947
peer->crypto &= ~CRYPTO_FLAG_TAI;
948
sys_tai = temp / 4 + TAI_1972 - 1;
1042
peer->crypto |= CRYPTO_FLAG_LEAP;
1043
peer->flash &= ~TEST10;
949
1044
#ifdef KERNEL_PLL
1047
* If the kernel cooperates, initialize the
1048
* current TAI offset.
951
1050
ntv.modes = MOD_TAI;
952
1051
ntv.constant = sys_tai;
953
if (ntp_adjtime(&ntv) == TIME_ERROR)
955
"kernel TAI update failed");
1052
(void)ntp_adjtime(&ntv);
956
1053
#endif /* NTP_API */
957
1054
#endif /* KERNEL_PLL */
960
* Initialize leapseconds table and extension
961
* field in network byte order.
963
tai_leap.tstamp = vp->tstamp;
964
tai_leap.fstamp = vp->fstamp;
965
tai_leap.vallen = vp->vallen;
966
if (tai_leap.ptr == NULL)
968
tai_leap.ptr = emalloc(temp);
969
memcpy(tai_leap.ptr, vp->pkt, temp);
970
if (tai_leap.sig == NULL)
972
emalloc(private_key.bits / 8);
1055
sprintf(statstr, "leap %u ts %u fs %u",
1056
vallen, ntohl(ep->tstamp),
1058
record_crypto_stats(&peer->srcadr, statstr);
1061
printf("crypto_recv: %s\n", statstr);
978
* For other requests, save the request code for later;
979
* for unknown responses or errors, just ignore for now.
1066
* We come here in symmetric modes for miscellaneous
1067
* commands that have value fields but are processed on
1068
* the transmit side. All we need do here is check for
1069
* valid field length. Remaining checks are below and on
1070
* the transmit side.
1076
if (len < VALUE_LEN) {
1084
* We come here for miscellaneous requests and unknown
1085
* requests and responses. If an unknown response or
1086
* error, forget it. If a request, save the extension
1087
* field for later. Unknown requests will be caught on
1088
* the transmit side.
982
if (code & (CRYPTO_RESP | CRYPTO_ERROR))
984
peer->cmmd = ntohl(pkt[i]);
1091
if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1093
} else if ((rval = crypto_verify(ep, NULL,
1094
peer)) == XEVNT_OK) {
1096
memcpy(fp, ep, len);
1097
temp32 = CRYPTO_RESP;
1098
fp->opcode |= htonl(temp32);
1104
* We don't log length/format/timestamp errors and
1105
* duplicates, which are log clogging vulnerabilities.
1106
* The first error found terminates the extension field
1107
* scan and we return the laundry to the caller. A
1108
* length/format/timestamp error on transmit is
1109
* cheerfully ignored, as the message is not sent.
1111
if (rval > XEVNT_TSP) {
1113
"error %x opcode %x ts %u fs %u", rval,
1114
code, tstamp, fstamp);
1115
record_crypto_stats(&peer->srcadr, statstr);
1116
report_event(rval, peer);
1119
printf("crypto_recv: %s\n", statstr);
1122
} else if (rval > XEVNT_OK && (code & CRYPTO_RESP)) {
1252
1379
if (opcode & CRYPTO_RESP)
1253
1380
opcode |= CRYPTO_ERROR;
1258
* Round up the field length to a multiple of 8 octets and save
1384
* We ignore length/format errors and duplicates. Other errors
1385
* are reported to the log and deny further service. To really
1386
* persistent rascals we toss back a kiss-of-death grenade.
1388
if (rval > XEVNT_TSP) {
1389
opcode |= CRYPTO_ERROR;
1390
sprintf(statstr, "error %x opcode %x", rval, opcode);
1391
record_crypto_stats(srcadr_sin, statstr);
1394
printf("crypto_xmit: %s\n", statstr);
1399
* Round up the field length to a multiple of 8 bytes and save
1259
1400
* the request code and length.
1261
1402
len = ((len + 7) / 8) * 8;
1263
xpkt[i] = htonl((u_int32)((opcode << 16) | len));
1267
"crypto_xmit: ext offset %d len %d code %x assocID %d\n",
1268
start, len, code, associd);
1276
* crypto_setup - load private key, public key, optional agreement
1277
* parameters and optional leapseconds table, then initialize extension
1278
* fields for later signatures.
1283
char filename[MAXFILENAME];
1284
u_int fstamp; /* filestamp */
1289
* Initialize structures.
1291
memset(&private_key, 0, sizeof(private_key));
1292
memset(&public_key, 0, sizeof(public_key));
1293
memset(&certif, 0, sizeof(certif));
1294
memset(&dh_params, 0, sizeof(dh_params));
1295
memset(&host, 0, sizeof(host));
1296
memset(&dhparam, 0, sizeof(dhparam));
1297
memset(&dhpub, 0, sizeof(dhpub));
1298
memset(&tai_leap, 0, sizeof(tai_leap));
1303
* Load required private key from file, default "ntpkey".
1305
if (private_key_file == NULL)
1306
private_key_file = "ntpkey";
1307
host.fstamp = htonl(crypto_rsa(private_key_file,
1308
(u_char *)&private_key, sizeof(R_RSA_PRIVATE_KEY)));
1311
* Load required public key from file, default
1312
* "ntpkey_host", where "host" is the canonical name of this
1315
if (public_key_file == NULL) {
1316
snprintf(filename, MAXFILENAME, "ntpkey_%s",
1318
public_key_file = emalloc(strlen(filename) + 1);
1319
strcpy(public_key_file, filename);
1321
fstamp = htonl(crypto_rsa(public_key_file,
1322
(u_char *)&public_key, sizeof(R_RSA_PUBLIC_KEY)));
1323
if (fstamp != host.fstamp || strstr(public_key_file,
1324
sys_hostname) == NULL) {
1326
"crypto: public/private key files mismatch");
1329
crypto_flags |= CRYPTO_FLAG_RSA;
1332
* Assemble public key and host name in network byte order.
1333
* These data will later be signed and sent in response to
1334
* a client request. Note that the modulus must be a u_int32 in
1335
* network byte order independent of the host order or u_int
1338
strcpy(filename, sys_hostname);
1339
for (len = strlen(filename) + 1; len % 4 != 0; len++)
1340
filename[len - 1] = 0;
1341
temp = sizeof(R_RSA_PUBLIC_KEY) - sizeof(u_int) + 4;
1342
host.vallen = htonl(temp + len);
1343
pp = emalloc(temp + len);
1344
host.ptr = (u_char *)pp;
1345
*pp++ = htonl(public_key.bits);
1346
memcpy(pp--, public_key.modulus, temp - 4);
1348
memcpy(pp, filename, len);
1349
host.sig = emalloc(private_key.bits / 8);
1352
* Load optional certificate from file, default "ntpkey_certif".
1353
* If the file is missing or defective, the values can later be
1354
* retrieved from a server.
1356
if (certif_file == NULL)
1357
snprintf(filename, MAXFILENAME, "ntpkey_certif_%s",
1359
certif_file = emalloc(strlen(filename) + 1);
1360
strcpy(certif_file, filename);
1361
crypto_cert(certif_file);
1364
* Load optional agreement parameters from file, default
1365
* "ntpkey_dh". If the file is missing or defective, the values
1366
* can later be retrieved from a server.
1368
if (dh_params_file == NULL)
1369
dh_params_file = "ntpkey_dh";
1370
crypto_dh(dh_params_file);
1373
* Load optional leapseconds from file, default "ntpkey_leap".
1374
* If the file is missing or defective, the values can later be
1375
* retrieved from a server.
1377
if (tai_leap_file == NULL)
1378
tai_leap_file = "ntpkey_leap";
1379
crypto_tai(tai_leap_file);
1384
* crypto_agree - compute new public value and sign extension fields.
1389
R_RANDOM_STRUCT randomstr; /* wiggle bits */
1390
R_SIGNATURE_CTX ctx; /* signature context */
1391
l_fp lstamp; /* NTP time */
1392
tstamp_t tstamp; /* seconds timestamp */
1397
* Sign host name and timestamps, but only if the clock is
1400
if (sys_leap == LEAP_NOTINSYNC)
1402
get_systime(&lstamp);
1403
tstamp = lstamp.l_ui;
1404
host.tstamp = htonl(tstamp);
1407
EVP_SignInit(&ctx, DA_MD5);
1408
EVP_SignUpdate(&ctx, (u_char *)&host, 12);
1409
EVP_SignUpdate(&ctx, host.ptr, ntohl(host.vallen));
1410
rval = EVP_SignFinal(&ctx, host.sig, &len, &private_key);
1411
if (rval != RV_OK || len != private_key.bits / 8) {
1412
msyslog(LOG_ERR, "crypto: host signature fails %x",
1416
host.siglen = ntohl(len);
1419
* Sign certificate and timestamps.
1421
if (certif.vallen != 0) {
1422
certif.tstamp = htonl(tstamp);
1423
EVP_SignInit(&ctx, DA_MD5);
1424
EVP_SignUpdate(&ctx, (u_char *)&certif, 12);
1425
EVP_SignUpdate(&ctx, certif.ptr,
1426
ntohl(certif.vallen));
1427
rval = EVP_SignFinal(&ctx, certif.sig, &len,
1429
if (rval != RV_OK || len != private_key.bits / 8) {
1431
"crypto: certificate signature fails %x",
1435
certif.siglen = ntohl(len);
1439
* Sign agreement parameters and timestamps.
1441
if (dhparam.vallen != 0) {
1442
dhparam.tstamp = htonl(tstamp);
1443
EVP_SignInit(&ctx, DA_MD5);
1444
EVP_SignUpdate(&ctx, (u_char *)&dhparam, 12);
1445
EVP_SignUpdate(&ctx, dhparam.ptr,
1446
ntohl(dhparam.vallen));
1447
rval = EVP_SignFinal(&ctx, dhparam.sig, &len,
1449
if (rval != RV_OK || len != private_key.bits / 8) {
1451
"crypto: parameters signature fails %x",
1455
dhparam.siglen = ntohl(len);
1458
* Compute public value.
1460
R_RandomInit(&randomstr);
1461
R_GetRandomBytesNeeded(&len, &randomstr);
1462
for (i = 0; i < len; i++) {
1464
R_RandomUpdate(&randomstr, (u_char *)&temp, 1);
1466
rval = R_SetupDHAgreement(dhpub.ptr, dh_private,
1467
dh_keyLen, &dh_params, &randomstr);
1468
if (rval != RV_OK) {
1470
"crypto: invalid public value");
1475
* Sign public value and timestamps.
1477
dhpub.tstamp = htonl(tstamp);
1478
EVP_SignInit(&ctx, DA_MD5);
1479
EVP_SignUpdate(&ctx, (u_char *)&dhpub, 12);
1480
EVP_SignUpdate(&ctx, dhpub.ptr, ntohl(dhpub.vallen));
1481
rval = EVP_SignFinal(&ctx, dhpub.sig, &len,
1483
if (rval != RV_OK || len != private_key.bits / 8) {
1485
"crypto: public value signature fails %x",
1489
dhpub.siglen = ntohl(len);
1493
* Sign leapseconds table and timestamps.
1403
fp->opcode = htonl((opcode & 0xffff0000) | len);
1407
"crypto_xmit: ext offset %d len %u code %x assocID %d\n",
1408
start, len, opcode>> 16, associd);
1415
* crypto_verify - parse and verify the extension field and value
1419
* XEVNT_LEN bad field format or length
1420
* XEVNT_TSP bad timestamp
1421
* XEVNT_FSP bad filestamp
1422
* XEVNT_PUB bad or missing public key
1423
* XEVNT_SGL bad signature length
1424
* XEVNT_SIG signature not verified
1428
struct exten *ep, /* extension pointer */
1429
struct value *vp, /* value pointer */
1430
struct peer *peer /* peer structure pointer */
1433
EVP_PKEY *pkey; /* server public key */
1434
EVP_MD_CTX ctx; /* signature context */
1435
tstamp_t tstamp; /* timestamp */
1436
tstamp_t fstamp; /* filestamp */
1437
u_int vallen; /* value length */
1438
u_int siglen; /* signature length */
1444
* We require valid opcode and field length, timestamp,
1445
* filestamp, public key, digest, signature length and
1446
* signature, where relevant. Note that preliminary length
1447
* checks are done in the main loop.
1449
len = ntohl(ep->opcode) & 0x0000ffff;
1450
opcode = ntohl(ep->opcode) & 0xffff0000;
1453
* Check for valid operation code and protocol. The opcode must
1454
* not have the error bit set. If a response, it must have a
1455
* value header. If a request and does not contain a value
1456
* header, no need for further checking.
1458
if (opcode & CRYPTO_ERROR)
1460
if (opcode & CRYPTO_RESP) {
1461
if (len < VALUE_LEN)
1464
if (len < VALUE_LEN)
1468
* We have a value header. Check for valid field lengths. The
1469
* field length must be long enough to contain the value header,
1470
* value and signature. If a request and a previous request of
1471
* the same type is pending, discard the previous request. If a
1472
* request but no signature, there is no need for further
1475
vallen = ntohl(ep->vallen);
1476
if (len < ((VALUE_LEN + vallen + 3) / 4) * 4)
1479
i = (vallen + 3) / 4;
1480
siglen = ntohl(ep->pkt[i++]);
1481
if (len < VALUE_LEN + vallen + siglen)
1484
if (!(opcode & CRYPTO_RESP)) {
1485
if (peer->cmmd != NULL) {
1486
if ((opcode | CRYPTO_RESP) ==
1487
(ntohl(peer->cmmd->opcode) & 0xffff0000)) {
1499
* We have a signature. Check for valid timestamp and filestamp.
1500
* The timestamp must not precede the filestamp. The timestamp
1501
* and filestamp must not precede the corresponding values in
1502
* the value structure. Once the autokey values have been
1503
* installed, the timestamp must always be later than the
1504
* corresponding value in the value structure. Duplicate
1505
* timestamps are illegal once the cookie has been validated.
1508
if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1512
tstamp = ntohl(ep->tstamp);
1513
fstamp = ntohl(ep->fstamp);
1514
if (tstamp == 0 || tstamp < fstamp) {
1516
} else if (vp != NULL && (tstamp < ntohl(vp->tstamp) ||
1517
(tstamp == ntohl(vp->tstamp) && (peer->crypto &
1518
CRYPTO_FLAG_AUTO)))) {
1520
} else if (vp != NULL && (tstamp < ntohl(vp->fstamp) || fstamp <
1521
ntohl(vp->fstamp))) {
1525
* If a public key and digest is present, and if valid key
1526
* length, check for valid signature. Note that the first valid
1527
* signature lights the proventic bit.
1529
} else if (pkey == NULL || peer->digest == NULL) {
1531
} else if (siglen != (u_int) EVP_PKEY_size(pkey)) {
1534
EVP_VerifyInit(&ctx, peer->digest);
1535
EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen +
1537
if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1539
if (peer->crypto & CRYPTO_FLAG_VRFY)
1540
peer->crypto |= CRYPTO_FLAG_PROV;
1548
"crypto_recv: verify %x vallen %u siglen %u ts %u fs %u\n",
1549
rval, vallen, siglen, tstamp, fstamp);
1556
* crypto_encrypt - construct encrypted cookie and signature from
1557
* extension field and cookie
1561
* XEVNT_PUB bad or missing public key
1562
* XEVNT_CKY bad or missing cookie
1566
struct exten *ep, /* extension pointer */
1567
struct value *vp, /* value pointer */
1568
keyid_t *cookie /* server cookie */
1571
EVP_PKEY *pkey; /* public key */
1572
EVP_MD_CTX ctx; /* signature context */
1573
tstamp_t tstamp; /* NTP timestamp */
1579
* Extract the public key from the request.
1581
len = ntohl(ep->vallen);
1582
ptr = (u_char *)ep->pkt;
1583
pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
1585
msyslog(LOG_ERR, "crypto_encrypt %s\n",
1586
ERR_error_string(ERR_get_error(), NULL));
1591
* Encrypt the cookie, encode in ASN.1 and sign.
1593
tstamp = crypto_time();
1594
memset(vp, 0, sizeof(struct value));
1595
vp->tstamp = htonl(tstamp);
1596
vp->fstamp = hostval.tstamp;
1597
len = EVP_PKEY_size(pkey);
1598
vp->vallen = htonl(len);
1599
vp->ptr = emalloc(len);
1600
temp32 = htonl(*cookie);
1601
if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr,
1602
pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) {
1603
msyslog(LOG_ERR, "crypto_encrypt %s\n",
1604
ERR_error_string(ERR_get_error(), NULL));
1605
EVP_PKEY_free(pkey);
1608
EVP_PKEY_free(pkey);
1612
vp->sig = emalloc(sign_siglen);
1613
EVP_SignInit(&ctx, sign_digest);
1614
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1615
EVP_SignUpdate(&ctx, vp->ptr, len);
1616
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
1617
vp->siglen = htonl(len);
1623
* crypto_ident - construct extension field for identity scheme
1625
* This routine determines which identity scheme is in use and
1626
* constructs an extension field for that scheme.
1630
struct peer *peer /* peer structure pointer */
1633
char filename[MAXFILENAME + 1];
1636
* If the server identity has already been verified, no further
1637
* action is necessary. Otherwise, try to load the identity file
1638
* of the certificate issuer. If the issuer file is not found,
1639
* try the host file. If nothing found, declare a cryptobust.
1640
* Note we can't get here unless the trusted certificate has
1641
* been found and the CRYPTO_FLAG_VALID bit is set, so the
1642
* certificate issuer is valid.
1644
if (peer->ident_pkey != NULL)
1645
EVP_PKEY_free(peer->ident_pkey);
1646
if (peer->crypto & CRYPTO_FLAG_GQ) {
1647
snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1649
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1650
if (peer->ident_pkey != NULL)
1653
snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1655
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1656
if (peer->ident_pkey != NULL)
1659
if (peer->crypto & CRYPTO_FLAG_IFF) {
1660
snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1662
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1663
if (peer->ident_pkey != NULL)
1664
return (CRYPTO_IFF);
1666
snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1668
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1669
if (peer->ident_pkey != NULL)
1670
return (CRYPTO_IFF);
1672
if (peer->crypto & CRYPTO_FLAG_MV) {
1673
snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1675
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1676
if (peer->ident_pkey != NULL)
1679
snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1681
peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1682
if (peer->ident_pkey != NULL)
1687
* No compatible identity scheme is available. Life is hard.
1690
"crypto_ident: no compatible identity scheme found");
1696
* crypto_args - construct extension field from arguments
1698
* This routine creates an extension field with current timestamps and
1699
* specified opcode, association ID and optional string. Note that the
1700
* extension field is created here, but freed after the crypto_xmit()
1701
* call in the protocol module.
1703
* Returns extension field pointer (no errors).
1707
struct peer *peer, /* peer structure pointer */
1708
u_int opcode, /* operation code */
1709
char *str /* argument string */
1712
tstamp_t tstamp; /* NTP timestamp */
1713
struct exten *ep; /* extension field pointer */
1714
u_int len; /* extension field length */
1716
tstamp = crypto_time();
1717
len = sizeof(struct exten);
1725
ep->opcode = htonl(opcode + len);
1728
* If a response, send our ID; if a request, send the
1731
if (opcode & CRYPTO_RESP)
1732
ep->associd = htonl(peer->associd);
1734
ep->associd = htonl(peer->assoc);
1735
ep->tstamp = htonl(tstamp);
1736
ep->fstamp = hostval.tstamp;
1739
ep->vallen = htonl(strlen(str));
1740
memcpy((char *)ep->pkt, str, strlen(str));
1742
ep->pkt[0] = peer->associd;
1749
* crypto_send - construct extension field from value components
1751
* Returns extension field length. Note: it is not polite to send a
1752
* nonempty signature with zero timestamp or a nonzero timestamp with
1753
* empty signature, but these rules are not enforced here.
1757
struct exten *ep, /* extension field pointer */
1758
struct value *vp /* value pointer */
1765
* Copy data. If the data field is empty or zero length, encode
1766
* an empty value with length zero.
1768
ep->tstamp = vp->tstamp;
1769
ep->fstamp = vp->fstamp;
1770
ep->vallen = vp->vallen;
1772
temp32 = ntohl(vp->vallen);
1773
if (temp32 > 0 && vp->ptr != NULL)
1774
memcpy(ep->pkt, vp->ptr, temp32);
1777
* Copy signature. If the signature field is empty or zero
1778
* length, encode an empty signature with length zero.
1780
i = (temp32 + 3) / 4;
1782
ep->pkt[i++] = vp->siglen;
1783
temp32 = ntohl(vp->siglen);
1784
if (temp32 > 0 && vp->sig != NULL)
1785
memcpy(&ep->pkt[i], vp->sig, temp32);
1792
* crypto_update - compute new public value and sign extension fields
1794
* This routine runs periodically, like once a day, and when something
1795
* changes. It updates the timestamps on three value structures and one
1796
* value structure list, then signs all the structures:
1798
* hostval host name (not signed)
1800
* cinfo certificate info/value list
1801
* tai_leap leapseconds file
1803
* Filestamps are proventicated data, so this routine is run only when
1804
* the host has been synchronized to a proventicated source. Thus, the
1805
* timestamp is proventicated, too, and can be used to deflect
1806
* clogging attacks and even cook breakfast.
1808
* Returns void (no errors)
1813
EVP_MD_CTX ctx; /* message digest context */
1814
struct cert_info *cp, *cpn, **zp; /* certificate info/value */
1815
char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1816
tstamp_t tstamp; /* NTP timestamp */
1819
if ((tstamp = crypto_time()) == 0)
1822
hostval.tstamp = htonl(tstamp);
1825
* Sign public key and timestamps. The filestamp is derived from
1826
* the host key file extension from wherever the file was
1829
if (pubkey.vallen != 0) {
1830
pubkey.tstamp = hostval.tstamp;
1832
if (pubkey.sig == NULL)
1833
pubkey.sig = emalloc(sign_siglen);
1834
EVP_SignInit(&ctx, sign_digest);
1835
EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1836
EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1837
if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
1838
pubkey.siglen = htonl(len);
1842
* Sign certificates and timestamps. The filestamp is derived
1843
* from the certificate file extension from wherever the file
1844
* was generated. At the same time expired certificates are
1848
for (cp = cinfo; cp != NULL; cp = cpn) {
1850
if (tstamp > cp->last) {
1854
cp->cert.tstamp = hostval.tstamp;
1855
cp->cert.siglen = 0;
1856
if (cp->cert.sig == NULL)
1857
cp->cert.sig = emalloc(sign_siglen);
1858
EVP_SignInit(&ctx, sign_digest);
1859
EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1860
EVP_SignUpdate(&ctx, cp->cert.ptr,
1861
ntohl(cp->cert.vallen));
1862
if (EVP_SignFinal(&ctx, cp->cert.sig, &len,
1864
cp->cert.siglen = htonl(len);
1870
* Sign leapseconds table and timestamps. The filestamp is
1871
* derived from the leapsecond file extension from wherever the
1872
* file was generated.
1495
1874
if (tai_leap.vallen != 0) {
1496
tai_leap.tstamp = htonl(tstamp);
1497
EVP_SignInit(&ctx, DA_MD5);
1875
tai_leap.tstamp = hostval.tstamp;
1876
tai_leap.siglen = 0;
1877
if (tai_leap.sig == NULL)
1878
tai_leap.sig = emalloc(sign_siglen);
1879
EVP_SignInit(&ctx, sign_digest);
1498
1880
EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1499
1881
EVP_SignUpdate(&ctx, tai_leap.ptr,
1500
1882
ntohl(tai_leap.vallen));
1501
rval = EVP_SignFinal(&ctx, tai_leap.sig, &len,
1503
if (rval != RV_OK || len != private_key.bits / 8) {
1505
"crypto: leapseconds signature fails %x",
1509
tai_leap.siglen = ntohl(len);
1883
if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
1884
tai_leap.siglen = htonl(len);
1886
sprintf(statstr, "update ts %u", ntohl(hostval.tstamp));
1887
record_crypto_stats(NULL, statstr);
1514
"cypto_agree: ts %u host %u par %u pub %u leap %u\n",
1515
tstamp, ntohl(host.fstamp), ntohl(dhparam.fstamp),
1516
ntohl(dhpub.fstamp), ntohl(tai_leap.fstamp));
1522
* crypto_rsa - read RSA key, decode and check for errors.
1526
char *cp, /* file name */
1527
u_char *key, /* key pointer */
1528
u_int keylen /* key length */
1531
FILE *str; /* file handle */
1532
u_char buf[MAX_LINLEN]; /* file line buffer */
1533
u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1534
char filename[MAXFILENAME]; /* name of parameter file */
1535
char linkname[MAXFILENAME]; /* file link (for filestamp) */
1536
u_int fstamp; /* filestamp */
1542
* Open the file and discard comment lines. If the first
1543
* character of the file name is not '/', prepend the keys
1890
printf("crypto_update: %s\n", statstr);
1896
* value_free - free value structure components.
1898
* Returns void (no errors)
1902
struct value *vp /* value structure */
1905
if (vp->ptr != NULL)
1907
if (vp->sig != NULL)
1909
memset(vp, 0, sizeof(struct value));
1914
* crypto_time - returns current NTP time in seconds.
1919
l_fp tstamp; /* NTP time */ L_CLR(&tstamp);
1922
if (sys_leap != LEAP_NOTINSYNC)
1923
get_systime(&tstamp);
1924
return (tstamp.l_ui);
1929
* asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
1933
ASN1_TIME *asn1time /* pointer to ASN1_TIME structure */
1936
char *v; /* pointer to ASN1_TIME string */
1937
struct tm tm; /* used to convert to NTP time */
1940
* Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1941
* Note that the YY, MM, DD fields start with one, the HH, MM,
1942
* SS fiels start with zero and the Z character should be 'Z'
1943
* for UTC. Also note that years less than 50 map to years
1944
* greater than 100. Dontcha love ASN.1? Better than MIL-188.
1946
if (asn1time->length > 13)
1947
return ((u_long)(~0)); /* We can't use -1 here. It's invalid */
1948
v = (char *)asn1time->data;
1949
tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
1950
if (tm.tm_year < 50)
1952
tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
1953
tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
1954
tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
1955
tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
1956
tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
1960
return (timegm(&tm) + JAN_1970);
1965
* bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
1969
BIGNUM *bn, /* BIGNUM * from */
1970
BIGNUM *bk /* BIGNUM * to */
1973
EVP_MD_CTX ctx; /* message digest context */
1974
u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
1975
u_char *ptr; /* a BIGNUM as binary string */
1978
len = BN_num_bytes(bn);
1981
EVP_DigestInit(&ctx, EVP_md5());
1982
EVP_DigestUpdate(&ctx, ptr, len);
1983
EVP_DigestFinal(&ctx, dgst, &len);
1984
BN_bin2bn(dgst, len, bk);
1990
***********************************************************************
1992
* The following routines implement the Schnorr (IFF) identity scheme *
1994
***********************************************************************
1996
* The Schnorr (IFF) identity scheme is intended for use when
1997
* the ntp-genkeys program does not generate the certificates used in
1998
* the protocol and the group key cannot be conveyed in the certificate
1999
* itself. For this purpose, new generations of IFF values must be
2000
* securely transmitted to all members of the group before use. The
2001
* scheme is self contained and independent of new generations of host
2002
* keys, sign keys and certificates.
2004
* The IFF identity scheme is based on DSA cryptography and algorithms
2005
* described in Stinson p. 285. The IFF values hide in a DSA cuckoo
2006
* structure, but only the primes and generator are used. The p is a
2007
* 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
2008
* of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
2009
* group key b disguised as a DSA structure member, then computes public
2010
* key g^(q - b). These values are shared only among group members and
2011
* never revealed in messages. Alice challenges Bob to confirm identity
2012
* using the protocol described below.
2016
* The scheme goes like this. Both Alice and Bob have the public primes
2017
* p, q and generator g. The TA gives private key b to Bob and public
2018
* key v = g^(q - a) mod p to Alice.
2020
* Alice rolls new random challenge r and sends to Bob in the IFF
2021
* request message. Bob rolls new random k, then computes y = k + b r
2022
* mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
2023
* response message. Besides making the response shorter, the hash makes
2024
* it effectivey impossible for an intruder to solve for b by observing
2025
* a number of these messages.
2027
* Alice receives the response and computes g^y v^r mod p. After a bit
2028
* of algebra, this simplifies to g^k. If the hash of this result
2029
* matches hash(x), Alice knows that Bob has the group key b. The signed
2030
* response binds this knowledge to Bob's private key and the public key
2031
* previously received in his certificate.
2033
* crypto_alice - construct Alice's challenge in IFF scheme
2037
* XEVNT_PUB bad or missing public key
2038
* XEVNT_ID bad or missing identity parameters
2042
struct peer *peer, /* peer pointer */
2043
struct value *vp /* value pointer */
2046
DSA *dsa; /* IFF parameters */
2047
BN_CTX *bctx; /* BIGNUM context */
2048
EVP_MD_CTX ctx; /* signature context */
2053
* The identity parameters must have correct format and content.
2055
if (peer->ident_pkey == NULL)
2057
if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2058
msyslog(LOG_INFO, "crypto_alice: defective key");
2063
* Roll new random r (0 < r < q). The OpenSSL library has a bug
2064
* omitting BN_rand_range, so we have to do it the hard way.
2066
bctx = BN_CTX_new();
2067
len = BN_num_bytes(dsa->q);
2068
if (peer->iffval != NULL)
2069
BN_free(peer->iffval);
2070
peer->iffval = BN_new();
2071
BN_rand(peer->iffval, len * 8, -1, 1); /* r */
2072
BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2076
* Sign and send to Bob. The filestamp is from the local file.
2078
tstamp = crypto_time();
2079
memset(vp, 0, sizeof(struct value));
2080
vp->tstamp = htonl(tstamp);
2081
vp->fstamp = htonl(peer->fstamp);
2082
vp->vallen = htonl(len);
2083
vp->ptr = emalloc(len);
2084
BN_bn2bin(peer->iffval, vp->ptr);
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);
2099
* crypto_bob - construct Bob's response to Alice's challenge
2103
* XEVNT_PUB bad or missing public key
2107
struct exten *ep, /* extension pointer */
2108
struct value *vp /* value pointer */
2111
DSA *dsa; /* IFF parameters */
2112
DSA_SIG *sdsa; /* DSA signature context fake */
2113
BN_CTX *bctx; /* BIGNUM context */
2114
EVP_MD_CTX ctx; /* signature context */
2115
tstamp_t tstamp; /* NTP timestamp */
2116
BIGNUM *bn, *bk, *r;
2121
* If the IFF parameters are not valid, something awful
2122
* happened or we are being tormented.
2124
if (!(crypto_flags & CRYPTO_FLAG_IFF)) {
2125
msyslog(LOG_INFO, "crypto_bob: scheme unavailable");
2128
dsa = iffpar_pkey->pkey.dsa;
2131
* Extract r from the challenge.
2133
len = ntohl(ep->vallen);
2134
if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2135
msyslog(LOG_ERR, "crypto_bob %s\n",
2136
ERR_error_string(ERR_get_error(), NULL));
2141
* Bob rolls random k (0 < k < q), computes y = k + b r mod q
2142
* and x = g^k mod p, then sends (y, hash(x)) to Alice.
2144
bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2145
sdsa = DSA_SIG_new();
2146
BN_rand(bk, len * 8, -1, 1); /* k */
2147
BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2149
BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
2150
sdsa->r = BN_dup(bn);
2151
BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2153
sdsa->s = BN_dup(bk);
2155
BN_free(r); BN_free(bn); BN_free(bk);
2158
* Encode the values in ASN.1 and sign.
2160
tstamp = crypto_time();
2161
memset(vp, 0, sizeof(struct value));
2162
vp->tstamp = htonl(tstamp);
2163
vp->fstamp = htonl(if_fstamp);
2164
len = i2d_DSA_SIG(sdsa, NULL);
2166
msyslog(LOG_ERR, "crypto_bob %s\n",
2167
ERR_error_string(ERR_get_error(), NULL));
2171
vp->vallen = htonl(len);
2174
i2d_DSA_SIG(sdsa, &ptr);
2179
vp->sig = emalloc(sign_siglen);
2180
EVP_SignInit(&ctx, sign_digest);
2181
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2182
EVP_SignUpdate(&ctx, vp->ptr, len);
2183
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2184
vp->siglen = htonl(len);
2190
* crypto_iff - verify Bob's response to Alice's challenge
2194
* XEVNT_PUB bad or missing public key
2195
* XEVNT_FSP bad filestamp
2196
* XEVNT_ID bad or missing identity parameters
2200
struct exten *ep, /* extension pointer */
2201
struct peer *peer /* peer structure pointer */
2204
DSA *dsa; /* IFF parameters */
2205
BN_CTX *bctx; /* BIGNUM context */
2206
DSA_SIG *sdsa; /* DSA parameters */
2213
* If the IFF parameters are not valid or no challenge was sent,
2214
* something awful happened or we are being tormented.
2216
if (peer->ident_pkey == NULL) {
2217
msyslog(LOG_INFO, "crypto_iff: scheme unavailable");
2220
if (ntohl(ep->fstamp) != peer->fstamp) {
2221
msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u",
2225
if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2226
msyslog(LOG_INFO, "crypto_iff: defective key");
2229
if (peer->iffval == NULL) {
2230
msyslog(LOG_INFO, "crypto_iff: missing challenge");
2235
* Extract the k + b r and g^k values from the response.
2237
bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2238
len = ntohl(ep->vallen);
2239
ptr = (const u_char *)ep->pkt;
2240
if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2241
msyslog(LOG_ERR, "crypto_iff %s\n",
2242
ERR_error_string(ERR_get_error(), NULL));
2247
* Compute g^(k + b r) g^(q - b)r mod p.
2249
BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2250
BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2251
BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2254
* Verify the hash of the result matches hash(x).
2257
temp = BN_cmp(bn, sdsa->s);
2258
BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2259
BN_free(peer->iffval);
2260
peer->iffval = NULL;
2270
***********************************************************************
2272
* The following routines implement the Guillou-Quisquater (GQ) *
2275
***********************************************************************
2277
* The Guillou-Quisquater (GQ) identity scheme is intended for use when
2278
* the ntp-genkeys program generates the certificates used in the
2279
* protocol and the group key can be conveyed in a certificate extension
2280
* field. The scheme is self contained and independent of new
2281
* generations of host keys, sign keys and certificates.
2283
* The GQ identity scheme is based on RSA cryptography and algorithms
2284
* described in Stinson p. 300 (with errors). The GQ values hide in a
2285
* RSA cuckoo structure, but only the modulus is used. The 512-bit
2286
* public modulus is n = p q, where p and q are secret large primes. The
2287
* TA rolls random group key b disguised as a RSA structure member.
2288
* Except for the public key, these values are shared only among group
2289
* members and never revealed in messages.
2291
* When rolling new certificates, Bob recomputes the private and
2292
* public keys. The private key u is a random roll, while the public key
2293
* is the inverse obscured by the group key v = (u^-1)^b. These values
2294
* replace the private and public keys normally generated by the RSA
2295
* scheme. Alice challenges Bob to confirm identity using the protocol
2300
* The scheme goes like this. Both Alice and Bob have the same modulus n
2301
* and some random b as the group key. These values are computed and
2302
* distributed in advance via secret means, although only the group key
2303
* b is truly secret. Each has a private random private key u and public
2304
* key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2305
* can regenerate the key pair from time to time without affecting
2306
* operations. The public key is conveyed on the certificate in an
2307
* extension field; the private key is never revealed.
2309
* Alice rolls new random challenge r and sends to Bob in the GQ
2310
* request message. Bob rolls new random k, then computes y = k u^r mod
2311
* n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2312
* message. Besides making the response shorter, the hash makes it
2313
* effectivey impossible for an intruder to solve for b by observing
2314
* a number of these messages.
2316
* Alice receives the response and computes y^b v^r mod n. After a bit
2317
* of algebra, this simplifies to k^b. If the hash of this result
2318
* matches hash(x), Alice knows that Bob has the group key b. The signed
2319
* response binds this knowledge to Bob's private key and the public key
2320
* previously received in his certificate.
2322
* crypto_alice2 - construct Alice's challenge in GQ scheme
2326
* XEVNT_PUB bad or missing public key
2327
* XEVNT_ID bad or missing identity parameters
2331
struct peer *peer, /* peer pointer */
2332
struct value *vp /* value pointer */
2335
RSA *rsa; /* GQ parameters */
2336
BN_CTX *bctx; /* BIGNUM context */
2337
EVP_MD_CTX ctx; /* signature context */
2342
* The identity parameters must have correct format and content.
2344
if (peer->ident_pkey == NULL)
2346
if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2347
msyslog(LOG_INFO, "crypto_alice2: defective key");
2352
* Roll new random r (0 < r < n). The OpenSSL library has a bug
2353
* omitting BN_rand_range, so we have to do it the hard way.
2355
bctx = BN_CTX_new();
2356
len = BN_num_bytes(rsa->n);
2357
if (peer->iffval != NULL)
2358
BN_free(peer->iffval);
2359
peer->iffval = BN_new();
2360
BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2361
BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2365
* Sign and send to Bob. The filestamp is from the local file.
2367
tstamp = crypto_time();
2368
memset(vp, 0, sizeof(struct value));
2369
vp->tstamp = htonl(tstamp);
2370
vp->fstamp = htonl(peer->fstamp);
2371
vp->vallen = htonl(len);
2372
vp->ptr = emalloc(len);
2373
BN_bn2bin(peer->iffval, vp->ptr);
2377
vp->sig = emalloc(sign_siglen);
2378
EVP_SignInit(&ctx, sign_digest);
2379
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2380
EVP_SignUpdate(&ctx, vp->ptr, len);
2381
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2382
vp->siglen = htonl(len);
2388
* crypto_bob2 - construct Bob's response to Alice's challenge
2392
* XEVNT_PUB bad or missing public key
2396
struct exten *ep, /* extension pointer */
2397
struct value *vp /* value pointer */
2400
RSA *rsa; /* GQ parameters */
2401
DSA_SIG *sdsa; /* DSA parameters */
2402
BN_CTX *bctx; /* BIGNUM context */
2403
EVP_MD_CTX ctx; /* signature context */
2404
tstamp_t tstamp; /* NTP timestamp */
2405
BIGNUM *r, *k, *g, *y;
2410
* If the GQ parameters are not valid, something awful
2411
* happened or we are being tormented.
2413
if (!(crypto_flags & CRYPTO_FLAG_GQ)) {
2414
msyslog(LOG_INFO, "crypto_bob2: scheme unavailable");
2417
rsa = gqpar_pkey->pkey.rsa;
2420
* Extract r from the challenge.
2422
len = ntohl(ep->vallen);
2423
if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2424
msyslog(LOG_ERR, "crypto_bob2 %s\n",
2425
ERR_error_string(ERR_get_error(), NULL));
2430
* Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2431
* x = k^b mod n, then sends (y, hash(x)) to Alice.
2433
bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2434
sdsa = DSA_SIG_new();
2435
BN_rand(k, len * 8, -1, 1); /* k */
2436
BN_mod(k, k, rsa->n, bctx);
2437
BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2438
BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
2439
sdsa->r = BN_dup(y);
2440
BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2442
sdsa->s = BN_dup(g);
2444
BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2447
* Encode the values in ASN.1 and sign.
2449
tstamp = crypto_time();
2450
memset(vp, 0, sizeof(struct value));
2451
vp->tstamp = htonl(tstamp);
2452
vp->fstamp = htonl(gq_fstamp);
2453
len = i2d_DSA_SIG(sdsa, NULL);
2455
msyslog(LOG_ERR, "crypto_bob2 %s\n",
2456
ERR_error_string(ERR_get_error(), NULL));
2460
vp->vallen = htonl(len);
2463
i2d_DSA_SIG(sdsa, &ptr);
2468
vp->sig = emalloc(sign_siglen);
2469
EVP_SignInit(&ctx, sign_digest);
2470
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2471
EVP_SignUpdate(&ctx, vp->ptr, len);
2472
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2473
vp->siglen = htonl(len);
2479
* crypto_gq - verify Bob's response to Alice's challenge
2483
* XEVNT_PUB bad or missing public key
2484
* XEVNT_FSP bad filestamp
2485
* XEVNT_ID bad or missing identity parameters
2489
struct exten *ep, /* extension pointer */
2490
struct peer *peer /* peer structure pointer */
2493
RSA *rsa; /* GQ parameters */
2494
BN_CTX *bctx; /* BIGNUM context */
2495
DSA_SIG *sdsa; /* RSA signature context fake */
2502
* If the GQ parameters are not valid or no challenge was sent,
2503
* something awful happened or we are being tormented.
2505
if (peer->ident_pkey == NULL) {
2506
msyslog(LOG_INFO, "crypto_gq: scheme unavailable");
2509
if (ntohl(ep->fstamp) != peer->fstamp) {
2510
msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u",
2514
if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2515
msyslog(LOG_INFO, "crypto_gq: defective key");
2518
if (peer->iffval == NULL) {
2519
msyslog(LOG_INFO, "crypto_gq: missing challenge");
2524
* Extract the y = k u^r and hash(x = k^b) values from the
2527
bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2528
len = ntohl(ep->vallen);
2529
ptr = (const u_char *)ep->pkt;
2530
if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2531
msyslog(LOG_ERR, "crypto_gq %s\n",
2532
ERR_error_string(ERR_get_error(), NULL));
2537
* Compute v^r y^b mod n.
2539
BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2541
BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2542
BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
2545
* Verify the hash of the result matches hash(x).
2548
temp = BN_cmp(y, sdsa->s);
2549
BN_CTX_free(bctx); BN_free(y); BN_free(v);
2550
BN_free(peer->iffval);
2551
peer->iffval = NULL;
2561
***********************************************************************
2563
* The following routines implement the Mu-Varadharajan (MV) identity *
2566
***********************************************************************
2569
* The Mu-Varadharajan (MV) cryptosystem was originally intended when
2570
* servers broadcast messages to clients, but clients never send
2571
* messages to servers. There is one encryption key for the server and a
2572
* separate decryption key for each client. It operated something like a
2573
* pay-per-view satellite broadcasting system where the session key is
2574
* encrypted by the broadcaster and the decryption keys are held in a
2575
* tamperproof set-top box.
2577
* The MV parameters and private encryption key hide in a DSA cuckoo
2578
* structure which uses the same parameters, but generated in a
2579
* different way. The values are used in an encryption scheme similar to
2580
* El Gamal cryptography and a polynomial formed from the expansion of
2581
* product terms (x - x[j]), as described in Mu, Y., and V.
2582
* Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2583
* 223-231. The paper has significant errors and serious omissions.
2585
* Let q be the product of n distinct primes s'[j] (j = 1...n), where
2586
* each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2587
* that q and each s'[j] divide p - 1 and p has M = n * m + 1
2588
* significant bits. The elements x mod q of Zq with the elements 2 and
2589
* the primes removed form a field Zq* valid for polynomial arithetic.
2590
* Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
2591
* mod p. We expect M to be in the 500-bit range and n relatively small,
2592
* like 25, so the likelihood of a randomly generated element of x mod q
2593
* of Zq colliding with a factor of p - 1 is very small and can be
2594
* avoided. Associated with each s'[j] is an element s[j] such that s[j]
2595
* s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
2596
* s'[j]. These are the parameters of the scheme and they are expensive
2599
* We set up an instance of the scheme as follows. A set of random
2600
* values x[j] mod q (j = 1...n), are generated as the zeros of a
2601
* polynomial of order n. The product terms (x - x[j]) are expanded to
2602
* form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2603
* used as exponents of the generator g mod p to generate the private
2604
* encryption key A. The pair (gbar, ghat) of public server keys and the
2605
* pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2606
* to construct the decryption keys. The devil is in the details.
2608
* The distinguishing characteristic of this scheme is the capability to
2609
* revoke keys. Included in the calculation of E, gbar and ghat is the
2610
* product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
2611
* subsequently removed from the product and E, gbar and ghat
2612
* recomputed, the jth client will no longer be able to compute E^-1 and
2613
* thus unable to decrypt the block.
2617
* The scheme goes like this. Bob has the server values (p, A, q, gbar,
2618
* ghat) and Alice the client values (p, xbar, xhat).
2620
* Alice rolls new random challenge r (0 < r < p) and sends to Bob in
2621
* the MV request message. Bob rolls new random k (0 < k < q), encrypts
2622
* y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
2625
* Alice receives the response and computes the decryption key (the
2626
* inverse permutation) from previously obtained (xbar, xhat) and
2627
* (gbar^k, ghat^k) in the message. She computes the inverse, which is
2628
* unique by reasons explained in the ntp-keygen.c program sources. If
2629
* the hash of this result matches hash(y), Alice knows that Bob has the
2630
* group key b. The signed response binds this knowledge to Bob's
2631
* private key and the public key previously received in his
2634
* crypto_alice3 - construct Alice's challenge in MV scheme
2638
* XEVNT_PUB bad or missing public key
2639
* XEVNT_ID bad or missing identity parameters
2643
struct peer *peer, /* peer pointer */
2644
struct value *vp /* value pointer */
2647
DSA *dsa; /* MV parameters */
2648
BN_CTX *bctx; /* BIGNUM context */
2649
EVP_MD_CTX ctx; /* signature context */
2654
* The identity parameters must have correct format and content.
2656
if (peer->ident_pkey == NULL)
2658
if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2659
msyslog(LOG_INFO, "crypto_alice3: defective key");
2664
* Roll new random r (0 < r < q). The OpenSSL library has a bug
2665
* omitting BN_rand_range, so we have to do it the hard way.
2667
bctx = BN_CTX_new();
2668
len = BN_num_bytes(dsa->p);
2669
if (peer->iffval != NULL)
2670
BN_free(peer->iffval);
2671
peer->iffval = BN_new();
2672
BN_rand(peer->iffval, len * 8, -1, 1); /* r */
2673
BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2677
* Sign and send to Bob. The filestamp is from the local file.
2679
tstamp = crypto_time();
2680
memset(vp, 0, sizeof(struct value));
2681
vp->tstamp = htonl(tstamp);
2682
vp->fstamp = htonl(peer->fstamp);
2683
vp->vallen = htonl(len);
2684
vp->ptr = emalloc(len);
2685
BN_bn2bin(peer->iffval, vp->ptr);
2689
vp->sig = emalloc(sign_siglen);
2690
EVP_SignInit(&ctx, sign_digest);
2691
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2692
EVP_SignUpdate(&ctx, vp->ptr, len);
2693
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2694
vp->siglen = htonl(len);
2700
* crypto_bob3 - construct Bob's response to Alice's challenge
2704
* XEVNT_PUB bad or missing public key
2708
struct exten *ep, /* extension pointer */
2709
struct value *vp /* value pointer */
2712
DSA *dsa; /* MV parameters */
2713
DSA *sdsa; /* DSA signature context fake */
2714
BN_CTX *bctx; /* BIGNUM context */
2715
EVP_MD_CTX ctx; /* signature context */
2716
tstamp_t tstamp; /* NTP timestamp */
2722
* If the MV parameters are not valid, something awful
2723
* happened or we are being tormented.
2725
if (!(crypto_flags & CRYPTO_FLAG_MV)) {
2726
msyslog(LOG_INFO, "crypto_bob3: scheme unavailable");
2729
dsa = mvpar_pkey->pkey.dsa;
2732
* Extract r from the challenge.
2734
len = ntohl(ep->vallen);
2735
if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2736
msyslog(LOG_ERR, "crypto_bob3 %s\n",
2737
ERR_error_string(ERR_get_error(), NULL));
2742
* Bob rolls random k (0 < k < q), making sure it is not a
2743
* factor of q. He then computes y = A^k r and sends (hash(y),
2744
* gbar^k, ghat^k) to Alice.
2746
bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2748
sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2750
BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2751
BN_mod(k, k, dsa->q, bctx);
2752
BN_gcd(u, k, dsa->q, bctx);
2756
BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */
2757
BN_mod_mul(u, u, r, dsa->p, bctx);
2758
bighash(u, sdsa->p);
2759
BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2760
BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2761
BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2764
* Encode the values in ASN.1 and sign.
2766
tstamp = crypto_time();
2767
memset(vp, 0, sizeof(struct value));
2768
vp->tstamp = htonl(tstamp);
2769
vp->fstamp = htonl(mv_fstamp);
2770
len = i2d_DSAparams(sdsa, NULL);
2772
msyslog(LOG_ERR, "crypto_bob3 %s\n",
2773
ERR_error_string(ERR_get_error(), NULL));
2777
vp->vallen = htonl(len);
2780
i2d_DSAparams(sdsa, &ptr);
2785
vp->sig = emalloc(sign_siglen);
2786
EVP_SignInit(&ctx, sign_digest);
2787
EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2788
EVP_SignUpdate(&ctx, vp->ptr, len);
2789
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2790
vp->siglen = htonl(len);
2796
* crypto_mv - verify Bob's response to Alice's challenge
2800
* XEVNT_PUB bad or missing public key
2801
* XEVNT_FSP bad filestamp
2802
* XEVNT_ID bad or missing identity parameters
2806
struct exten *ep, /* extension pointer */
2807
struct peer *peer /* peer structure pointer */
2810
DSA *dsa; /* MV parameters */
2811
DSA *sdsa; /* DSA parameters */
2812
BN_CTX *bctx; /* BIGNUM context */
2819
* If the MV parameters are not valid or no challenge was sent,
2820
* something awful happened or we are being tormented.
2822
if (peer->ident_pkey == NULL) {
2823
msyslog(LOG_INFO, "crypto_mv: scheme unavailable");
2826
if (ntohl(ep->fstamp) != peer->fstamp) {
2827
msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u",
2831
if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2832
msyslog(LOG_INFO, "crypto_mv: defective key");
2835
if (peer->iffval == NULL) {
2836
msyslog(LOG_INFO, "crypto_mv: missing challenge");
2841
* Extract the (hash(y), gbar, ghat) values from the response.
2843
bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2844
len = ntohl(ep->vallen);
2845
ptr = (const u_char *)ep->pkt;
2846
if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2847
msyslog(LOG_ERR, "crypto_mv %s\n",
2848
ERR_error_string(ERR_get_error(), NULL));
2853
* Compute (gbar^xhat ghat^xbar)^-1 mod p.
2855
BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2856
BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2857
BN_mod_mul(u, u, v, dsa->p, bctx);
2858
BN_mod_inverse(u, u, dsa->p, bctx);
2859
BN_mod_mul(v, u, peer->iffval, dsa->p, bctx);
2862
* The result should match the hash of r mod p.
2865
temp = BN_cmp(v, sdsa->p);
2866
BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
2867
BN_free(peer->iffval);
2868
peer->iffval = NULL;
2878
***********************************************************************
2880
* The following routines are used to manipulate certificates *
2882
***********************************************************************
2885
* cert_parse - parse x509 certificate and create info/value structures.
2887
* The server certificate includes the version number, issuer name,
2888
* subject name, public key and valid date interval. If the issuer name
2889
* is the same as the subject name, the certificate is self signed and
2890
* valid only if the server is configured as trustable. If the names are
2891
* different, another issuer has signed the server certificate and
2892
* vouched for it. In this case the server certificate is valid if
2893
* verified by the issuer public key.
2895
* Returns certificate info/value pointer if valid, NULL if not.
2897
struct cert_info * /* certificate information structure */
2899
u_char *asn1cert, /* X509 certificate */
2900
u_int len, /* certificate length */
2901
tstamp_t fstamp /* filestamp */
2904
X509 *cert; /* X509 certificate */
2905
X509_EXTENSION *ext; /* X509v3 extension */
2906
struct cert_info *ret; /* certificate info/value */
2908
X509V3_EXT_METHOD *method;
2909
char pathbuf[MAXFILENAME];
2915
* Decode ASN.1 objects and construct certificate structure.
2918
if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) {
2919
msyslog(LOG_ERR, "cert_parse %s\n",
2920
ERR_error_string(ERR_get_error(), NULL));
2925
* Extract version, subject name and public key.
2927
ret = emalloc(sizeof(struct cert_info));
2928
memset(ret, 0, sizeof(struct cert_info));
2929
if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
2930
msyslog(LOG_ERR, "cert_parse %s\n",
2931
ERR_error_string(ERR_get_error(), NULL));
2936
ret->version = X509_get_version(cert);
2937
X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
2939
ptr = strstr(pathbuf, "CN=");
2941
msyslog(LOG_INFO, "cert_parse: invalid subject %s",
2947
ret->subject = emalloc(strlen(ptr) + 1);
2948
strcpy(ret->subject, ptr + 3);
2951
* Extract remaining objects. Note that the NTP serial number is
2952
* the NTP seconds at the time of signing, but this might not be
2953
* the case for other authority. We don't bother to check the
2954
* objects at this time, since the real crunch can happen only
2955
* when the time is valid but not yet certificated.
2957
ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
2958
ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
2960
(u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
2961
X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
2963
if ((ptr = strstr(pathbuf, "CN=")) == NULL) {
2964
msyslog(LOG_INFO, "cert_parse: invalid issuer %s",
2970
ret->issuer = emalloc(strlen(ptr) + 1);
2971
strcpy(ret->issuer, ptr + 3);
2972
ret->first = asn2ntp(X509_get_notBefore(cert));
2973
ret->last = asn2ntp(X509_get_notAfter(cert));
2976
* Extract extension fields. These are ad hoc ripoffs of
2977
* currently assigned functions and will certainly be changed
2978
* before prime time.
2980
cnt = X509_get_ext_count(cert);
2981
for (i = 0; i < cnt; i++) {
2982
ext = X509_get_ext(cert, i);
2983
method = X509V3_EXT_get(ext);
2984
temp = OBJ_obj2nid(ext->object);
2988
* If a key_usage field is present, we decode whether
2989
* this is a trusted or private certificate. This is
2990
* dorky; all we want is to compare NIDs, but OpenSSL
2991
* insists on BIO text strings.
2993
case NID_ext_key_usage:
2994
bp = BIO_new(BIO_s_mem());
2995
X509V3_EXT_print(bp, ext, 0, 0);
2996
BIO_gets(bp, pathbuf, MAXFILENAME);
3000
printf("cert_parse: %s: %s\n",
3001
OBJ_nid2ln(temp), pathbuf);
3003
if (strcmp(pathbuf, "Trust Root") == 0)
3004
ret->flags |= CERT_TRUST;
3005
else if (strcmp(pathbuf, "Private") == 0)
3006
ret->flags |= CERT_PRIV;
3010
* If a NID_subject_key_identifier field is present, it
3011
* contains the GQ public key.
3013
case NID_subject_key_identifier:
3014
ret->grplen = ext->value->length - 2;
3015
ret->grpkey = emalloc(ret->grplen);
3016
memcpy(ret->grpkey, &ext->value->data[2],
3023
* If certificate is self signed, verify signature.
3025
if (strcmp(ret->subject, ret->issuer) == 0) {
3026
if (!X509_verify(cert, ret->pkey)) {
3028
"cert_parse: invalid signature not verified %s",
3037
* Verify certificate valid times. Note that certificates cannot
3040
if (ret->first > ret->last || ret->first < fstamp) {
3042
"cert_parse: expired %s",
3050
* Build the value structure to sign and send later.
3052
ret->cert.fstamp = htonl(fstamp);
3053
ret->cert.vallen = htonl(len);
3054
ret->cert.ptr = emalloc(len);
3055
memcpy(ret->cert.ptr, asn1cert, len);
3058
X509_print_fp(stdout, cert);
3066
* cert_sign - sign x509 certificate and update value structure.
3068
* The certificate request is a copy of the client certificate, which
3069
* includes the version number, subject name and public key of the
3070
* client. The resulting certificate includes these values plus the
3071
* serial number, issuer name and validity interval of the server. The
3072
* validity interval extends from the current time to the same time one
3073
* year hence. For NTP purposes, it is convenient to use the NTP seconds
3074
* of the current time as the serial number.
3078
* XEVNT_PUB bad or missing public key
3079
* XEVNT_CRT bad or missing certificate
3080
* XEVNT_VFY certificate not verified
3084
struct exten *ep, /* extension field pointer */
3085
struct value *vp /* value pointer */
3088
X509 *req; /* X509 certificate request */
3089
X509 *cert; /* X509 certificate */
3090
X509_EXTENSION *ext; /* certificate extension */
3091
ASN1_INTEGER *serial; /* serial number */
3092
X509_NAME *subj; /* distinguished (common) name */
3093
EVP_PKEY *pkey; /* public key */
3094
EVP_MD_CTX ctx; /* message digest context */
3095
tstamp_t tstamp; /* NTP timestamp */
3101
* Decode ASN.1 objects and construct certificate structure.
3103
tstamp = crypto_time();
3107
ptr = (u_char *)ep->pkt;
3108
if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) {
3109
msyslog(LOG_ERR, "cert_sign %s\n",
3110
ERR_error_string(ERR_get_error(), NULL));
3114
* Extract public key and check for errors.
3116
if ((pkey = X509_get_pubkey(req)) == NULL) {
3117
msyslog(LOG_ERR, "cert_sign %s\n",
3118
ERR_error_string(ERR_get_error(), NULL));
3124
* Generate X509 certificate signed by this server. For this
3125
* prupose the issuer name is the server name. Also copy any
3126
* extensions that might be present.
3129
X509_set_version(cert, X509_get_version(req));
3130
serial = ASN1_INTEGER_new();
3131
ASN1_INTEGER_set(serial, tstamp);
3132
X509_set_serialNumber(cert, serial);
3133
X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3134
X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3135
subj = X509_get_issuer_name(cert);
3136
X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3137
(u_char *)sys_hostname, strlen(sys_hostname), -1, 0);
3138
subj = X509_get_subject_name(req);
3139
X509_set_subject_name(cert, subj);
3140
X509_set_pubkey(cert, pkey);
3141
ext = X509_get_ext(req, 0);
3142
temp = X509_get_ext_count(req);
3143
for (i = 0; i < temp; i++) {
3144
ext = X509_get_ext(req, i);
3145
X509_add_ext(cert, ext, -1);
3150
* Sign and verify the certificate.
3152
X509_sign(cert, sign_pkey, sign_digest);
3153
if (!X509_verify(cert, sign_pkey)) {
3154
printf("cert_sign\n%s\n",
3155
ERR_error_string(ERR_get_error(), NULL));
3159
len = i2d_X509(cert, NULL);
3162
* Build and sign the value structure. We have to sign it here,
3163
* since the response has to be returned right away. This is a
3166
memset(vp, 0, sizeof(struct value));
3167
vp->tstamp = htonl(tstamp);
3168
vp->fstamp = ep->fstamp;
3169
vp->vallen = htonl(len);
3170
vp->ptr = emalloc(len);
3172
i2d_X509(cert, &ptr);
3174
vp->sig = emalloc(sign_siglen);
3175
EVP_SignInit(&ctx, sign_digest);
3176
EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3177
EVP_SignUpdate(&ctx, vp->ptr, len);
3178
if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
3179
vp->siglen = htonl(len);
3182
X509_print_fp(stdout, cert);
3190
* cert_valid - verify certificate with given public key
3192
* This is pretty ugly, as the certificate has to be verified in the
3193
* OpenSSL X509 structure, not in the DER format in the info/value
3198
* XEVNT_VFY certificate not verified
3202
struct cert_info *cinf, /* certificate information structure */
3203
EVP_PKEY *pkey /* public key */
3206
X509 *cert; /* X509 certificate */
3209
if (cinf->flags & CERT_SIGN)
3211
ptr = (u_char *)cinf->cert.ptr;
3212
cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen));
3213
if (!X509_verify(cert, pkey))
3215
cinf->flags |= CERT_SIGN;
3222
* cert - install certificate in certificate list
3224
* This routine encodes an extension field into a certificate info/value
3225
* structure. It searches the certificate list for duplicates and
3226
* expunges whichever is older. It then searches the list for other
3227
* certificates that might be verified by this latest one. Finally, it
3228
* inserts this certificate first on the list.
3232
* XEVNT_PER certificate expired
3233
* XEVNT_CRT bad or missing certificate
3237
struct exten *ep, /* cert info/value */
3238
struct peer *peer /* peer structure */
3241
struct cert_info *cp, *xp, *yp, **zp;
3246
* Parse and validate the signed certificate. If valid,
3247
* construct the info/value structure; otherwise, scamper home.
3248
* Note this allows a certificate not-before time to be in the
3249
* future, but not a not-after time to be in the past.
3251
if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen),
3252
ntohl(ep->fstamp))) == NULL)
3255
tstamp = crypto_time();
3256
if (tstamp > cp->last) {
3262
* Scan certificate list looking for another certificate with
3263
* the same subject and issuer. If another is found with the
3264
* same or older filestamp, unlink it and return the goodies to
3265
* the heap. If another is found with a later filetsamp, discard
3266
* the new one and leave the building.
3271
for (xp = cinfo; xp != NULL; xp = xp->link) {
3272
if (strcmp(cp->subject, xp->subject) == 0 &&
3273
strcmp(cp->issuer, xp->issuer) == 0) {
3274
if (ntohl(cp->cert.fstamp) <=
3275
ntohl(xp->cert.fstamp)) {
3290
* Scan the certificate list to see if Y is signed by X.
3292
for (yp = cinfo; yp != NULL; yp = yp->link) {
3293
for (xp = cinfo; xp != NULL; xp = xp->link) {
3294
if (yp->flags & CERT_ERROR)
3298
* If issuer Y matches subject X and signature Y
3299
* is valid using public key X, then Y is valid.
3301
if (strcmp(yp->issuer, xp->subject) != 0)
3304
if (cert_valid(yp, xp->pkey) != XEVNT_OK) {
3305
yp->flags |= CERT_ERROR;
3308
xp->flags |= CERT_SIGN;
3311
* If X is trusted, then Y is trusted. Note that
3312
* we might stumble over a self signed
3313
* certificate that is not trusted, at least
3314
* temporarily. This can happen when a dude
3315
* first comes up, but has not synchronized the
3316
* clock and had its certificate signed by its
3317
* server. In case of broken certificate trail,
3318
* this might result in a loop that could
3319
* persist until timeout.
3321
if (!(xp->flags & CERT_TRUST))
3324
yp->flags |= CERT_TRUST;
3327
* If subject Y matches the server subject name,
3328
* then Y has completed the certificate trail.
3329
* Save the group key and light the valid bit.
3331
if (strcmp(yp->subject, peer->subject) != 0)
3334
if (yp->grpkey != NULL) {
3335
if (peer->grpkey != NULL)
3336
BN_free(peer->grpkey);
3337
peer->grpkey = BN_bin2bn(yp->grpkey,
3340
peer->crypto |= CRYPTO_FLAG_VALID;
3343
* If the server has an an identity scheme,
3344
* fetch the identity credentials. If not, the
3345
* identity is verified only by the trusted
3346
* certificate. The next signature will set the
3349
if (peer->crypto & (CRYPTO_FLAG_GQ |
3350
CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV))
3353
peer->crypto |= CRYPTO_FLAG_VRFY;
3358
* That was awesome. Now update the timestamps and signatures.
3366
* cert_free - free certificate information structure
3370
struct cert_info *cinf /* certificate info/value structure */
3373
if (cinf->pkey != NULL)
3374
EVP_PKEY_free(cinf->pkey);
3375
if (cinf->subject != NULL)
3376
free(cinf->subject);
3377
if (cinf->issuer != NULL)
3379
if (cinf->grpkey != NULL)
3381
value_free(&cinf->cert);
3387
***********************************************************************
3389
* The following routines are used only at initialization time *
3391
***********************************************************************
3394
* crypto_key - load cryptographic parameters and keys from files
3396
* This routine loads a PEM-encoded public/private key pair and extracts
3397
* the filestamp from the file name.
3399
* Returns public key pointer if valid, NULL if not. Side effect updates
3400
* the filestamp if valid.
3404
char *cp, /* file name */
3405
tstamp_t *fstamp /* filestamp */
3408
FILE *str; /* file handle */
3409
EVP_PKEY *pkey = NULL; /* public/private key */
3410
char filename[MAXFILENAME]; /* name of key file */
3411
char linkname[MAXFILENAME]; /* filestamp buffer) */
3412
char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3416
* Open the key file. If the first character of the file name is
3417
* not '/', prepend the keys directory string. If something goes
3418
* wrong, abandon ship.
1546
3420
if (*cp == '/')
1547
3421
strcpy(filename, cp);
1549
3423
snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1550
3424
str = fopen(filename, "r");
1552
msyslog(LOG_ERR, "crypto: RSA file %s not found",
1558
* Ignore initial comments and empty lines.
1560
while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1564
if (*buf == '#' || *buf == '\r' || *buf == '\0')
1570
* We are rather paranoid here, since an intruder might cause a
1571
* coredump by infiltrating a naughty key. The line must contain
1572
* a single integer followed by a PEM encoded, null-terminated
1577
else if (sscanf(buf, "%d %s", &bits, encoded_key) != 2)
1579
else if (R_DecodePEMBlock(&buf[sizeof(u_int)], &len,
1580
encoded_key, strlen(encoded_key)))
1582
else if ((len += sizeof(u_int)) != keylen)
1584
else if (bits < MIN_RSA_MODULUS_BITS || bits >
1585
MAX_RSA_MODULUS_BITS)
1589
if (rval != RV_OK) {
1591
msyslog(LOG_ERR, "crypto: RSA file %s error %x", cp,
3429
* Read the filestamp, which is contained in the first line.
3431
if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3432
msyslog(LOG_ERR, "crypto_key: no data %s\n",
3436
if ((ptr = strrchr(ptr, '.')) == NULL) {
3437
msyslog(LOG_ERR, "crypto_key: no filestamp %s\n",
3441
if (sscanf(++ptr, "%u", fstamp) != 1) {
3442
msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n",
3448
* Read and decrypt PEM-encoded private key.
3450
pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
1596
*(u_int *)buf = bits;
1597
memcpy(key, buf, keylen);
3453
msyslog(LOG_ERR, "crypto_key %s\n",
3454
ERR_error_string(ERR_get_error(), NULL));
1600
* Extract filestamp if present.
3459
* Leave tracks in the cryptostats.
1602
rval = readlink(filename, linkname, MAXFILENAME - 1);
1604
linkname[rval] = '\0';
1605
rptr = strrchr(linkname, '.');
1607
rptr = strrchr(filename, '.');
1610
sscanf(++rptr, "%u", &fstamp);
3461
if ((ptr = strrchr(linkname, '\n')) != NULL)
3463
sprintf(statstr, "%s mod %d", &linkname[2],
3464
EVP_PKEY_size(pkey) * 8);
3465
record_crypto_stats(NULL, statstr);
1616
"crypto_rsa: key file %s link %d fs %u modulus %d\n",
1617
cp, rval, fstamp, bits);
3468
printf("crypto_key: %s\n", statstr);
3470
if (EVP_MD_type(pkey) == EVP_PKEY_DSA)
3471
DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3473
RSA_print_fp(stdout, pkey->pkey.rsa, 0);
1624
* crypto_cert - read certificate
3481
* crypto_cert - load certificate from file
3483
* This routine loads a X.509 RSA or DSA certificate from a file and
3484
* constructs a info/cert value structure for this machine. The
3485
* structure includes a filestamp extracted from the file name. Later
3486
* the certificate can be sent to another machine by request.
3488
* Returns certificate info/value pointer if valid, NULL if not.
3490
static struct cert_info * /* certificate information */
1628
char *cp /* file name */
1631
u_char buf[5000]; /* file line buffer */
1632
char filename[MAXFILENAME]; /* name of certificate file */
1633
char linkname[MAXFILENAME]; /* file link (for filestamp) */
1634
u_int fstamp; /* filestamp */
1641
* Open the file and discard comment lines. If the first
1642
* character of the file name is not '/', prepend the keys
1643
* directory string. If the file is not found, not to worry; it
1644
* can be retrieved over the net. But, if it is found with
1645
* errors, we crash and burn.
1648
strcpy(filename, cp);
1650
snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1651
fd = open(filename, O_RDONLY, 0777);
1654
"crypto: certificate file %s not found",
1660
* We are rather paranoid here, since an intruder might cause a
1661
* coredump by infiltrating naughty values.
1664
len = read(fd, buf, 5000);
1666
if (rval != RV_OK) {
1668
"crypto: certificate file %s error %d", cp,
1674
* The extension field entry consists of the raw certificate.
1676
certif.vallen = htonl(200); /* xxxxxxxxxxxxxxxxxx */
1678
certif.ptr = (u_char *)pp;
1679
memcpy(pp, buf, len);
1680
certif.sig = emalloc(private_key.bits / 8);
1681
crypto_flags |= CRYPTO_FLAG_CERT;
1684
* Extract filestamp if present.
1686
rval = readlink(filename, linkname, MAXFILENAME - 1);
1688
linkname[rval] = '\0';
1689
rptr = strrchr(linkname, '.');
1691
rptr = strrchr(filename, '.');
1694
sscanf(++rptr, "%u", &fstamp);
1697
certif.fstamp = htonl(fstamp);
1701
"crypto_cert: certif file %s link %d fs %u len %d\n",
1702
cp, rval, fstamp, len);
1708
* crypto_dh - read agreement parameters, decode and check for errors.
1712
char *cp /* file name */
1715
FILE *str; /* file handle */
1716
u_char buf[MAX_LINLEN]; /* file line buffer */
1717
u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1718
u_char prime[MAX_KEYLEN]; /* decoded prime */
1719
u_char generator[MAX_KEYLEN]; /* decode generator */
1720
u_int primelen; /* prime length (octets) */
1721
u_int generatorlen; /* generator length (octets) */
1722
char filename[MAXFILENAME]; /* name of parameter file */
1723
char linkname[MAXFILENAME]; /* file link (for filestamp) */
1724
u_int fstamp; /* filestamp */
1731
* Open the file and discard comment lines. If the first
1732
* character of the file name is not '/', prepend the keys
1733
* directory string. If the file is not found, not to worry; it
1734
* can be retrieved over the net. But, if it is found with
1735
* errors, we crash and burn.
3492
char *cp /* file name */
3495
struct cert_info *ret; /* certificate information */
3496
FILE *str; /* file handle */
3497
char filename[MAXFILENAME]; /* name of certificate file */
3498
char linkname[MAXFILENAME]; /* filestamp buffer */
3499
char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3500
tstamp_t fstamp; /* filestamp */
3503
char *name, *header;
3507
* Open the certificate file. If the first character of the file
3508
* name is not '/', prepend the keys directory string. If
3509
* something goes wrong, abandon ship.
1737
3511
if (*cp == '/')
1738
3512
strcpy(filename, cp);
1740
3514
snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1741
3515
str = fopen(filename, "r");
1744
"crypto: parameters file %s not found", filename);
1749
* Ignore initial comments and empty lines.
1751
while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1752
if (strlen(buf) < 1)
1754
if (*buf == '#' || *buf == '\r' || *buf == '\0')
1760
* We are rather paranoid here, since an intruder might cause a
1761
* coredump by infiltrating a naughty key. There must be two
1762
* lines; the first contains the prime, the second the
1763
* generator. Each line must contain a single integer followed
1764
* by a PEM encoded, null-terminated string.
1768
else if (sscanf(buf, "%u %s", &primelen, encoded_key) != 2)
1770
else if (primelen > MAX_KEYLEN)
1772
else if (R_DecodePEMBlock(prime, &len, encoded_key,
1773
strlen(encoded_key)))
1775
else if (primelen != len || primelen >
1776
DECODED_CONTENT_LEN(strlen(encoded_key)))
1778
else if (fscanf(str, "%u %s", &generatorlen, encoded_key) != 2)
1780
else if (generatorlen > MAX_KEYLEN)
1782
else if (R_DecodePEMBlock(generator, &len, encoded_key,
1783
strlen(encoded_key)))
1785
else if (generatorlen != len || generatorlen >
1786
DECODED_CONTENT_LEN(strlen(encoded_key)))
1790
if (rval != RV_OK) {
1792
"crypto: parameters file %s error %x", cp,
1799
* Initialize agreement parameters and extension field in
1800
* network byte order. Note the private key length is set
1801
* arbitrarily at half the prime length.
1803
len = 4 + primelen + 4 + generatorlen;
1804
dhparam.vallen = htonl(len);
1806
dhparam.ptr = (u_char *)pp;
1807
*pp++ = htonl(primelen);
1808
memcpy(pp, prime, primelen);
1809
dh_params.prime = (u_char *)pp;
1811
*pp++ = htonl(generatorlen);
1812
memcpy(pp, &generator, generatorlen);
1813
dh_params.generator = (u_char *)pp;
1815
dh_params.primeLen = primelen;
1816
dh_params.generatorLen = generatorlen;
1817
dh_keyLen = primelen / 2;
1818
dh_private = emalloc(dh_keyLen);
1819
dhparam.sig = emalloc(private_key.bits / 8);
1820
crypto_flags |= CRYPTO_FLAG_DH;
1823
* Initialize public value extension field.
1825
dhpub.vallen = htonl(dh_params.primeLen);
1826
dhpub.ptr = emalloc(dh_params.primeLen);
1827
dhpub.sig = emalloc(private_key.bits / 8);
1830
* Extract filestamp if present.
1832
rval = readlink(filename, linkname, MAXFILENAME - 1);
1834
linkname[rval] = '\0';
1835
rptr = strrchr(linkname, '.');
1837
rptr = strrchr(filename, '.');
1840
sscanf(++rptr, "%u", &fstamp);
1843
dhparam.fstamp = htonl(fstamp);
1844
dhpub.fstamp = htonl(fstamp);
3520
* Read the filestamp, which is contained in the first line.
3522
if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3523
msyslog(LOG_ERR, "crypto_cert: no data %s\n",
3527
if ((ptr = strrchr(ptr, '.')) == NULL) {
3528
msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n",
3532
if (sscanf(++ptr, "%u", &fstamp) != 1) {
3533
msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n",
3539
* Read PEM-encoded certificate and install.
3541
if (!PEM_read(str, &name, &header, &data, &len)) {
3542
msyslog(LOG_ERR, "crypto_cert %s\n",
3543
ERR_error_string(ERR_get_error(), NULL));
3547
if (strcmp(name, "CERTIFICATE") !=0) {
3548
msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s",
3557
* Parse certificate and generate info/value structure.
3559
ret = cert_parse(data, len, fstamp);
3563
if ((ptr = strrchr(linkname, '\n')) != NULL)
3565
sprintf(statstr, "%s 0x%x len %lu", &linkname[2], ret->flags,
3567
record_crypto_stats(NULL, statstr);
1848
"crypto_dh: pars file %s link %d fs %u prime %u gen %u\n",
1849
cp, rval, fstamp, dh_params.primeLen,
1850
dh_params.generatorLen);
3570
printf("crypto_cert: %s\n", statstr);
1856
* crypto_tai - read leapseconds table and check for errors.
3577
* crypto_tai - load leapseconds table from file
3579
* This routine loads the ERTS leapsecond file in NIST text format,
3580
* converts to a value structure and extracts a filestamp from the file
3581
* name. The data are used to establish the TAI offset from UTC, which
3582
* is provided to the kernel if supported. Later the data can be sent to
3583
* another machine on request.
1860
char *cp /* file name */
3587
char *cp /* file name */
1863
FILE *str; /* file handle */
1864
u_char buf[MAX_LINLEN]; /* file line buffer */
1865
u_int leapsec[MAX_LEAP]; /* NTP time at leaps */
1866
u_int offset; /* offset at leap (s) */
1867
char filename[MAXFILENAME]; /* name of leapseconds file */
1868
char linkname[MAXFILENAME]; /* file link (for filestamp) */
1869
u_int fstamp; /* filestamp */
3590
FILE *str; /* file handle */
3591
char buf[NTP_MAXSTRLEN]; /* file line buffer */
3592
u_int leapsec[MAX_LEAP]; /* NTP time at leaps */
3593
u_int offset; /* offset at leap (s) */
3594
char filename[MAXFILENAME]; /* name of leapseconds file */
3595
char linkname[MAXFILENAME]; /* file link (for filestamp) */
3596
char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3597
tstamp_t fstamp; /* filestamp */
1874
3601
#ifdef KERNEL_PLL
1875
3602
#if NTP_API > 3
1876
3603
struct timex ntv; /* kernel interface structure */