1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
|
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"math/rand"
"net/http"
"strconv"
"sync"
"time"
"github.com/google/certificate-transparency-go/client"
"github.com/google/certificate-transparency-go/schedule"
"github.com/google/certificate-transparency-go/tls"
"github.com/google/certificate-transparency-go/trillian/ctfe"
"github.com/google/certificate-transparency-go/trillian/ctfe/configpb"
"github.com/google/certificate-transparency-go/x509"
"github.com/google/trillian/monitoring"
"github.com/transparency-dev/merkle"
"github.com/transparency-dev/merkle/proof"
"github.com/transparency-dev/merkle/rfc6962"
"k8s.io/klog/v2"
ct "github.com/google/certificate-transparency-go"
)
const (
// How many STHs and SCTs to hold on to.
sthCount = 10
sctCount = 10
// How far beyond current tree size to request for invalid requests.
invalidStretch = int64(1000000000)
)
var (
// Metrics are all per-log (label "logid"), but may also be
// per-entrypoint (label "ep") or per-return-code (label "rc").
once sync.Once
reqs monitoring.Counter // logid, ep => value
errs monitoring.Counter // logid, ep => value
rsps monitoring.Counter // logid, ep, rc => value
rspLatency monitoring.Histogram // logid, ep, rc => values
invalidReqs monitoring.Counter // logid, ep => value
)
// setupMetrics initializes all the exported metrics.
func setupMetrics(mf monitoring.MetricFactory) {
reqs = mf.NewCounter("reqs", "Number of valid requests sent", "logid", "ep")
errs = mf.NewCounter("errs", "Number of error responses received for valid requests", "logid", "ep")
rsps = mf.NewCounter("rsps", "Number of responses received for valid requests", "logid", "ep", "rc")
rspLatency = mf.NewHistogram("rsp_latency", "Latency of valid responses in seconds", "logid", "ep", "rc")
invalidReqs = mf.NewCounter("invalid_reqs", "Number of deliberately-invalid requests sent", "logid", "ep")
}
// errSkip indicates that a test operation should be skipped.
type errSkip struct{}
func (e errSkip) Error() string {
return "test operation skipped"
}
// Choice represents a random decision about a hammer operation.
type Choice string
// Constants for per-operation choices.
const (
ParamTooBig = Choice("ParamTooBig")
Param2TooBig = Choice("Param2TooBig")
ParamNegative = Choice("ParamNegative")
ParamInvalid = Choice("ParamInvalid")
ParamsInverted = Choice("ParamsInverted")
InvalidBase64 = Choice("InvalidBase64")
EmptyChain = Choice("EmptyChain")
CertNotPrecert = Choice("CertNotPrecert")
PrecertNotCert = Choice("PrecertNotCert")
NoChainToRoot = Choice("NoChainToRoot")
UnparsableCert = Choice("UnparsableCert")
NewCert = Choice("NewCert")
LastCert = Choice("LastCert")
FirstCert = Choice("FirstCert")
)
// Limiter is an interface to allow different rate limiters to be used with the
// hammer.
type Limiter interface {
Wait(context.Context) error
}
type unLimited struct{}
func (u unLimited) Wait(ctx context.Context) error {
return nil
}
// HammerConfig provides configuration for a stress/load test.
type HammerConfig struct {
// Configuration for the log.
LogCfg *configpb.LogConfig
// How to create process-wide metrics.
MetricFactory monitoring.MetricFactory
// Maximum merge delay.
MMD time.Duration
// Certificate chain generator.
ChainGenerator ChainGenerator
// ClientPool provides the clients used to make requests.
ClientPool ClientPool
// Bias values to favor particular log operations.
EPBias HammerBias
// Range of how many entries to get.
MinGetEntries, MaxGetEntries int
// OversizedGetEntries governs whether get-entries requests that go beyond the
// current tree size are allowed (with a truncated response expected).
OversizedGetEntries bool
// Number of operations to perform.
Operations uint64
// Rate limiter
Limiter Limiter
// MaxParallelChains sets the upper limit for the number of parallel
// add-*-chain requests to make when the biasing model says to perform an add.
MaxParallelChains int
// EmitInterval defines how frequently stats are logged.
EmitInterval time.Duration
// IgnoreErrors controls whether a hammer run fails immediately on any error.
IgnoreErrors bool
// MaxRetryDuration governs how long to keep retrying when IgnoreErrors is true.
MaxRetryDuration time.Duration
// RequestDeadline indicates the deadline to set on each request to the log.
RequestDeadline time.Duration
// DuplicateChance sets the probability of attempting to add a duplicate when
// calling add[-pre]-chain (as the N in 1-in-N). Set to 0 to disable sending
// duplicates.
DuplicateChance int
// StrictSTHConsistencySize if set to true will cause Hammer to only request
// STH consistency proofs between tree sizes for which it's seen valid STHs.
// If set to false, Hammer will request a consistency proof between the
// current tree size, and a random smaller size greater than zero.
StrictSTHConsistencySize bool
}
// HammerBias indicates the bias for selecting different log operations.
type HammerBias struct {
Bias map[ctfe.EntrypointName]int
total int
// InvalidChance gives the odds of performing an invalid operation, as the N in 1-in-N.
InvalidChance map[ctfe.EntrypointName]int
}
// Choose randomly picks an operation to perform according to the biases.
func (hb HammerBias) Choose() ctfe.EntrypointName {
if hb.total == 0 {
for _, ep := range ctfe.Entrypoints {
hb.total += hb.Bias[ep]
}
}
which := rand.Intn(hb.total)
for _, ep := range ctfe.Entrypoints {
which -= hb.Bias[ep]
if which < 0 {
return ep
}
}
panic("random choice out of range")
}
// Invalid randomly chooses whether an operation should be invalid.
func (hb HammerBias) Invalid(ep ctfe.EntrypointName) bool {
chance := hb.InvalidChance[ep]
if chance <= 0 {
return false
}
return rand.Intn(chance) == 0
}
type submittedCert struct {
leafData []byte
leafHash [sha256.Size]byte
sct *ct.SignedCertificateTimestamp
integrateBy time.Time
precert bool
}
// pendingCerts holds certificates that have been submitted that we want
// to check inclusion proofs for. The array is ordered from oldest to
// most recent, but new entries are only appended when enough time has
// passed since the last append, so the SCTs that get checked are spread
// out across the MMD period.
type pendingCerts struct {
mu sync.Mutex
certs [sctCount]*submittedCert
}
func (pc *pendingCerts) empty() bool {
pc.mu.Lock()
defer pc.mu.Unlock()
return pc.certs[0] == nil
}
// tryAppendCert locks mu, checks whether it's possible to append the cert, and
// appends it if so.
func (pc *pendingCerts) tryAppendCert(now time.Time, mmd time.Duration, submitted *submittedCert) {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.canAppend(now, mmd) {
which := 0
for ; which < sctCount; which++ {
if pc.certs[which] == nil {
break
}
}
pc.certs[which] = submitted
}
}
// canAppend checks whether a pending cert can be appended.
// It must be called with mu locked.
func (pc *pendingCerts) canAppend(now time.Time, mmd time.Duration) bool {
if pc.certs[sctCount-1] != nil {
return false // full already
}
if pc.certs[0] == nil {
return true // nothing yet
}
// Only allow append if enough time has passed, namely MMD/#savedSCTs.
last := sctCount - 1
for ; last >= 0; last-- {
if pc.certs[last] != nil {
break
}
}
lastTime := timeFromMS(pc.certs[last].sct.Timestamp)
nextTime := lastTime.Add(mmd / sctCount)
return now.After(nextTime)
}
// oldestIfMMDPassed returns the oldest submitted certificate if the maximum
// merge delay has passed, i.e. it is expected to be integrated as of now. This
// function locks mu.
func (pc *pendingCerts) oldestIfMMDPassed(now time.Time) *submittedCert {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.certs[0] == nil {
return nil
}
submitted := pc.certs[0]
if !now.After(submitted.integrateBy) {
// Oldest cert not due to be integrated yet, so neither will any others.
return nil
}
return submitted
}
// dropOldest removes the oldest submitted certificate.
func (pc *pendingCerts) dropOldest() {
pc.mu.Lock()
defer pc.mu.Unlock()
// Can pop the oldest cert and shuffle the others along, which make room for
// another cert to be stored.
for i := 0; i < (sctCount - 1); i++ {
pc.certs[i] = pc.certs[i+1]
}
pc.certs[sctCount-1] = nil
}
// hammerState tracks the operations that have been performed during a test run, including
// earlier SCTs/STHs for later checking.
type hammerState struct {
cfg *HammerConfig
// Store the first submitted and the most recently submitted [pre-]chain,
// to allow submission of both old and new duplicates.
chainMu sync.Mutex
firstChain, lastChain []ct.ASN1Cert
firstChainIntegrated time.Time
firstPreChain, lastPreChain []ct.ASN1Cert
firstPreChainIntegrated time.Time
firstTBS, lastTBS []byte
mu sync.RWMutex
// STHs are arranged from later to earlier (so [0] is the most recent), and the
// discovery of new STHs will push older ones off the end.
sth [sthCount]*ct.SignedTreeHead
// Submitted certs also run from later to earlier, but the discovery of new SCTs
// does not affect the existing contents of the array, so if the array is full it
// keeps the same elements. Instead, the oldest entry is removed (and a space
// created) when we are able to get an inclusion proof for it.
pending pendingCerts
// Operations that are required to fix dependencies.
nextOp []ctfe.EntrypointName
hasher merkle.LogHasher
}
func newHammerState(cfg *HammerConfig) (*hammerState, error) {
mf := cfg.MetricFactory
if mf == nil {
mf = monitoring.InertMetricFactory{}
}
once.Do(func() { setupMetrics(mf) })
if cfg.MinGetEntries <= 0 {
cfg.MinGetEntries = 1
}
if cfg.MaxGetEntries <= cfg.MinGetEntries {
cfg.MaxGetEntries = cfg.MinGetEntries + 300
}
if cfg.EmitInterval <= 0 {
cfg.EmitInterval = 10 * time.Second
}
if cfg.Limiter == nil {
cfg.Limiter = unLimited{}
}
if cfg.MaxRetryDuration <= 0 {
cfg.MaxRetryDuration = 60 * time.Second
}
if cfg.LogCfg.IsMirror {
klog.Warningf("%v: disabling add-[pre-]chain for mirror log", cfg.LogCfg.Prefix)
cfg.EPBias.Bias[ctfe.AddChainName] = 0
cfg.EPBias.Bias[ctfe.AddPreChainName] = 0
}
state := hammerState{
cfg: cfg,
nextOp: make([]ctfe.EntrypointName, 0),
hasher: rfc6962.DefaultHasher,
}
return &state, nil
}
func (s *hammerState) client() *client.LogClient {
return s.cfg.ClientPool.Next()
}
func (s *hammerState) lastTreeSize() uint64 {
if s.sth[0] == nil {
return 0
}
return s.sth[0].TreeSize
}
func (s *hammerState) needOps(ops ...ctfe.EntrypointName) {
klog.V(2).Infof("need operations %+v to satisfy dependencies", ops)
s.nextOp = append(s.nextOp, ops...)
}
// addMultiple calls the passed in function a random number
// (1 <= n < MaxParallelChains) of times.
// The first of any errors returned by calls to addOne will be returned by this function.
func (s *hammerState) addMultiple(ctx context.Context, addOne func(context.Context) error) error {
var wg sync.WaitGroup
numAdds := rand.Intn(s.cfg.MaxParallelChains) + 1
klog.V(2).Infof("%s: do %d parallel add operations...", s.cfg.LogCfg.Prefix, numAdds)
errs := make(chan error, numAdds)
for i := 0; i < numAdds; i++ {
wg.Add(1)
go func() {
if err := addOne(ctx); err != nil {
errs <- err
}
wg.Done()
}()
}
wg.Wait()
klog.V(2).Infof("%s: do %d parallel add operations...done", s.cfg.LogCfg.Prefix, numAdds)
select {
case err := <-errs:
return err
default:
}
return nil
}
func (s *hammerState) getChain() (Choice, []ct.ASN1Cert, error) {
s.chainMu.Lock()
defer s.chainMu.Unlock()
choice := s.chooseCertToAdd()
// Override choice if necessary
if s.lastChain == nil {
choice = NewCert
}
if choice == FirstCert && time.Now().Before(s.firstChainIntegrated) {
choice = NewCert
}
switch choice {
case NewCert:
chain, err := s.cfg.ChainGenerator.CertChain()
if err != nil {
return choice, nil, fmt.Errorf("failed to make fresh cert: %v", err)
}
if s.firstChain == nil {
s.firstChain = chain
s.firstChainIntegrated = time.Now().Add(s.cfg.MMD)
}
s.lastChain = chain
return choice, chain, nil
case FirstCert:
return choice, s.firstChain, nil
case LastCert:
return choice, s.lastChain, nil
}
return choice, nil, fmt.Errorf("unhandled choice %s", choice)
}
func (s *hammerState) addChain(ctx context.Context) error {
choice, chain, err := s.getChain()
if err != nil {
return fmt.Errorf("failed to make chain (%s): %v", choice, err)
}
sct, err := s.client().AddChain(ctx, chain)
if err != nil {
if err, ok := err.(client.RspError); ok {
klog.Errorf("%s: add-chain(%s): error %v HTTP status %d body %s", s.cfg.LogCfg.Prefix, choice, err.Error(), err.StatusCode, err.Body)
}
return fmt.Errorf("failed to add-chain(%s): %v", choice, err)
}
klog.V(2).Infof("%s: Uploaded %s cert, got SCT(time=%q)", s.cfg.LogCfg.Prefix, choice, timeFromMS(sct.Timestamp))
// Calculate leaf hash = SHA256(0x00 | tls-encode(MerkleTreeLeaf))
submitted := submittedCert{precert: false, sct: sct}
leaf := ct.MerkleTreeLeaf{
Version: ct.V1,
LeafType: ct.TimestampedEntryLeafType,
TimestampedEntry: &ct.TimestampedEntry{
Timestamp: sct.Timestamp,
EntryType: ct.X509LogEntryType,
X509Entry: &(chain[0]),
Extensions: sct.Extensions,
},
}
submitted.integrateBy = timeFromMS(sct.Timestamp).Add(s.cfg.MMD)
submitted.leafData, err = tls.Marshal(leaf)
if err != nil {
return fmt.Errorf("failed to tls.Marshal leaf cert: %v", err)
}
submitted.leafHash = sha256.Sum256(append([]byte{ct.TreeLeafPrefix}, submitted.leafData...))
s.pending.tryAppendCert(time.Now(), s.cfg.MMD, &submitted)
klog.V(3).Infof("%s: Uploaded %s cert has leaf-hash %x", s.cfg.LogCfg.Prefix, choice, submitted.leafHash)
return nil
}
func (s *hammerState) addChainInvalid(ctx context.Context) error {
choices := []Choice{EmptyChain, PrecertNotCert, NoChainToRoot, UnparsableCert}
choice := choices[rand.Intn(len(choices))]
var err error
var chain []ct.ASN1Cert
switch choice {
case EmptyChain:
case PrecertNotCert:
chain, _, err = s.cfg.ChainGenerator.PreCertChain()
if err != nil {
return fmt.Errorf("failed to make chain(%s): %v", choice, err)
}
case NoChainToRoot:
chain, err = s.cfg.ChainGenerator.CertChain()
if err != nil {
return fmt.Errorf("failed to make chain(%s): %v", choice, err)
}
// Drop the intermediate (chain[1]).
chain = append(chain[:1], chain[2:]...)
case UnparsableCert:
chain, err = s.cfg.ChainGenerator.CertChain()
if err != nil {
return fmt.Errorf("failed to make chain(%s): %v", choice, err)
}
// Remove the initial ASN.1 SEQUENCE type byte (0x30) to make an unparsable cert.
chain[0].Data[0] = 0x00
default:
klog.Exitf("Unhandled choice %s", choice)
}
sct, err := s.client().AddChain(ctx, chain)
klog.V(3).Infof("invalid add-chain(%s) => error %v", choice, err)
if err, ok := err.(client.RspError); ok {
klog.V(3).Infof(" HTTP status %d body %s", err.StatusCode, err.Body)
}
if err == nil {
return fmt.Errorf("unexpected success: add-chain(%s): %+v", choice, sct)
}
return nil
}
// chooseCertToAdd determines whether to add a new or pre-existing cert.
func (s *hammerState) chooseCertToAdd() Choice {
if s.cfg.DuplicateChance > 0 && rand.Intn(s.cfg.DuplicateChance) == 0 {
// TODO(drysdale): restore LastCert as an option
return FirstCert
}
return NewCert
}
func (s *hammerState) getPreChain() (Choice, []ct.ASN1Cert, []byte, error) {
s.chainMu.Lock()
defer s.chainMu.Unlock()
choice := s.chooseCertToAdd()
// Override choice if necessary
if s.lastPreChain == nil {
choice = NewCert
}
if choice == FirstCert && time.Now().Before(s.firstPreChainIntegrated) {
choice = NewCert
}
switch choice {
case NewCert:
prechain, tbs, err := s.cfg.ChainGenerator.PreCertChain()
if err != nil {
return choice, nil, nil, fmt.Errorf("failed to make fresh pre-cert: %v", err)
}
if s.firstPreChain == nil {
s.firstPreChain = prechain
s.firstPreChainIntegrated = time.Now().Add(s.cfg.MMD)
s.firstTBS = tbs
}
s.lastPreChain = prechain
s.lastTBS = tbs
return choice, prechain, tbs, nil
case FirstCert:
return choice, s.firstPreChain, s.firstTBS, nil
case LastCert:
return choice, s.lastPreChain, s.lastTBS, nil
}
return choice, nil, nil, fmt.Errorf("unhandled choice %s", choice)
}
func (s *hammerState) addPreChain(ctx context.Context) error {
choice, prechain, tbs, err := s.getPreChain()
if err != nil {
return fmt.Errorf("failed to make pre-cert chain (%s): %v", choice, err)
}
issuer, err := x509.ParseCertificate(prechain[1].Data)
if err != nil {
return fmt.Errorf("failed to parse pre-cert issuer: %v", err)
}
sct, err := s.client().AddPreChain(ctx, prechain)
if err != nil {
if err, ok := err.(client.RspError); ok {
klog.Errorf("%s: add-pre-chain(%s): error %v HTTP status %d body %s", s.cfg.LogCfg.Prefix, choice, err.Error(), err.StatusCode, err.Body)
}
return fmt.Errorf("failed to add-pre-chain: %v", err)
}
klog.V(2).Infof("%s: Uploaded %s pre-cert, got SCT(time=%q)", s.cfg.LogCfg.Prefix, choice, timeFromMS(sct.Timestamp))
// Calculate leaf hash = SHA256(0x00 | tls-encode(MerkleTreeLeaf))
submitted := submittedCert{precert: true, sct: sct}
leaf := ct.MerkleTreeLeaf{
Version: ct.V1,
LeafType: ct.TimestampedEntryLeafType,
TimestampedEntry: &ct.TimestampedEntry{
Timestamp: sct.Timestamp,
EntryType: ct.PrecertLogEntryType,
PrecertEntry: &ct.PreCert{
IssuerKeyHash: sha256.Sum256(issuer.RawSubjectPublicKeyInfo),
TBSCertificate: tbs,
},
Extensions: sct.Extensions,
},
}
submitted.integrateBy = timeFromMS(sct.Timestamp).Add(s.cfg.MMD)
submitted.leafData, err = tls.Marshal(leaf)
if err != nil {
return fmt.Errorf("tls.Marshal(precertLeaf)=(nil,%v); want (_,nil)", err)
}
submitted.leafHash = sha256.Sum256(append([]byte{ct.TreeLeafPrefix}, submitted.leafData...))
s.pending.tryAppendCert(time.Now(), s.cfg.MMD, &submitted)
klog.V(3).Infof("%s: Uploaded %s pre-cert has leaf-hash %x", s.cfg.LogCfg.Prefix, choice, submitted.leafHash)
return nil
}
func (s *hammerState) addPreChainInvalid(ctx context.Context) error {
choices := []Choice{EmptyChain, CertNotPrecert, NoChainToRoot, UnparsableCert}
choice := choices[rand.Intn(len(choices))]
var err error
var prechain []ct.ASN1Cert
switch choice {
case EmptyChain:
case CertNotPrecert:
prechain, err = s.cfg.ChainGenerator.CertChain()
if err != nil {
return fmt.Errorf("failed to make pre-chain(%s): %v", choice, err)
}
case NoChainToRoot:
prechain, _, err = s.cfg.ChainGenerator.PreCertChain()
if err != nil {
return fmt.Errorf("failed to make pre-chain(%s): %v", choice, err)
}
// Drop the intermediate (prechain[1]).
prechain = append(prechain[:1], prechain[2:]...)
case UnparsableCert:
prechain, _, err = s.cfg.ChainGenerator.PreCertChain()
if err != nil {
return fmt.Errorf("failed to make pre-chain(%s): %v", choice, err)
}
// Remove the initial ASN.1 SEQUENCE type byte (0x30) to make an unparsable cert.
prechain[0].Data[0] = 0x00
default:
klog.Exitf("Unhandled choice %s", choice)
}
sct, err := s.client().AddPreChain(ctx, prechain)
klog.V(3).Infof("invalid add-pre-chain(%s) => error %v", choice, err)
if err, ok := err.(client.RspError); ok {
klog.V(3).Infof(" HTTP status %d body %s", err.StatusCode, err.Body)
}
if err == nil {
return fmt.Errorf("unexpected success: add-pre-chain: %+v", sct)
}
return nil
}
func (s *hammerState) getSTH(ctx context.Context) error {
// Shuffle earlier STHs along.
for i := sthCount - 1; i > 0; i-- {
s.sth[i] = s.sth[i-1]
}
var err error
s.sth[0], err = s.client().GetSTH(ctx)
if err != nil {
return fmt.Errorf("failed to get-sth: %v", err)
}
klog.V(2).Infof("%s: Got STH(time=%q, size=%d)", s.cfg.LogCfg.Prefix, timeFromMS(s.sth[0].Timestamp), s.sth[0].TreeSize)
return nil
}
// chooseSTHs gets the current STH, and also picks an earlier STH.
func (s *hammerState) chooseSTHs(ctx context.Context) (*ct.SignedTreeHead, *ct.SignedTreeHead, error) {
// Get current size, and pick an earlier size
sthNow, err := s.client().GetSTH(ctx)
if err != nil {
return nil, nil, fmt.Errorf("failed to get-sth for current tree: %v", err)
}
which := rand.Intn(sthCount)
if s.sth[which] == nil {
klog.V(3).Infof("%s: skipping get-sth-consistency as no earlier STH", s.cfg.LogCfg.Prefix)
s.needOps(ctfe.GetSTHName)
return nil, sthNow, errSkip{}
}
if s.sth[which].TreeSize == 0 {
klog.V(3).Infof("%s: skipping get-sth-consistency as no earlier STH", s.cfg.LogCfg.Prefix)
s.needOps(ctfe.AddChainName, ctfe.GetSTHName)
return nil, sthNow, errSkip{}
}
if s.sth[which].TreeSize == sthNow.TreeSize {
klog.V(3).Infof("%s: skipping get-sth-consistency as same size (%d)", s.cfg.LogCfg.Prefix, sthNow.TreeSize)
s.needOps(ctfe.AddChainName, ctfe.GetSTHName)
return nil, sthNow, errSkip{}
}
return s.sth[which], sthNow, nil
}
func (s *hammerState) getSTHConsistency(ctx context.Context) error {
sthOld, sthNow, err := s.chooseSTHs(ctx)
if err != nil {
// bail on actual errors
if _, ok := err.(errSkip); !ok {
return err
}
// If we're being asked to skip, it's because we don't have an earlier STH,
// if the config says we must only use "known" STHs then we'll have to wait
// until we get a larger STH.
if s.cfg.StrictSTHConsistencySize {
return err
}
// Otherwise, let's use our imagination and make one up, if possible...
if sthNow.TreeSize < 2 {
klog.V(3).Infof("%s: current STH size too small to invent a smaller STH for consistency proof (%d)", s.cfg.LogCfg.Prefix, sthNow.TreeSize)
return errSkip{}
}
sthOld = &ct.SignedTreeHead{TreeSize: uint64(1 + rand.Int63n(int64(sthNow.TreeSize)))}
klog.V(3).Infof("%s: Inventing a smaller STH size for consistency proof (%d)", s.cfg.LogCfg.Prefix, sthOld.TreeSize)
}
proof, err := s.client().GetSTHConsistency(ctx, sthOld.TreeSize, sthNow.TreeSize)
if err != nil {
return fmt.Errorf("failed to get-sth-consistency(%d, %d): %v", sthOld.TreeSize, sthNow.TreeSize, err)
}
if sthOld.Timestamp == 0 {
klog.V(3).Infof("%s: Skipping consistency proof verification for invented STH", s.cfg.LogCfg.Prefix)
return nil
}
if err := s.checkCTConsistencyProof(sthOld, sthNow, proof); err != nil {
return fmt.Errorf("get-sth-consistency(%d, %d) proof check failed: %v", sthOld.TreeSize, sthNow.TreeSize, err)
}
klog.V(2).Infof("%s: Got STH consistency proof (size=%d => %d) len %d",
s.cfg.LogCfg.Prefix, sthOld.TreeSize, sthNow.TreeSize, len(proof))
return nil
}
func (s *hammerState) getSTHConsistencyInvalid(ctx context.Context) error {
lastSize := s.lastTreeSize()
if lastSize == 0 {
return errSkip{}
}
choices := []Choice{ParamTooBig, ParamsInverted, ParamNegative, ParamInvalid}
choice := choices[rand.Intn(len(choices))]
var err error
var proof [][]byte
switch choice {
case ParamTooBig:
first := lastSize + uint64(invalidStretch)
second := first + 100
proof, err = s.client().GetSTHConsistency(ctx, first, second)
case Param2TooBig:
first := lastSize
second := lastSize + uint64(invalidStretch)
proof, err = s.client().GetSTHConsistency(ctx, first, second)
case ParamsInverted:
var sthOld, sthNow *ct.SignedTreeHead
sthOld, sthNow, err = s.chooseSTHs(ctx)
if err != nil {
return err
}
proof, err = s.client().GetSTHConsistency(ctx, sthNow.TreeSize, sthOld.TreeSize)
case ParamNegative, ParamInvalid:
params := make(map[string]string)
switch choice {
case ParamNegative:
params["first"] = "-3"
params["second"] = "-1"
case ParamInvalid:
params["first"] = "foo"
params["second"] = "bar"
}
// Need to use lower-level API to be able to use invalid parameters
var resp ct.GetSTHConsistencyResponse
var httpRsp *http.Response
var body []byte
httpRsp, body, err = s.client().GetAndParse(ctx, ct.GetSTHConsistencyPath, params, &resp)
if err != nil && httpRsp != nil {
err = client.RspError{Err: err, StatusCode: httpRsp.StatusCode, Body: body}
}
proof = resp.Consistency
default:
klog.Exitf("Unhandled choice %s", choice)
}
klog.V(3).Infof("invalid get-sth-consistency(%s) => error %v", choice, err)
if err, ok := err.(client.RspError); ok {
klog.V(3).Infof(" HTTP status %d body %s", err.StatusCode, err.Body)
}
if err == nil {
return fmt.Errorf("unexpected success: get-sth-consistency(%s): %+v", choice, proof)
}
return nil
}
func (s *hammerState) getProofByHash(ctx context.Context) error {
submitted := s.pending.oldestIfMMDPassed(time.Now())
if submitted == nil {
// No SCT that is guaranteed to be integrated, so move on.
return errSkip{}
}
// Get an STH that should include this submitted [pre-]cert.
sth, err := s.client().GetSTH(ctx)
if err != nil {
return fmt.Errorf("failed to get-sth for proof: %v", err)
}
// Get and check an inclusion proof.
rsp, err := s.client().GetProofByHash(ctx, submitted.leafHash[:], sth.TreeSize)
if err != nil {
return fmt.Errorf("failed to get-proof-by-hash(size=%d) on cert with SCT @ %v: %v, %+v", sth.TreeSize, timeFromMS(submitted.sct.Timestamp), err, rsp)
}
if err := proof.VerifyInclusion(s.hasher, uint64(rsp.LeafIndex), sth.TreeSize, submitted.leafHash[:], rsp.AuditPath, sth.SHA256RootHash[:]); err != nil {
return fmt.Errorf("failed to VerifyInclusion(%d, %d)=%v", rsp.LeafIndex, sth.TreeSize, err)
}
s.pending.dropOldest()
return nil
}
func (s *hammerState) getProofByHashInvalid(ctx context.Context) error {
lastSize := s.lastTreeSize()
if lastSize == 0 {
return errSkip{}
}
submitted := s.pending.oldestIfMMDPassed(time.Now())
choices := []Choice{ParamInvalid, ParamTooBig, ParamNegative, InvalidBase64}
choice := choices[rand.Intn(len(choices))]
var err error
var rsp *ct.GetProofByHashResponse
switch choice {
case ParamInvalid:
rsp, err = s.client().GetProofByHash(ctx, []byte{0x01, 0x02}, 1) // Hash too short
case ParamTooBig:
if submitted == nil {
return errSkip{}
}
rsp, err = s.client().GetProofByHash(ctx, submitted.leafHash[:], lastSize+uint64(invalidStretch))
case ParamNegative, InvalidBase64:
params := make(map[string]string)
switch choice {
case ParamNegative:
if submitted == nil {
return errSkip{}
}
params["tree_size"] = "-1"
params["hash"] = base64.StdEncoding.EncodeToString(submitted.leafHash[:])
case InvalidBase64:
params["tree_size"] = "1"
params["hash"] = "@^()"
}
var r ct.GetProofByHashResponse
rsp = &r
var httpRsp *http.Response
var body []byte
httpRsp, body, err = s.client().GetAndParse(ctx, ct.GetProofByHashPath, params, &r)
if err != nil && httpRsp != nil {
err = client.RspError{Err: err, StatusCode: httpRsp.StatusCode, Body: body}
}
default:
klog.Exitf("Unhandled choice %s", choice)
}
klog.V(3).Infof("invalid get-proof-by-hash(%s) => error %v", choice, err)
if err, ok := err.(client.RspError); ok {
klog.V(3).Infof(" HTTP status %d body %s", err.StatusCode, err.Body)
}
if err == nil {
return fmt.Errorf("unexpected success: get-proof-by-hash(%s): %+v", choice, rsp)
}
return nil
}
func (s *hammerState) getEntries(ctx context.Context) error {
if s.sth[0] == nil {
klog.V(3).Infof("%s: skipping get-entries as no earlier STH", s.cfg.LogCfg.Prefix)
s.needOps(ctfe.GetSTHName)
return errSkip{}
}
lastSize := s.lastTreeSize()
if lastSize == 0 {
if s.pending.empty() {
klog.V(3).Infof("%s: skipping get-entries as tree size 0", s.cfg.LogCfg.Prefix)
s.needOps(ctfe.AddChainName, ctfe.GetSTHName)
return errSkip{}
}
klog.V(3).Infof("%s: skipping get-entries as STH stale", s.cfg.LogCfg.Prefix)
s.needOps(ctfe.GetSTHName)
return errSkip{}
}
// Entry indices are zero-based, and may or may not be allowed to extend
// beyond current tree size (RFC 6962 s4.6).
first := rand.Intn(int(lastSize))
span := s.cfg.MaxGetEntries - s.cfg.MinGetEntries
count := s.cfg.MinGetEntries + rand.Intn(int(span))
last := first + count
if !s.cfg.OversizedGetEntries && last >= int(lastSize) {
last = int(lastSize) - 1
}
entries, err := s.client().GetEntries(ctx, int64(first), int64(last))
if err != nil {
return fmt.Errorf("failed to get-entries(%d,%d): %v", first, last, err)
}
for i, entry := range entries {
if want := int64(first + i); entry.Index != want {
return fmt.Errorf("leaf[%d].LeafIndex=%d; want %d", i, entry.Index, want)
}
leaf := entry.Leaf
if leaf.Version != 0 {
return fmt.Errorf("leaf[%d].Version=%v; want V1(0)", i, leaf.Version)
}
if leaf.LeafType != ct.TimestampedEntryLeafType {
return fmt.Errorf("leaf[%d].Version=%v; want TimestampedEntryLeafType", i, leaf.LeafType)
}
ts := leaf.TimestampedEntry
if ts.EntryType != ct.X509LogEntryType && ts.EntryType != ct.PrecertLogEntryType {
return fmt.Errorf("leaf[%d].ts.EntryType=%v; want {X509,Precert}LogEntryType", i, ts.EntryType)
}
}
klog.V(2).Infof("%s: Got entries [%d:%d)\n", s.cfg.LogCfg.Prefix, first, first+len(entries))
return nil
}
func (s *hammerState) getEntriesInvalid(ctx context.Context) error {
lastSize := s.lastTreeSize()
if lastSize == 0 {
return errSkip{}
}
choices := []Choice{ParamTooBig, ParamNegative, ParamsInverted}
choice := choices[rand.Intn(len(choices))]
var first, last int64
switch choice {
case ParamTooBig:
last = int64(lastSize) + invalidStretch
first = last - 4
case ParamNegative:
first = -2
last = 10
case ParamsInverted:
first = 10
last = 5
default:
klog.Exitf("Unhandled choice %s", choice)
}
entries, err := s.client().GetEntries(ctx, first, last)
klog.V(3).Infof("invalid get-entries(%s) => error %v", choice, err)
if err, ok := err.(client.RspError); ok {
klog.V(3).Infof(" HTTP status %d body %s", err.StatusCode, err.Body)
}
if err == nil {
return fmt.Errorf("unexpected success: get-entries(%d,%d): %d entries", first, last, len(entries))
}
return nil
}
func (s *hammerState) getRoots(ctx context.Context) error {
roots, err := s.client().GetAcceptedRoots(ctx)
if err != nil {
return fmt.Errorf("failed to get-roots: %v", err)
}
klog.V(2).Infof("%s: Got roots (len=%d)", s.cfg.LogCfg.Prefix, len(roots))
return nil
}
func sthSize(sth *ct.SignedTreeHead) string {
if sth == nil {
return "n/a"
}
return fmt.Sprintf("%d", sth.TreeSize)
}
func (s *hammerState) label() string {
return strconv.FormatInt(s.cfg.LogCfg.LogId, 10)
}
func (s *hammerState) String() string {
s.mu.RLock()
defer s.mu.RUnlock()
details := ""
statusOK := strconv.Itoa(http.StatusOK)
totalReqs := 0
totalInvalidReqs := 0
totalErrs := 0
for _, ep := range ctfe.Entrypoints {
reqCount := int(reqs.Value(s.label(), string(ep)))
totalReqs += reqCount
if s.cfg.EPBias.Bias[ep] > 0 {
details += fmt.Sprintf(" %s=%d/%d", ep, int(rsps.Value(s.label(), string(ep), statusOK)), reqCount)
}
totalInvalidReqs += int(invalidReqs.Value(s.label(), string(ep)))
totalErrs += int(errs.Value(s.label(), string(ep)))
}
return fmt.Sprintf("%10s: lastSTH.size=%s ops: total=%d invalid=%d errs=%v%s", s.cfg.LogCfg.Prefix, sthSize(s.sth[0]), totalReqs, totalInvalidReqs, totalErrs, details)
}
func (s *hammerState) performOp(ctx context.Context, ep ctfe.EntrypointName) (int, error) {
if err := s.cfg.Limiter.Wait(ctx); err != nil {
return http.StatusRequestTimeout, fmt.Errorf("Limiter.Wait(): %v", err)
}
s.mu.Lock()
defer s.mu.Unlock()
if s.cfg.RequestDeadline > 0 {
cctx, cancel := context.WithTimeout(ctx, s.cfg.RequestDeadline)
defer cancel()
ctx = cctx
}
status := http.StatusOK
var err error
switch ep {
case ctfe.AddChainName:
err = s.addMultiple(ctx, s.addChain)
case ctfe.AddPreChainName:
err = s.addMultiple(ctx, s.addPreChain)
case ctfe.GetSTHName:
err = s.getSTH(ctx)
case ctfe.GetSTHConsistencyName:
err = s.getSTHConsistency(ctx)
case ctfe.GetProofByHashName:
err = s.getProofByHash(ctx)
case ctfe.GetEntriesName:
err = s.getEntries(ctx)
case ctfe.GetRootsName:
err = s.getRoots(ctx)
case ctfe.GetEntryAndProofName:
status = http.StatusNotImplemented
klog.V(2).Infof("%s: hammering entrypoint %s not yet implemented", s.cfg.LogCfg.Prefix, ep)
default:
err = fmt.Errorf("internal error: unknown entrypoint %s selected", ep)
}
return status, err
}
func (s *hammerState) performInvalidOp(ctx context.Context, ep ctfe.EntrypointName) error {
if err := s.cfg.Limiter.Wait(ctx); err != nil {
return fmt.Errorf("Limiter.Wait(): %v", err)
}
switch ep {
case ctfe.AddChainName:
return s.addChainInvalid(ctx)
case ctfe.AddPreChainName:
return s.addPreChainInvalid(ctx)
case ctfe.GetSTHConsistencyName:
return s.getSTHConsistencyInvalid(ctx)
case ctfe.GetProofByHashName:
return s.getProofByHashInvalid(ctx)
case ctfe.GetEntriesName:
return s.getEntriesInvalid(ctx)
case ctfe.GetSTHName, ctfe.GetRootsName:
return fmt.Errorf("no invalid request possible for entrypoint %s", ep)
case ctfe.GetEntryAndProofName:
return fmt.Errorf("hammering entrypoint %s not yet implemented", ep)
}
return fmt.Errorf("internal error: unknown entrypoint %s", ep)
}
func (s *hammerState) chooseOp() (ctfe.EntrypointName, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.nextOp) > 0 {
ep := s.nextOp[0]
s.nextOp = s.nextOp[1:]
if s.cfg.EPBias.Bias[ep] > 0 {
return ep, false
}
}
ep := s.cfg.EPBias.Choose()
return ep, s.cfg.EPBias.Invalid(ep)
}
// Perform a random operation on the log, retrying if necessary. If non-empty, the
// returned entrypoint should be performed next to unblock dependencies.
func (s *hammerState) retryOneOp(ctx context.Context) error {
ep, invalid := s.chooseOp()
if invalid {
klog.V(3).Infof("perform invalid %s operation", ep)
invalidReqs.Inc(s.label(), string(ep))
err := s.performInvalidOp(ctx, ep)
if _, ok := err.(errSkip); ok {
klog.V(2).Infof("invalid operation %s was skipped", ep)
return nil
}
return err
}
klog.V(3).Infof("perform %s operation", ep)
deadline := time.Now().Add(s.cfg.MaxRetryDuration)
for {
if err := ctx.Err(); err != nil {
return err
}
start := time.Now()
reqs.Inc(s.label(), string(ep))
status, err := s.performOp(ctx, ep)
period := time.Since(start)
rspLatency.Observe(period.Seconds(), s.label(), string(ep), strconv.Itoa(status))
switch err.(type) {
case nil:
rsps.Inc(s.label(), string(ep), strconv.Itoa(status))
return nil
case errSkip:
klog.V(2).Infof("operation %s was skipped", ep)
return nil
default:
errs.Inc(s.label(), string(ep))
if s.cfg.IgnoreErrors {
left := time.Until(deadline)
if left < 0 {
klog.Warningf("%s: gave up retrying failed op %v after %v, returning last err: %v", s.cfg.LogCfg.Prefix, ep, s.cfg.MaxRetryDuration, err)
return err
}
klog.Warningf("%s: op %v failed after %v (will retry for %v more): %v", s.cfg.LogCfg.Prefix, ep, period, left, err)
} else {
return err
}
}
}
}
// checkCTConsistencyProof checks the given consistency proof.
func (s *hammerState) checkCTConsistencyProof(sth1, sth2 *ct.SignedTreeHead, pf [][]byte) error {
return proof.VerifyConsistency(s.hasher, sth1.TreeSize, sth2.TreeSize, pf, sth1.SHA256RootHash[:], sth2.SHA256RootHash[:])
}
// HammerCTLog performs load/stress operations according to given config.
func HammerCTLog(ctx context.Context, cfg HammerConfig) error {
s, err := newHammerState(&cfg)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go schedule.Every(ctx, cfg.EmitInterval, func(ctx context.Context) {
klog.Info(s.String())
})
for count := uint64(1); count < cfg.Operations; count++ {
if err := s.retryOneOp(ctx); err != nil {
return err
}
// Terminate from the loop if the context is cancelled.
if err := ctx.Err(); err != nil {
return err
}
}
klog.Infof("%s: completed %d operations on log", cfg.LogCfg.Prefix, cfg.Operations)
return nil
}
|