|
| 1 | +// Copyright 2016 Google LLC. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// The ct_server binary runs the CT personality. |
| 16 | +package main |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "crypto/x509" |
| 21 | + "encoding/pem" |
| 22 | + "flag" |
| 23 | + "fmt" |
| 24 | + "net/http" |
| 25 | + "os" |
| 26 | + "os/signal" |
| 27 | + "strings" |
| 28 | + "sync" |
| 29 | + "syscall" |
| 30 | + "time" |
| 31 | + |
| 32 | + "github.com/go-sql-driver/mysql" |
| 33 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 34 | + sctfe "github.com/transparency-dev/static-ct" |
| 35 | + "github.com/transparency-dev/static-ct/internal/testdata" |
| 36 | + "github.com/transparency-dev/static-ct/storage" |
| 37 | + awsSCTFE "github.com/transparency-dev/static-ct/storage/aws" |
| 38 | + "github.com/transparency-dev/static-ct/storage/bbolt" |
| 39 | + tessera "github.com/transparency-dev/trillian-tessera" |
| 40 | + awsTessera "github.com/transparency-dev/trillian-tessera/storage/aws" |
| 41 | + "golang.org/x/mod/sumdb/note" |
| 42 | + "k8s.io/klog/v2" |
| 43 | +) |
| 44 | + |
| 45 | +func init() { |
| 46 | + flag.Var(¬AfterStart, "not_after_start", "Start of the range of acceptable NotAfter values, inclusive. Leaving this unset implies no lower bound to the range. RFC3339 UTC format, e.g: 2024-01-02T15:04:05Z.") |
| 47 | + flag.Var(¬AfterLimit, "not_after_limit", "Cut off point of notAfter dates - only notAfter dates strictly *before* notAfterLimit will be accepted. Leaving this unset means no upper bound on the accepted range. RFC3339 UTC format, e.g: 2024-01-02T15:04:05Z.") |
| 48 | +} |
| 49 | + |
| 50 | +// Global flags that affect all log instances. |
| 51 | +var ( |
| 52 | + notAfterStart timestampFlag |
| 53 | + notAfterLimit timestampFlag |
| 54 | + |
| 55 | + httpEndpoint = flag.String("http_endpoint", "localhost:6962", "Endpoint for HTTP (host:port).") |
| 56 | + metricsEndpoint = flag.String("metrics_endpoint", "", "Endpoint for serving metrics; if left empty, metrics will be visible on --http_endpoint.") |
| 57 | + httpDeadline = flag.Duration("http_deadline", time.Second*10, "Deadline for HTTP requests.") |
| 58 | + maskInternalErrors = flag.Bool("mask_internal_errors", false, "Don't return error strings with Internal Server Error HTTP responses.") |
| 59 | + origin = flag.String("origin", "", "Origin of the log, for checkpoints and the monitoring prefix.") |
| 60 | + bucket = flag.String("bucket", "", "Name of the bucket to store the log in.") |
| 61 | + dbName = flag.String("db_name", "", "AuroraDB name") |
| 62 | + dbHost = flag.String("db_host", "", "AuroraDB host") |
| 63 | + dbPort = flag.Int("db_port", 3306, "AuroraDB port") |
| 64 | + dbUser = flag.String("db_user", "", "AuroraDB user") |
| 65 | + dbPassword = flag.String("db_password", "", "AuroraDB password") |
| 66 | + dbMaxConns = flag.Int("db_max_conns", 0, "Maximum connections to the database, defaults to 0, i.e unlimited") |
| 67 | + dbMaxIdle = flag.Int("db_max_idle_conns", 2, "Maximum idle database connections in the connection pool, defaults to 2") |
| 68 | + dedupPath = flag.String("dedup_path", "", "Path to the deduplication database.") |
| 69 | + rootsPemFile = flag.String("roots_pem_file", "", "Path to the file containing root certificates that are acceptable to the log. The certs are served through get-roots endpoint.") |
| 70 | + rejectExpired = flag.Bool("reject_expired", false, "If true then the certificate validity period will be checked against the current time during the validation of submissions. This will cause expired certificates to be rejected.") |
| 71 | + rejectUnexpired = flag.Bool("reject_unexpired", false, "If true then CTFE rejects certificates that are either currently valid or not yet valid.") |
| 72 | + extKeyUsages = flag.String("ext_key_usages", "", "If set, will restrict the set of such usages that the server will accept. By default all are accepted. The values specified must be ones known to the x509 package.") |
| 73 | + rejectExtensions = flag.String("reject_extension", "", "A list of X.509 extension OIDs, in dotted string form (e.g. '2.3.4.5') which, if present, should cause submissions to be rejected.") |
| 74 | +) |
| 75 | + |
| 76 | +// nolint:staticcheck |
| 77 | +func main() { |
| 78 | + klog.InitFlags(nil) |
| 79 | + flag.Parse() |
| 80 | + ctx := context.Background() |
| 81 | + |
| 82 | + // TODO: Replace the fake signer with AWS Secrets Manager Signer. |
| 83 | + block, _ := pem.Decode([]byte(testdata.DemoPublicKey)) |
| 84 | + key, err := x509.ParsePKIXPublicKey(block.Bytes) |
| 85 | + if err != nil { |
| 86 | + klog.Exitf("Can't parse public key: %v", err) |
| 87 | + } |
| 88 | + fakeSigner := testdata.NewSignerWithFixedSig(key, []byte("sig")) |
| 89 | + |
| 90 | + chainValidationConfig := sctfe.ChainValidationConfig{ |
| 91 | + RootsPEMFile: *rootsPemFile, |
| 92 | + RejectExpired: *rejectExpired, |
| 93 | + RejectUnexpired: *rejectUnexpired, |
| 94 | + ExtKeyUsages: *extKeyUsages, |
| 95 | + RejectExtensions: *rejectExtensions, |
| 96 | + NotAfterStart: notAfterStart.t, |
| 97 | + NotAfterLimit: notAfterLimit.t, |
| 98 | + } |
| 99 | + |
| 100 | + logHandler, err := sctfe.NewLogHandler(ctx, *origin, fakeSigner, chainValidationConfig, newAWSStorage, *httpDeadline, *maskInternalErrors) |
| 101 | + if err != nil { |
| 102 | + klog.Exitf("Can't initialize CT HTTP Server: %v", err) |
| 103 | + } |
| 104 | + |
| 105 | + klog.CopyStandardLogTo("WARNING") |
| 106 | + klog.Info("**** CT HTTP Server Starting ****") |
| 107 | + http.Handle("/", logHandler) |
| 108 | + |
| 109 | + metricsAt := *metricsEndpoint |
| 110 | + if metricsAt == "" { |
| 111 | + metricsAt = *httpEndpoint |
| 112 | + } |
| 113 | + |
| 114 | + if metricsAt != *httpEndpoint { |
| 115 | + // Run a separate handler for metrics. |
| 116 | + go func() { |
| 117 | + mux := http.NewServeMux() |
| 118 | + mux.Handle("/metrics", promhttp.Handler()) |
| 119 | + metricsServer := http.Server{Addr: metricsAt, Handler: mux} |
| 120 | + err := metricsServer.ListenAndServe() |
| 121 | + klog.Warningf("Metrics server exited: %v", err) |
| 122 | + }() |
| 123 | + } else { |
| 124 | + // Handle metrics on the DefaultServeMux. |
| 125 | + http.Handle("/metrics", promhttp.Handler()) |
| 126 | + } |
| 127 | + |
| 128 | + // Bring up the HTTP server and serve until we get a signal not to. |
| 129 | + srv := http.Server{Addr: *httpEndpoint} |
| 130 | + shutdownWG := new(sync.WaitGroup) |
| 131 | + go awaitSignal(func() { |
| 132 | + shutdownWG.Add(1) |
| 133 | + defer shutdownWG.Done() |
| 134 | + // Allow 60s for any pending requests to finish then terminate any stragglers |
| 135 | + // TODO(phboneff): maybe wait for the sequencer queue to be empty? |
| 136 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) |
| 137 | + defer cancel() |
| 138 | + klog.Info("Shutting down HTTP server...") |
| 139 | + if err := srv.Shutdown(ctx); err != nil { |
| 140 | + klog.Errorf("srv.Shutdown(): %v", err) |
| 141 | + } |
| 142 | + klog.Info("HTTP server shutdown") |
| 143 | + }) |
| 144 | + |
| 145 | + if err := srv.ListenAndServe(); err != http.ErrServerClosed { |
| 146 | + klog.Warningf("Server exited: %v", err) |
| 147 | + } |
| 148 | + // Wait will only block if the function passed to awaitSignal was called, |
| 149 | + // in which case it'll block until the HTTP server has gracefully shutdown |
| 150 | + shutdownWG.Wait() |
| 151 | + klog.Flush() |
| 152 | +} |
| 153 | + |
| 154 | +// awaitSignal waits for standard termination signals, then runs the given |
| 155 | +// function; it should be run as a separate goroutine. |
| 156 | +func awaitSignal(doneFn func()) { |
| 157 | + // Arrange notification for the standard set of signals used to terminate a server |
| 158 | + sigs := make(chan os.Signal, 1) |
| 159 | + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) |
| 160 | + |
| 161 | + // Now block main and wait for a signal |
| 162 | + sig := <-sigs |
| 163 | + klog.Warningf("Signal received: %v", sig) |
| 164 | + klog.Flush() |
| 165 | + |
| 166 | + doneFn() |
| 167 | +} |
| 168 | + |
| 169 | +func newAWSStorage(ctx context.Context, signer note.Signer) (*storage.CTStorage, error) { |
| 170 | + awsCfg := storageConfigFromFlags() |
| 171 | + driver, err := awsTessera.New(ctx, awsCfg) |
| 172 | + if err != nil { |
| 173 | + return nil, fmt.Errorf("failed to initialize AWS Tessera storage driver: %v", err) |
| 174 | + } |
| 175 | + appender, _, _, err := tessera.NewAppender(ctx, driver, tessera.NewAppendOptions(). |
| 176 | + WithCheckpointSigner(signer). |
| 177 | + WithCTLayout()) |
| 178 | + if err != nil { |
| 179 | + return nil, fmt.Errorf("failed to initialize AWS Tessera storage: %v", err) |
| 180 | + } |
| 181 | + |
| 182 | + issuerStorage, err := awsSCTFE.NewIssuerStorage(ctx, *bucket, "fingerprints/", "application/pkix-cert") |
| 183 | + if err != nil { |
| 184 | + return nil, fmt.Errorf("failed to initialize AWS issuer storage: %v", err) |
| 185 | + } |
| 186 | + |
| 187 | + beDedupStorage, err := bbolt.NewStorage(*dedupPath) |
| 188 | + if err != nil { |
| 189 | + return nil, fmt.Errorf("failed to initialize BBolt deduplication database: %v", err) |
| 190 | + } |
| 191 | + |
| 192 | + return storage.NewCTStorage(appender, issuerStorage, beDedupStorage) |
| 193 | +} |
| 194 | + |
| 195 | +type timestampFlag struct { |
| 196 | + t *time.Time |
| 197 | +} |
| 198 | + |
| 199 | +func (t *timestampFlag) String() string { |
| 200 | + if t.t != nil { |
| 201 | + return t.t.Format(time.RFC3339) |
| 202 | + } |
| 203 | + return "" |
| 204 | +} |
| 205 | + |
| 206 | +func (t *timestampFlag) Set(w string) error { |
| 207 | + if !strings.HasSuffix(w, "Z") { |
| 208 | + return fmt.Errorf("timestamps MUST be in UTC, got %v", w) |
| 209 | + } |
| 210 | + tt, err := time.Parse(time.RFC3339, w) |
| 211 | + if err != nil { |
| 212 | + return fmt.Errorf("can't parse %q as RFC3339 timestamp: %v", w, err) |
| 213 | + } |
| 214 | + t.t = &tt |
| 215 | + return nil |
| 216 | +} |
| 217 | + |
| 218 | +// storageConfigFromFlags returns an aws.Config struct populated with values |
| 219 | +// provided via flags. |
| 220 | +func storageConfigFromFlags() awsTessera.Config { |
| 221 | + if *bucket == "" { |
| 222 | + klog.Exit("--bucket must be set") |
| 223 | + } |
| 224 | + if *dbName == "" { |
| 225 | + klog.Exit("--db_name must be set") |
| 226 | + } |
| 227 | + if *dbHost == "" { |
| 228 | + klog.Exit("--db_host must be set") |
| 229 | + } |
| 230 | + if *dbPort == 0 { |
| 231 | + klog.Exit("--db_port must be set") |
| 232 | + } |
| 233 | + if *dbUser == "" { |
| 234 | + klog.Exit("--db_user must be set") |
| 235 | + } |
| 236 | + // Empty passord isn't an option with AuroraDB MySQL. |
| 237 | + if *dbPassword == "" { |
| 238 | + klog.Exit("--db_password must be set") |
| 239 | + } |
| 240 | + |
| 241 | + c := mysql.Config{ |
| 242 | + User: *dbUser, |
| 243 | + Passwd: *dbPassword, |
| 244 | + Net: "tcp", |
| 245 | + Addr: fmt.Sprintf("%s:%d", *dbHost, *dbPort), |
| 246 | + DBName: *dbName, |
| 247 | + AllowCleartextPasswords: true, |
| 248 | + AllowNativePasswords: true, |
| 249 | + } |
| 250 | + |
| 251 | + return awsTessera.Config{ |
| 252 | + Bucket: *bucket, |
| 253 | + DSN: c.FormatDSN(), |
| 254 | + MaxOpenConns: *dbMaxConns, |
| 255 | + MaxIdleConns: *dbMaxIdle, |
| 256 | + } |
| 257 | +} |
0 commit comments