| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package config |
| 18 | |
| 19 | import ( |
| 20 | "crypto/x509" |
| 21 | "errors" |
| 22 | "fmt" |
| 23 | "io/ioutil" |
| 24 | "strings" |
| 25 | |
| 26 | "gopkg.in/yaml.v3" |
| 27 | |
| 28 | "github.com/sassoftware/relic/v7/lib/certloader" |
| 29 | ) |
| 30 | |
| 31 | const ( |
| 32 | defaultSigXchg = "relic.signatures" |
| 33 | sigKey = "relic.signatures" |
| 34 | ) |
| 35 | |
| 36 | var ( |
| 37 | // these are set by main |
| 38 | Version = "unknown" |
| 39 | Commit = "unknown" |
| 40 | Author = "SAS Institute Inc." |
| 41 | UserAgent = "relic/" + Version |
| 42 | ) |
| 43 | |
| 44 | type TokenConfig struct { |
| 45 | Type string // Provider type: file or pkcs11 (default) |
| 46 | Provider string // Path to PKCS#11 provider module (required) |
| 47 | Label string // Select a token by label |
| 48 | Serial string // Select a token by serial number |
| 49 | Pin *string // PIN to use, otherwise will be prompted. Can be empty. (optional) |
| 50 | Timeout int // (server) Terminate command after N seconds (default 60) |
| 51 | Retries int // (server) Retry failed commands N times (default 5) |
| 52 | RateLimit float64 // (server) limit token operations per second |
| 53 | RateBurst int // (server) allow burst of operations before limit kicks in |
| 54 | User *uint // User argument for PKCS#11 login (optional) |
| 55 | UseKeyring bool // Read PIN from system keyring |
| 56 | |
| 57 | name string |
| 58 | } |
| 59 | |
| 60 | type KeyConfig struct { |
| 61 | Token string // Token section to use for this key (linux) |
| 62 | Alias string // This is an alias for another key |
| 63 | Label string // Select a key by label |
| 64 | ID string // Select a key by ID (hex notation) |
| 65 | PgpCertificate string // Path to PGP certificate associated with this key |
| 66 | X509Certificate string // Path to X.509 certificate associated with this key |
| 67 | KeyFile string // For "file" tokens, path to the private key |
| 68 | IsPkcs12 bool // If true, key file contains PKCS#12 key and certificate chain |
| 69 | Roles []string // List of user roles that can use this key |
| 70 | Timestamp bool // If true, attach a timestamped countersignature when possible |
| 71 | Hide bool // If true, then omit this key from 'remote list-keys' |
| 72 | |
| 73 | name string |
| 74 | token *TokenConfig |
| 75 | } |
| 76 | |
| 77 | type ServerConfig struct { |
| 78 | Listen string // Port to listen for TLS connections |
| 79 | ListenHTTP string // Port to listen for plaintext connections |
| 80 | KeyFile string // Path to TLS key file |
| 81 | CertFile string // Path to TLS certificate chain |
| 82 | LogFile string // Optional error log |
| 83 | LogLevel string // Optional log level |
| 84 | PolicyURL string // Optional open-policy-agent endpoint |
| 85 | |
| 86 | Disabled bool // Always return 503 Service Unavailable |
| 87 | ListenDebug bool // Serve debug info on an alternate port |
| 88 | ListenMetrics string // Port to listen for plaintext metrics |
| 89 | NumWorkers int // Number of worker subprocesses per configured token |
| 90 | |
| 91 | TokenCheckInterval int |
| 92 | TokenCheckFailures int |
| 93 | TokenCheckTimeout int |
| 94 | TokenCacheSeconds int |
| 95 | |
| 96 | ReadHeaderTimeout int |
| 97 | ReadTimeout int |
| 98 | WriteTimeout int |
| 99 | |
| 100 | // URLs to all servers in the cluster. If a client uses DirectoryURL to |
| 101 | // point to this server (or a load balancer), then we will give them these |
| 102 | // URLs as a means to distribute load without needing a middle-box. |
| 103 | Siblings []string |
| 104 | |
| 105 | // IP networks of trusted reverse proxies that can front this service |
| 106 | TrustedProxies []string |
| 107 | |
| 108 | AzureAD *ServerAzureConfig |
| 109 | } |
| 110 | |
| 111 | type ServerAzureConfig struct { |
| 112 | Authority string |
| 113 | ClientID string |
| 114 | Scopes []string |
| 115 | } |
| 116 | |
| 117 | type ClientConfig struct { |
| 118 | Nickname string // Name that appears in audit log entries |
| 119 | Roles []string // List of roles that this client possesses |
| 120 | Certificate string // Optional CA certificate(s) that sign client certs instead of using fingerprint-based auth |
| 121 | |
| 122 | certs *x509.CertPool |
| 123 | } |
| 124 | |
| 125 | type RemoteConfig struct { |
| 126 | URL string `yaml:",omitempty"` // URL of remote server |
| 127 | DirectoryURL string `yaml:",omitempty"` // URL of directory server |
| 128 | KeyFile string `yaml:",omitempty"` // Path to TLS client key file |
| 129 | CertFile string `yaml:",omitempty"` // Path to TLS client certificate or embedded certificate |
| 130 | CaCert string `yaml:",omitempty"` // Path to CA certificate or embedded certificate |
| 131 | ConnectTimeout int `yaml:",omitempty"` // Connection timeout in seconds |
| 132 | Retries int `yaml:",omitempty"` // Attempt an operation (at least) N times |
| 133 | |
| 134 | AccessToken string `yaml:"-"` |
| 135 | Interactive bool |
| 136 | } |
| 137 | |
| 138 | type TimestampConfig struct { |
| 139 | URLs []string // List of timestamp server URLs |
| 140 | MsURLs []string // List of microsoft-style URLs |
| 141 | Timeout int // Connect timeout in seconds |
| 142 | CaCert string // Path to CA certificate |
| 143 | Memcache []string // host:port of memcached to use for caching timestamps |
| 144 | RateLimit float64 // limit timestamp requests per second |
| 145 | RateBurst int // allow burst of requests before limit kicks in |
| 146 | } |
| 147 | |
| 148 | type AmqpConfig struct { |
| 149 | URL string // AMQP URL to report signatures to i.e. amqp://user:password@host |
| 150 | CaCert string |
| 151 | KeyFile string |
| 152 | CertFile string |
| 153 | SigsXchg string // Name of exchange to send to (default relic.signatures) |
| 154 | } |
| 155 | |
| 156 | type Config struct { |
| 157 | Tokens map[string]*TokenConfig `yaml:",omitempty"` |
| 158 | Keys map[string]*KeyConfig `yaml:",omitempty"` |
| 159 | Server *ServerConfig `yaml:",omitempty"` |
| 160 | Clients map[string]*ClientConfig `yaml:",omitempty"` |
| 161 | Remote *RemoteConfig `yaml:",omitempty"` |
| 162 | Timestamp *TimestampConfig `yaml:",omitempty"` |
| 163 | Amqp *AmqpConfig `yaml:",omitempty"` |
| 164 | |
| 165 | PinFile string `yaml:",omitempty"` // Optional YAML file with additional token PINs |
| 166 | |
| 167 | path string |
| 168 | } |
| 169 | |
| 170 | func ReadFile(path string) (*Config, error) { |
| 171 | data, err := ioutil.ReadFile(path) |
| 172 | if err != nil { |
| 173 | return nil, err |
| 174 | } |
| 175 | config := new(Config) |
| 176 | err = yaml.Unmarshal(data, config) |
| 177 | if err != nil { |
| 178 | return nil, err |
| 179 | } |
| 180 | return config, config.Normalize(path) |
| 181 | } |
| 182 | |
| 183 | func (config *Config) Normalize(path string) error { |
| 184 | config.path = path |
| 185 | normalized := make(map[string]*ClientConfig) |
| 186 | for fingerprint, client := range config.Clients { |
| 187 | if client.Certificate != "" { |
| 188 | certs, err := certloader.ParseX509Certificates([]byte(client.Certificate)) |
| 189 | if err != nil { |
| 190 | return fmt.Errorf("invalid certificate for client %s: %w", fingerprint, err) |
| 191 | } |
| 192 | client.certs = x509.NewCertPool() |
| 193 | for _, cert := range certs { |
| 194 | client.certs.AddCert(cert) |
| 195 | } |
| 196 | } else if len(fingerprint) != 64 { |
| 197 | return errors.New("Client keys must be hex-encoded SHA256 digests of the public key") |
| 198 | } |
| 199 | lower := strings.ToLower(fingerprint) |
| 200 | normalized[lower] = client |
| 201 | } |
| 202 | config.Clients = normalized |
| 203 | if config.PinFile != "" { |
| 204 | contents, err := ioutil.ReadFile(config.PinFile) |
| 205 | if err != nil { |
| 206 | return fmt.Errorf("reading PinFile: %w", err) |
| 207 | } |
| 208 | pinMap := make(map[string]string) |
| 209 | if err := yaml.Unmarshal(contents, pinMap); err != nil { |
| 210 | return fmt.Errorf("reading PinFile: %w", err) |
| 211 | } |
| 212 | for token, pin := range pinMap { |
| 213 | tokenConf := config.Tokens[token] |
| 214 | if tokenConf != nil { |
| 215 | ppin := pin |
| 216 | tokenConf.Pin = &ppin |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | for tokenName, tokenConf := range config.Tokens { |
| 221 | tokenConf.name = tokenName |
| 222 | if tokenConf.Type == "" { |
| 223 | tokenConf.Type = "pkcs11" |
| 224 | } |
| 225 | } |
| 226 | for keyName, keyConf := range config.Keys { |
| 227 | keyConf.name = keyName |
| 228 | if keyConf.Token != "" { |
| 229 | keyConf.token = config.Tokens[keyConf.Token] |
| 230 | } |
| 231 | } |
| 232 | if s := config.Server; s != nil { |
| 233 | if s.TokenCheckInterval == 0 { |
| 234 | s.TokenCheckInterval = 60 |
| 235 | } |
| 236 | if s.TokenCheckTimeout == 0 { |
| 237 | s.TokenCheckTimeout = 60 |
| 238 | } |
| 239 | if s.TokenCheckFailures == 0 { |
| 240 | s.TokenCheckFailures = 3 |
| 241 | } |
| 242 | if s.TokenCacheSeconds == 0 { |
| 243 | s.TokenCacheSeconds = 600 |
| 244 | } |
| 245 | if s.ReadHeaderTimeout == 0 { |
| 246 | s.ReadHeaderTimeout = 10 |
| 247 | } |
| 248 | if s.ReadTimeout == 0 { |
| 249 | s.ReadTimeout = 600 |
| 250 | } |
| 251 | if s.WriteTimeout == 0 { |
| 252 | s.WriteTimeout = 600 |
| 253 | } |
| 254 | } |
| 255 | if r := config.Remote; r != nil { |
| 256 | if r.ConnectTimeout == 0 { |
| 257 | r.ConnectTimeout = 15 |
| 258 | } |
| 259 | if r.Retries == 0 { |
| 260 | r.Retries = 3 |
| 261 | } |
| 262 | } |
| 263 | return nil |
| 264 | } |
| 265 | |
| 266 | func (config *Config) GetToken(tokenName string) (*TokenConfig, error) { |
| 267 | if config.Tokens == nil { |
| 268 | return nil, errors.New("No tokens defined in configuration") |
| 269 | } |
| 270 | tokenConf, ok := config.Tokens[tokenName] |
| 271 | if !ok { |
| 272 | return nil, fmt.Errorf("Token \"%s\" not found in configuration", tokenName) |
| 273 | } |
| 274 | return tokenConf, nil |
| 275 | } |
| 276 | |
| 277 | func (config *Config) NewToken(name string) *TokenConfig { |
| 278 | if config.Tokens == nil { |
| 279 | config.Tokens = make(map[string]*TokenConfig) |
| 280 | } |
| 281 | tok := &TokenConfig{name: name} |
| 282 | config.Tokens[name] = tok |
| 283 | return tok |
| 284 | } |
| 285 | |
| 286 | func (config *Config) GetKey(keyName string) (*KeyConfig, error) { |
| 287 | keyConf, ok := config.Keys[keyName] |
| 288 | if !ok { |
| 289 | return nil, fmt.Errorf("Key \"%s\" not found in configuration", keyName) |
| 290 | } else if keyConf.Alias != "" { |
| 291 | keyConf, ok = config.Keys[keyConf.Alias] |
| 292 | if !ok { |
| 293 | return nil, fmt.Errorf("Alias \"%s\" points to undefined key \"%s\"", keyName, keyConf.Alias) |
| 294 | } |
| 295 | } |
| 296 | if keyConf.Token == "" { |
| 297 | return nil, fmt.Errorf("Key \"%s\" does not specify required value 'token'", keyName) |
| 298 | } |
| 299 | return keyConf, nil |
| 300 | } |
| 301 | |
| 302 | func (config *Config) NewKey(name string) *KeyConfig { |
| 303 | if config.Keys == nil { |
| 304 | config.Keys = make(map[string]*KeyConfig) |
| 305 | } |
| 306 | key := &KeyConfig{name: name} |
| 307 | config.Keys[name] = key |
| 308 | return key |
| 309 | } |
| 310 | |
| 311 | func (config *Config) Path() string { |
| 312 | return config.path |
| 313 | } |
| 314 | |
| 315 | func (config *Config) GetTimestampConfig() (*TimestampConfig, error) { |
| 316 | tconf := config.Timestamp |
| 317 | if tconf == nil { |
| 318 | return nil, errors.New("No timestamp section exists in the configuration") |
| 319 | } |
| 320 | return tconf, nil |
| 321 | } |
| 322 | |
| 323 | // ListServedTokens returns a list of token names that are accessible by at least one role |
| 324 | func (config *Config) ListServedTokens() []string { |
| 325 | names := make(map[string]bool) |
| 326 | for _, key := range config.Keys { |
| 327 | if len(key.Roles) != 0 { |
| 328 | names[key.Token] = true |
| 329 | } |
| 330 | } |
| 331 | ret := make([]string, 0, len(names)) |
| 332 | for name := range names { |
| 333 | ret = append(ret, name) |
| 334 | } |
| 335 | return ret |
| 336 | } |
| 337 | |
| 338 | func (tconf *TokenConfig) Name() string { |
| 339 | return tconf.name |
| 340 | } |
| 341 | |
| 342 | func (aconf *AmqpConfig) ExchangeName() string { |
| 343 | if aconf.SigsXchg != "" { |
| 344 | return aconf.SigsXchg |
| 345 | } |
| 346 | return defaultSigXchg |
| 347 | } |
| 348 | |
| 349 | func (aconf *AmqpConfig) RoutingKey() string { |
| 350 | return sigKey |
| 351 | } |