github.com/rawahars/moby@v24.0.4+incompatible/daemon/config/config.go (about) 1 package config // import "github.com/docker/docker/daemon/config" 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "net" 8 "net/url" 9 "os" 10 "path/filepath" 11 "strings" 12 "sync" 13 14 "golang.org/x/text/encoding" 15 "golang.org/x/text/encoding/unicode" 16 "golang.org/x/text/transform" 17 18 "github.com/containerd/containerd/runtime/v2/shim" 19 "github.com/docker/docker/opts" 20 "github.com/docker/docker/registry" 21 "github.com/imdario/mergo" 22 "github.com/pkg/errors" 23 "github.com/sirupsen/logrus" 24 "github.com/spf13/pflag" 25 ) 26 27 const ( 28 // DefaultMaxConcurrentDownloads is the default value for 29 // maximum number of downloads that 30 // may take place at a time. 31 DefaultMaxConcurrentDownloads = 3 32 // DefaultMaxConcurrentUploads is the default value for 33 // maximum number of uploads that 34 // may take place at a time. 35 DefaultMaxConcurrentUploads = 5 36 // DefaultDownloadAttempts is the default value for 37 // maximum number of attempts that 38 // may take place at a time for each pull when the connection is lost. 39 DefaultDownloadAttempts = 5 40 // DefaultShmSize is the default value for container's shm size (64 MiB) 41 DefaultShmSize int64 = 64 * 1024 * 1024 42 // DefaultNetworkMtu is the default value for network MTU 43 DefaultNetworkMtu = 1500 44 // DisableNetworkBridge is the default value of the option to disable network bridge 45 DisableNetworkBridge = "none" 46 // DefaultShutdownTimeout is the default shutdown timeout (in seconds) for 47 // the daemon for containers to stop when it is shutting down. 48 DefaultShutdownTimeout = 15 49 // DefaultInitBinary is the name of the default init binary 50 DefaultInitBinary = "docker-init" 51 // DefaultRuntimeBinary is the default runtime to be used by 52 // containerd if none is specified 53 DefaultRuntimeBinary = "runc" 54 // DefaultContainersNamespace is the name of the default containerd namespace used for users containers. 55 DefaultContainersNamespace = "moby" 56 // DefaultPluginNamespace is the name of the default containerd namespace used for plugins. 57 DefaultPluginNamespace = "plugins.moby" 58 59 // LinuxV2RuntimeName is the runtime used to specify the containerd v2 runc shim 60 LinuxV2RuntimeName = "io.containerd.runc.v2" 61 62 // SeccompProfileDefault is the built-in default seccomp profile. 63 SeccompProfileDefault = "builtin" 64 // SeccompProfileUnconfined is a special profile name for seccomp to use an 65 // "unconfined" seccomp profile. 66 SeccompProfileUnconfined = "unconfined" 67 ) 68 69 var builtinRuntimes = map[string]bool{ 70 StockRuntimeName: true, 71 LinuxV2RuntimeName: true, 72 } 73 74 // flatOptions contains configuration keys 75 // that MUST NOT be parsed as deep structures. 76 // Use this to differentiate these options 77 // with others like the ones in TLSOptions. 78 var flatOptions = map[string]bool{ 79 "cluster-store-opts": true, 80 "default-network-opts": true, 81 "log-opts": true, 82 "runtimes": true, 83 "default-ulimits": true, 84 "features": true, 85 "builder": true, 86 } 87 88 // skipValidateOptions contains configuration keys 89 // that will be skipped from findConfigurationConflicts 90 // for unknown flag validation. 91 var skipValidateOptions = map[string]bool{ 92 "features": true, 93 "builder": true, 94 // Corresponding flag has been removed because it was already unusable 95 "deprecated-key-path": true, 96 } 97 98 // skipDuplicates contains configuration keys that 99 // will be skipped when checking duplicated 100 // configuration field defined in both daemon 101 // config file and from dockerd cli flags. 102 // This allows some configurations to be merged 103 // during the parsing. 104 var skipDuplicates = map[string]bool{ 105 "runtimes": true, 106 } 107 108 // LogConfig represents the default log configuration. 109 // It includes json tags to deserialize configuration from a file 110 // using the same names that the flags in the command line use. 111 type LogConfig struct { 112 Type string `json:"log-driver,omitempty"` 113 Config map[string]string `json:"log-opts,omitempty"` 114 } 115 116 // commonBridgeConfig stores all the platform-common bridge driver specific 117 // configuration. 118 type commonBridgeConfig struct { 119 Iface string `json:"bridge,omitempty"` 120 FixedCIDR string `json:"fixed-cidr,omitempty"` 121 } 122 123 // NetworkConfig stores the daemon-wide networking configurations 124 type NetworkConfig struct { 125 // Default address pools for docker networks 126 DefaultAddressPools opts.PoolsOpt `json:"default-address-pools,omitempty"` 127 // NetworkControlPlaneMTU allows to specify the control plane MTU, this will allow to optimize the network use in some components 128 NetworkControlPlaneMTU int `json:"network-control-plane-mtu,omitempty"` 129 // Default options for newly created networks 130 DefaultNetworkOpts map[string]map[string]string `json:"default-network-opts,omitempty"` 131 } 132 133 // TLSOptions defines TLS configuration for the daemon server. 134 // It includes json tags to deserialize configuration from a file 135 // using the same names that the flags in the command line use. 136 type TLSOptions struct { 137 CAFile string `json:"tlscacert,omitempty"` 138 CertFile string `json:"tlscert,omitempty"` 139 KeyFile string `json:"tlskey,omitempty"` 140 } 141 142 // DNSConfig defines the DNS configurations. 143 type DNSConfig struct { 144 DNS []string `json:"dns,omitempty"` 145 DNSOptions []string `json:"dns-opts,omitempty"` 146 DNSSearch []string `json:"dns-search,omitempty"` 147 HostGatewayIP net.IP `json:"host-gateway-ip,omitempty"` 148 } 149 150 // CommonConfig defines the configuration of a docker daemon which is 151 // common across platforms. 152 // It includes json tags to deserialize configuration from a file 153 // using the same names that the flags in the command line use. 154 type CommonConfig struct { 155 AuthorizationPlugins []string `json:"authorization-plugins,omitempty"` // AuthorizationPlugins holds list of authorization plugins 156 AutoRestart bool `json:"-"` 157 Context map[string][]string `json:"-"` 158 DisableBridge bool `json:"-"` 159 ExecOptions []string `json:"exec-opts,omitempty"` 160 GraphDriver string `json:"storage-driver,omitempty"` 161 GraphOptions []string `json:"storage-opts,omitempty"` 162 Labels []string `json:"labels,omitempty"` 163 Mtu int `json:"mtu,omitempty"` 164 NetworkDiagnosticPort int `json:"network-diagnostic-port,omitempty"` 165 Pidfile string `json:"pidfile,omitempty"` 166 RawLogs bool `json:"raw-logs,omitempty"` 167 Root string `json:"data-root,omitempty"` 168 ExecRoot string `json:"exec-root,omitempty"` 169 SocketGroup string `json:"group,omitempty"` 170 CorsHeaders string `json:"api-cors-header,omitempty"` 171 172 // Proxies holds the proxies that are configured for the daemon. 173 Proxies `json:"proxies"` 174 175 // LiveRestoreEnabled determines whether we should keep containers 176 // alive upon daemon shutdown/start 177 LiveRestoreEnabled bool `json:"live-restore,omitempty"` 178 179 // MaxConcurrentDownloads is the maximum number of downloads that 180 // may take place at a time for each pull. 181 MaxConcurrentDownloads int `json:"max-concurrent-downloads,omitempty"` 182 183 // MaxConcurrentUploads is the maximum number of uploads that 184 // may take place at a time for each push. 185 MaxConcurrentUploads int `json:"max-concurrent-uploads,omitempty"` 186 187 // MaxDownloadAttempts is the maximum number of attempts that 188 // may take place at a time for each push. 189 MaxDownloadAttempts int `json:"max-download-attempts,omitempty"` 190 191 // ShutdownTimeout is the timeout value (in seconds) the daemon will wait for the container 192 // to stop when daemon is being shutdown 193 ShutdownTimeout int `json:"shutdown-timeout,omitempty"` 194 195 Debug bool `json:"debug,omitempty"` 196 Hosts []string `json:"hosts,omitempty"` 197 LogLevel string `json:"log-level,omitempty"` 198 TLS *bool `json:"tls,omitempty"` 199 TLSVerify *bool `json:"tlsverify,omitempty"` 200 201 // Embedded structs that allow config 202 // deserialization without the full struct. 203 TLSOptions 204 205 // SwarmDefaultAdvertiseAddr is the default host/IP or network interface 206 // to use if a wildcard address is specified in the ListenAddr value 207 // given to the /swarm/init endpoint and no advertise address is 208 // specified. 209 SwarmDefaultAdvertiseAddr string `json:"swarm-default-advertise-addr"` 210 211 // SwarmRaftHeartbeatTick is the number of ticks in time for swarm mode raft quorum heartbeat 212 // Typical value is 1 213 SwarmRaftHeartbeatTick uint32 `json:"swarm-raft-heartbeat-tick"` 214 215 // SwarmRaftElectionTick is the number of ticks to elapse before followers in the quorum can propose 216 // a new round of leader election. Default, recommended value is at least 10X that of Heartbeat tick. 217 // Higher values can make the quorum less sensitive to transient faults in the environment, but this also 218 // means it takes longer for the managers to detect a down leader. 219 SwarmRaftElectionTick uint32 `json:"swarm-raft-election-tick"` 220 221 MetricsAddress string `json:"metrics-addr"` 222 223 DNSConfig 224 LogConfig 225 BridgeConfig // BridgeConfig holds bridge network specific configuration. 226 NetworkConfig 227 registry.ServiceOptions 228 229 sync.Mutex 230 // FIXME(vdemeester) This part is not that clear and is mainly dependent on cli flags 231 // It should probably be handled outside this package. 232 ValuesSet map[string]interface{} `json:"-"` 233 234 Experimental bool `json:"experimental"` // Experimental indicates whether experimental features should be exposed or not 235 236 // Exposed node Generic Resources 237 // e.g: ["orange=red", "orange=green", "orange=blue", "apple=3"] 238 NodeGenericResources []string `json:"node-generic-resources,omitempty"` 239 240 // ContainerAddr is the address used to connect to containerd if we're 241 // not starting it ourselves 242 ContainerdAddr string `json:"containerd,omitempty"` 243 244 // CriContainerd determines whether a supervised containerd instance 245 // should be configured with the CRI plugin enabled. This allows using 246 // Docker's containerd instance directly with a Kubernetes kubelet. 247 CriContainerd bool `json:"cri-containerd,omitempty"` 248 249 // Features contains a list of feature key value pairs indicating what features are enabled or disabled. 250 // If a certain feature doesn't appear in this list then it's unset (i.e. neither true nor false). 251 Features map[string]bool `json:"features,omitempty"` 252 253 Builder BuilderConfig `json:"builder,omitempty"` 254 255 ContainerdNamespace string `json:"containerd-namespace,omitempty"` 256 ContainerdPluginNamespace string `json:"containerd-plugin-namespace,omitempty"` 257 258 DefaultRuntime string `json:"default-runtime,omitempty"` 259 } 260 261 // Proxies holds the proxies that are configured for the daemon. 262 type Proxies struct { 263 HTTPProxy string `json:"http-proxy,omitempty"` 264 HTTPSProxy string `json:"https-proxy,omitempty"` 265 NoProxy string `json:"no-proxy,omitempty"` 266 } 267 268 // IsValueSet returns true if a configuration value 269 // was explicitly set in the configuration file. 270 func (conf *Config) IsValueSet(name string) bool { 271 if conf.ValuesSet == nil { 272 return false 273 } 274 _, ok := conf.ValuesSet[name] 275 return ok 276 } 277 278 // New returns a new fully initialized Config struct with default values set. 279 func New() (*Config, error) { 280 // platform-agnostic default values for the Config. 281 cfg := &Config{ 282 CommonConfig: CommonConfig{ 283 ShutdownTimeout: DefaultShutdownTimeout, 284 LogConfig: LogConfig{ 285 Config: make(map[string]string), 286 }, 287 MaxConcurrentDownloads: DefaultMaxConcurrentDownloads, 288 MaxConcurrentUploads: DefaultMaxConcurrentUploads, 289 MaxDownloadAttempts: DefaultDownloadAttempts, 290 Mtu: DefaultNetworkMtu, 291 NetworkConfig: NetworkConfig{ 292 NetworkControlPlaneMTU: DefaultNetworkMtu, 293 DefaultNetworkOpts: make(map[string]map[string]string), 294 }, 295 ContainerdNamespace: DefaultContainersNamespace, 296 ContainerdPluginNamespace: DefaultPluginNamespace, 297 DefaultRuntime: StockRuntimeName, 298 }, 299 } 300 301 if err := setPlatformDefaults(cfg); err != nil { 302 return nil, err 303 } 304 305 return cfg, nil 306 } 307 308 // GetConflictFreeLabels validates Labels for conflict 309 // In swarm the duplicates for labels are removed 310 // so we only take same values here, no conflict values 311 // If the key-value is the same we will only take the last label 312 func GetConflictFreeLabels(labels []string) ([]string, error) { 313 labelMap := map[string]string{} 314 for _, label := range labels { 315 key, val, ok := strings.Cut(label, "=") 316 if ok { 317 // If there is a conflict we will return an error 318 if v, ok := labelMap[key]; ok && v != val { 319 return nil, errors.Errorf("conflict labels for %s=%s and %s=%s", key, val, key, v) 320 } 321 labelMap[key] = val 322 } 323 } 324 325 newLabels := []string{} 326 for k, v := range labelMap { 327 newLabels = append(newLabels, k+"="+v) 328 } 329 return newLabels, nil 330 } 331 332 // Reload reads the configuration in the host and reloads the daemon and server. 333 func Reload(configFile string, flags *pflag.FlagSet, reload func(*Config)) error { 334 logrus.Infof("Got signal to reload configuration, reloading from: %s", configFile) 335 newConfig, err := getConflictFreeConfiguration(configFile, flags) 336 if err != nil { 337 if flags.Changed("config-file") || !os.IsNotExist(err) { 338 return errors.Wrapf(err, "unable to configure the Docker daemon with file %s", configFile) 339 } 340 newConfig, err = New() 341 if err != nil { 342 return err 343 } 344 } 345 346 // Check if duplicate label-keys with different values are found 347 newLabels, err := GetConflictFreeLabels(newConfig.Labels) 348 if err != nil { 349 return err 350 } 351 newConfig.Labels = newLabels 352 353 // TODO(thaJeztah) This logic is problematic and needs a rewrite; 354 // This is validating newConfig before the "reload()" callback is executed. 355 // At this point, newConfig may be a partial configuration, to be merged 356 // with the existing configuration in the "reload()" callback. Validating 357 // this config before it's merged can result in incorrect validation errors. 358 // 359 // However, the current "reload()" callback we use is DaemonCli.reloadConfig(), 360 // which includes a call to Daemon.Reload(), which both performs "merging" 361 // and validation, as well as actually updating the daemon configuration. 362 // Calling DaemonCli.reloadConfig() *before* validation, could thus lead to 363 // a failure in that function (making the reload non-atomic). 364 // 365 // While *some* errors could always occur when applying/updating the config, 366 // we should make it more atomic, and; 367 // 368 // 1. get (a copy of) the active configuration 369 // 2. get the new configuration 370 // 3. apply the (reloadable) options from the new configuration 371 // 4. validate the merged results 372 // 5. apply the new configuration. 373 if err := Validate(newConfig); err != nil { 374 return errors.Wrap(err, "file configuration validation failed") 375 } 376 377 reload(newConfig) 378 return nil 379 } 380 381 // boolValue is an interface that boolean value flags implement 382 // to tell the command line how to make -name equivalent to -name=true. 383 type boolValue interface { 384 IsBoolFlag() bool 385 } 386 387 // MergeDaemonConfigurations reads a configuration file, 388 // loads the file configuration in an isolated structure, 389 // and merges the configuration provided from flags on top 390 // if there are no conflicts. 391 func MergeDaemonConfigurations(flagsConfig *Config, flags *pflag.FlagSet, configFile string) (*Config, error) { 392 fileConfig, err := getConflictFreeConfiguration(configFile, flags) 393 if err != nil { 394 return nil, err 395 } 396 397 // merge flags configuration on top of the file configuration 398 if err := mergo.Merge(fileConfig, flagsConfig); err != nil { 399 return nil, err 400 } 401 402 // validate the merged fileConfig and flagsConfig 403 if err := Validate(fileConfig); err != nil { 404 return nil, errors.Wrap(err, "merged configuration validation from file and command line flags failed") 405 } 406 407 return fileConfig, nil 408 } 409 410 // getConflictFreeConfiguration loads the configuration from a JSON file. 411 // It compares that configuration with the one provided by the flags, 412 // and returns an error if there are conflicts. 413 func getConflictFreeConfiguration(configFile string, flags *pflag.FlagSet) (*Config, error) { 414 b, err := os.ReadFile(configFile) 415 if err != nil { 416 return nil, err 417 } 418 419 // Decode the contents of the JSON file using a [byte order mark] if present, instead of assuming UTF-8 without BOM. 420 // The BOM, if present, will be used to determine the encoding. If no BOM is present, we will assume the default 421 // and preferred encoding for JSON as defined by [RFC 8259], UTF-8 without BOM. 422 // 423 // While JSON is normatively UTF-8 with no BOM, there are a couple of reasons to decode here: 424 // * UTF-8 with BOM is something that new implementations should avoid producing; however, [RFC 8259 Section 8.1] 425 // allows implementations to ignore the UTF-8 BOM when present for interoperability. Older versions of Notepad, 426 // the only text editor available out of the box on Windows Server, writes UTF-8 with a BOM by default. 427 // * The default encoding for [Windows PowerShell] is UTF-16 LE with BOM. While encodings in PowerShell can be a 428 // bit idiosyncratic, BOMs are still generally written. There is no support for selecting UTF-8 without a BOM as 429 // the encoding in Windows PowerShell, though some Cmdlets only write UTF-8 with no BOM. PowerShell Core 430 // introduces `utf8NoBOM` and makes it the default, but PowerShell Core is unlikely to be the implementation for 431 // a majority of Windows Server + PowerShell users. 432 // * While [RFC 8259 Section 8.1] asserts that software that is not part of a closed ecosystem or that crosses a 433 // network boundary should only support UTF-8, and should never write a BOM, it does acknowledge older versions 434 // of the standard, such as [RFC 7159 Section 8.1]. In the interest of pragmatism and easing pain for Windows 435 // users, we consider Windows tools such as Windows PowerShell and Notepad part of our ecosystem, and support 436 // the two most common encodings: UTF-16 LE with BOM, and UTF-8 with BOM, in addition to the standard UTF-8 437 // without BOM. 438 // 439 // [byte order mark]: https://www.unicode.org/faq/utf_bom.html#BOM 440 // [RFC 8259]: https://www.rfc-editor.org/rfc/rfc8259 441 // [RFC 8259 Section 8.1]: https://www.rfc-editor.org/rfc/rfc8259#section-8.1 442 // [RFC 7159 Section 8.1]: https://www.rfc-editor.org/rfc/rfc7159#section-8.1 443 // [Windows PowerShell]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-5.1 444 b, n, err := transform.Bytes(transform.Chain(unicode.BOMOverride(transform.Nop), encoding.UTF8Validator), b) 445 if err != nil { 446 return nil, errors.Wrapf(err, "failed to decode configuration JSON at offset %d", n) 447 } 448 // Trim whitespace so that an empty config can be detected for an early return. 449 b = bytes.TrimSpace(b) 450 451 var config Config 452 if len(b) == 0 { 453 return &config, nil // early return on empty config 454 } 455 456 if flags != nil { 457 var jsonConfig map[string]interface{} 458 if err := json.Unmarshal(b, &jsonConfig); err != nil { 459 return nil, err 460 } 461 462 configSet := configValuesSet(jsonConfig) 463 464 if err := findConfigurationConflicts(configSet, flags); err != nil { 465 return nil, err 466 } 467 468 // Override flag values to make sure the values set in the config file with nullable values, like `false`, 469 // are not overridden by default truthy values from the flags that were not explicitly set. 470 // See https://github.com/docker/docker/issues/20289 for an example. 471 // 472 // TODO: Rewrite configuration logic to avoid same issue with other nullable values, like numbers. 473 namedOptions := make(map[string]interface{}) 474 for key, value := range configSet { 475 f := flags.Lookup(key) 476 if f == nil { // ignore named flags that don't match 477 namedOptions[key] = value 478 continue 479 } 480 481 if _, ok := f.Value.(boolValue); ok { 482 f.Value.Set(fmt.Sprintf("%v", value)) 483 } 484 } 485 if len(namedOptions) > 0 { 486 // set also default for mergeVal flags that are boolValue at the same time. 487 flags.VisitAll(func(f *pflag.Flag) { 488 if opt, named := f.Value.(opts.NamedOption); named { 489 v, set := namedOptions[opt.Name()] 490 _, boolean := f.Value.(boolValue) 491 if set && boolean { 492 f.Value.Set(fmt.Sprintf("%v", v)) 493 } 494 } 495 }) 496 } 497 498 config.ValuesSet = configSet 499 } 500 501 if err := json.Unmarshal(b, &config); err != nil { 502 return nil, err 503 } 504 505 return &config, nil 506 } 507 508 // configValuesSet returns the configuration values explicitly set in the file. 509 func configValuesSet(config map[string]interface{}) map[string]interface{} { 510 flatten := make(map[string]interface{}) 511 for k, v := range config { 512 if m, isMap := v.(map[string]interface{}); isMap && !flatOptions[k] { 513 for km, vm := range m { 514 flatten[km] = vm 515 } 516 continue 517 } 518 519 flatten[k] = v 520 } 521 return flatten 522 } 523 524 // findConfigurationConflicts iterates over the provided flags searching for 525 // duplicated configurations and unknown keys. It returns an error with all the conflicts if 526 // it finds any. 527 func findConfigurationConflicts(config map[string]interface{}, flags *pflag.FlagSet) error { 528 // 1. Search keys from the file that we don't recognize as flags. 529 unknownKeys := make(map[string]interface{}) 530 for key, value := range config { 531 if flag := flags.Lookup(key); flag == nil && !skipValidateOptions[key] { 532 unknownKeys[key] = value 533 } 534 } 535 536 // 2. Discard values that implement NamedOption. 537 // Their configuration name differs from their flag name, like `labels` and `label`. 538 if len(unknownKeys) > 0 { 539 unknownNamedConflicts := func(f *pflag.Flag) { 540 if namedOption, ok := f.Value.(opts.NamedOption); ok { 541 delete(unknownKeys, namedOption.Name()) 542 } 543 } 544 flags.VisitAll(unknownNamedConflicts) 545 } 546 547 if len(unknownKeys) > 0 { 548 var unknown []string 549 for key := range unknownKeys { 550 unknown = append(unknown, key) 551 } 552 return errors.Errorf("the following directives don't match any configuration option: %s", strings.Join(unknown, ", ")) 553 } 554 555 var conflicts []string 556 printConflict := func(name string, flagValue, fileValue interface{}) string { 557 switch name { 558 case "http-proxy", "https-proxy": 559 flagValue = MaskCredentials(flagValue.(string)) 560 fileValue = MaskCredentials(fileValue.(string)) 561 } 562 return fmt.Sprintf("%s: (from flag: %v, from file: %v)", name, flagValue, fileValue) 563 } 564 565 // 3. Search keys that are present as a flag and as a file option. 566 duplicatedConflicts := func(f *pflag.Flag) { 567 // search option name in the json configuration payload if the value is a named option 568 if namedOption, ok := f.Value.(opts.NamedOption); ok { 569 if optsValue, ok := config[namedOption.Name()]; ok && !skipDuplicates[namedOption.Name()] { 570 conflicts = append(conflicts, printConflict(namedOption.Name(), f.Value.String(), optsValue)) 571 } 572 } else { 573 // search flag name in the json configuration payload 574 for _, name := range []string{f.Name, f.Shorthand} { 575 if value, ok := config[name]; ok && !skipDuplicates[name] { 576 conflicts = append(conflicts, printConflict(name, f.Value.String(), value)) 577 break 578 } 579 } 580 } 581 } 582 583 flags.Visit(duplicatedConflicts) 584 585 if len(conflicts) > 0 { 586 return errors.Errorf("the following directives are specified both as a flag and in the configuration file: %s", strings.Join(conflicts, ", ")) 587 } 588 return nil 589 } 590 591 // Validate validates some specific configs. 592 // such as config.DNS, config.Labels, config.DNSSearch, 593 // as well as config.MaxConcurrentDownloads, config.MaxConcurrentUploads and config.MaxDownloadAttempts. 594 func Validate(config *Config) error { 595 // validate log-level 596 if config.LogLevel != "" { 597 if _, err := logrus.ParseLevel(config.LogLevel); err != nil { 598 return errors.Errorf("invalid logging level: %s", config.LogLevel) 599 } 600 } 601 602 // validate DNS 603 for _, dns := range config.DNS { 604 if _, err := opts.ValidateIPAddress(dns); err != nil { 605 return err 606 } 607 } 608 609 // validate DNSSearch 610 for _, dnsSearch := range config.DNSSearch { 611 if _, err := opts.ValidateDNSSearch(dnsSearch); err != nil { 612 return err 613 } 614 } 615 616 // validate Labels 617 for _, label := range config.Labels { 618 if _, err := opts.ValidateLabel(label); err != nil { 619 return err 620 } 621 } 622 623 // TODO(thaJeztah) Validations below should not accept "0" to be valid; see Validate() for a more in-depth description of this problem 624 if config.Mtu < 0 { 625 return errors.Errorf("invalid default MTU: %d", config.Mtu) 626 } 627 if config.MaxConcurrentDownloads < 0 { 628 return errors.Errorf("invalid max concurrent downloads: %d", config.MaxConcurrentDownloads) 629 } 630 if config.MaxConcurrentUploads < 0 { 631 return errors.Errorf("invalid max concurrent uploads: %d", config.MaxConcurrentUploads) 632 } 633 if config.MaxDownloadAttempts < 0 { 634 return errors.Errorf("invalid max download attempts: %d", config.MaxDownloadAttempts) 635 } 636 637 // validate that "default" runtime is not reset 638 if runtimes := config.GetAllRuntimes(); len(runtimes) > 0 { 639 if _, ok := runtimes[StockRuntimeName]; ok { 640 return errors.Errorf("runtime name '%s' is reserved", StockRuntimeName) 641 } 642 } 643 644 if _, err := ParseGenericResources(config.NodeGenericResources); err != nil { 645 return err 646 } 647 648 if defaultRuntime := config.GetDefaultRuntimeName(); defaultRuntime != "" { 649 if !builtinRuntimes[defaultRuntime] { 650 runtimes := config.GetAllRuntimes() 651 if _, ok := runtimes[defaultRuntime]; !ok && !IsPermissibleC8dRuntimeName(defaultRuntime) { 652 return errors.Errorf("specified default runtime '%s' does not exist", defaultRuntime) 653 } 654 } 655 } 656 657 for _, h := range config.Hosts { 658 if _, err := opts.ValidateHost(h); err != nil { 659 return err 660 } 661 } 662 663 // validate platform-specific settings 664 return config.ValidatePlatformConfig() 665 } 666 667 // GetDefaultRuntimeName returns the current default runtime 668 func (conf *Config) GetDefaultRuntimeName() string { 669 conf.Lock() 670 rt := conf.DefaultRuntime 671 conf.Unlock() 672 673 return rt 674 } 675 676 // MaskCredentials masks credentials that are in an URL. 677 func MaskCredentials(rawURL string) string { 678 parsedURL, err := url.Parse(rawURL) 679 if err != nil || parsedURL.User == nil { 680 return rawURL 681 } 682 parsedURL.User = url.UserPassword("xxxxx", "xxxxx") 683 return parsedURL.String() 684 } 685 686 // IsPermissibleC8dRuntimeName tests whether name is safe to pass into 687 // containerd as a runtime name, and whether the name is well-formed. 688 // It does not check if the runtime is installed. 689 // 690 // A runtime name containing slash characters is interpreted by containerd as 691 // the path to a runtime binary. If we allowed this, anyone with Engine API 692 // access could get containerd to execute an arbitrary binary as root. Although 693 // Engine API access is already equivalent to root on the host, the runtime name 694 // has not historically been a vector to run arbitrary code as root so users are 695 // not expecting it to become one. 696 // 697 // This restriction is not configurable. There are viable workarounds for 698 // legitimate use cases: administrators and runtime developers can make runtimes 699 // available for use with Docker by installing them onto PATH following the 700 // [binary naming convention] for containerd Runtime v2. 701 // 702 // [binary naming convention]: https://github.com/containerd/containerd/blob/main/runtime/v2/README.md#binary-naming 703 func IsPermissibleC8dRuntimeName(name string) bool { 704 // containerd uses a rather permissive test to validate runtime names: 705 // 706 // - Any name for which filepath.IsAbs(name) is interpreted as the absolute 707 // path to a shim binary. We want to block this behaviour. 708 // - Any name which contains at least one '.' character and no '/' characters 709 // and does not begin with a '.' character is a valid runtime name. The shim 710 // binary name is derived from the final two components of the name and 711 // searched for on the PATH. The name "a.." is technically valid per 712 // containerd's implementation: it would resolve to a binary named 713 // "containerd-shim---". 714 // 715 // https://github.com/containerd/containerd/blob/11ded166c15f92450958078cd13c6d87131ec563/runtime/v2/manager.go#L297-L317 716 // https://github.com/containerd/containerd/blob/11ded166c15f92450958078cd13c6d87131ec563/runtime/v2/shim/util.go#L83-L93 717 return !filepath.IsAbs(name) && !strings.ContainsRune(name, '/') && shim.BinaryName(name) != "" 718 }