// validateEtcdTLS checks the TLS settings for etcd are valid
194437
func validateEtcdTLS(specs []*kops.EtcdClusterSpec, fieldPath *field.Path) *field.Error {
	var usingTLS int
	for _, x := range specs {
		if x.EnableEtcdTLS {
			usingTLS++
		}
	}
	// check both clusters are using tls if one us enabled
	if usingTLS > 0 && usingTLS != len(specs) {
		return field.Invalid(fieldPath.Index(0).Child("EnableEtcdTLS"), false, "Both etcd clusters must have TLS enabled or none at all")
	}

	return nil
}
461478
func validateEtcdClusterSpecLegacy(spec *kops.EtcdClusterSpec, fieldPath *field.Path) *field.Error {
	if spec.Name == "" {
		return field.Required(fieldPath.Child("Name"), "EtcdCluster did not have name")
	}
	if len(spec.Members) == 0 {
		return field.Required(fieldPath.Child("Members"), "No members defined in etcd cluster")
	}
	if (len(spec.Members) % 2) == 0 {
		// Not technically a requirement, but doesn't really make sense to allow
		return field.Invalid(fieldPath.Child("Members"), len(spec.Members), "Should be an odd number of master-zones for quorum. Use --zones and --master-zones to declare node zones and master zones separately")
	}
	if err := validateEtcdVersion(spec, fieldPath, nil); err != nil {
		return err
	}
	for _, m := range spec.Members {
		if err := validateEtcdMemberSpec(m, fieldPath); err != nil {
			return err
		}
	}

	return nil
}
1172578
func (fc FullCommit) ValidateFull(chainID string) error {
	// Ensure that Validators exists and matches the header.
	if fc.Validators.Size() == 0 {
		return errors.New("need FullCommit.Validators")
	}
	if !bytes.Equal(
		fc.SignedHeader.ValidatorsHash,
		fc.Validators.Hash()) {
		return fmt.Errorf("header has vhash %X but valset hash is %X",
			fc.SignedHeader.ValidatorsHash,
			fc.Validators.Hash(),
		)
	}
	// Ensure that NextValidators exists and matches the header.
	if fc.NextValidators.Size() == 0 {
		return errors.New("need FullCommit.NextValidators")
	}
	if !bytes.Equal(
		fc.SignedHeader.NextValidatorsHash,
		fc.NextValidators.Hash()) {
		return fmt.Errorf("header has next vhash %X but next valset hash is %X",
			fc.SignedHeader.NextValidatorsHash,
			fc.NextValidators.Hash(),
		)
	}
	// Validate the header.
	err := fc.SignedHeader.ValidateBasic(chainID)
	if err != nil {
		return err
	}
	// Validate the signatures on the commit.
	hdr, cmt := fc.SignedHeader.Header, fc.SignedHeader.Commit
	return fc.Validators.VerifyCommit(
		hdr.ChainID, cmt.BlockID,
		hdr.Height, cmt)
}
980939
func WithTLS(cfg *tls.Config) Option {
	return func(opts *options) {
		opts.useTLS = true
		opts.tlsConfig = cfg
	}
}
344450
func validateEtcdStorage(specs []*kops.EtcdClusterSpec, fieldPath *field.Path) *field.Error {
	version := specs[0].Version
	for i, x := range specs {
		if x.Version != "" && x.Version != version {
			return field.Invalid(fieldPath.Index(i).Child("Version"), x.Version, fmt.Sprintf("cluster: %q, has a different storage versions: %q, both must be the same", x.Name, x.Version))
		}
	}

	return nil
}
1359409
func (cli *Client) validatePacketID(packets map[uint16]packet.Packet, id uint16, ptype byte) error {
	// Extract the Packet.
	p, exist := packets[id]

	if !exist {
		// Return an error if there is no Packet which has the Packet Identifier
		// specified by the parameter.
		return packet.ErrInvalidPacketID
	}

	// Extract the MQTT Control Packet type of the Packet.
	t, err := p.Type()
	if err != nil {
		return err
	}

	if t != ptype {
		// Return an error if the Packet's MQTT Control Packet type does not
		// equal to one specified by the parameter.
		return packet.ErrInvalidPacketID
	}

	return nil
}
524369
func validateDatacentersCfg(c *validation.Context, cfg *configPB.Datacenters) {
	// Datacenter filenames must be unique.
	// Keep records of which ones we've already seen.
	files := stringset.New(len(cfg.Datacenter))
	for _, file := range cfg.Datacenter {
		switch {
		case file == "":
			c.Errorf("datacenter filenames are required and must be non-empty")
		case !files.Add(file):
			c.Errorf("duplicate filename %q", file)
		}
	}
}
1068563
func (m *TLSProperties) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for TlsVersion

	{
		tmp := m.GetTlsCipherSuite()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TLSPropertiesValidationError{
					field:  "TlsCipherSuite",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	// no validation rules for TlsSniHostname

	{
		tmp := m.GetLocalCertificateProperties()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TLSPropertiesValidationError{
					field:  "LocalCertificateProperties",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	{
		tmp := m.GetPeerCertificateProperties()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TLSPropertiesValidationError{
					field:  "PeerCertificateProperties",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	return nil
}
524628
func SkipTLSValidation(skipTLSvalidation bool) Option {
	return func(c *CredHub) error {
		c.insecureSkipVerify = skipTLSvalidation
		return nil
	}
}
618500
func setupTLS(c *caddy.Controller) error {
	// set up the clustering plugin, if there is one (and there should always
	// be one since this tls plugin requires it) -- this should be done exactly
	// once, but we can't do it during init while plugins are still registering,
	// so do it as soon as we run a setup)
	if atomic.CompareAndSwapInt32(&clusterPluginSetup, 0, 1) {
		clusterPluginName := os.Getenv("CADDY_CLUSTERING")
		if clusterPluginName == "" {
			clusterPluginName = "file" // name of default storage plugin
		}
		clusterFn, ok := clusterProviders[clusterPluginName]
		if ok {
			storage, err := clusterFn()
			if err != nil {
				return fmt.Errorf("constructing cluster plugin %s: %v", clusterPluginName, err)
			}
			certmagic.Default.Storage = storage
		} else {
			return fmt.Errorf("unrecognized cluster plugin (was it included in the Caddy build?): %s", clusterPluginName)
		}
	}

	configGetter, ok := configGetters[c.ServerType()]
	if !ok {
		return fmt.Errorf("no caddytls.ConfigGetter for %s server type; must call RegisterConfigGetter", c.ServerType())
	}
	config := configGetter(c)
	if config == nil {
		return fmt.Errorf("no caddytls.Config to set up for %s", c.Key)
	}

	config.Enabled = true

	// we use certmagic events to collect metrics for telemetry
	config.Manager.OnEvent = func(event string, data interface{}) {
		switch event {
		case "tls_handshake_started":
			clientHello := data.(*tls.ClientHelloInfo)
			if ClientHelloTelemetry && len(clientHello.SupportedVersions) > 0 {
				// If no other plugin (such as the HTTP server type) is implementing ClientHello telemetry, we do it.
				// NOTE: The values in the Go standard lib's ClientHelloInfo aren't guaranteed to be in order.
				info := ClientHelloInfo{
					Version:                   clientHello.SupportedVersions[0], // report the highest
					CipherSuites:              clientHello.CipherSuites,
					ExtensionsUnknown:         true, // no extension info... :(
					CompressionMethodsUnknown: true, // no compression methods... :(
					Curves:                    clientHello.SupportedCurves,
					Points:                    clientHello.SupportedPoints,
					// We also have, but do not yet use: SignatureSchemes, ServerName, and SupportedProtos (ALPN)
					// because the standard lib parses some extensions, but our MITM detector generally doesn't.
				}
				go telemetry.SetNested("tls_client_hello", info.Key(), info)
			}

		case "tls_handshake_completed":
			// TODO: This is a "best guess" for now - at this point, we only gave a
			// certificate to the client; we need something listener-level to be sure
			go telemetry.Increment("tls_handshake_count")

		case "acme_cert_obtained":
			go telemetry.Increment("tls_acme_certs_obtained")

		case "acme_cert_renewed":
			name := data.(string)
			caddy.EmitEvent(caddy.CertRenewEvent, name)
			go telemetry.Increment("tls_acme_certs_renewed")

		case "acme_cert_revoked":
			telemetry.Increment("acme_certs_revoked")

		case "cached_managed_cert":
			telemetry.Increment("tls_managed_cert_count")

		case "cached_unmanaged_cert":
			telemetry.Increment("tls_unmanaged_cert_count")
		}
	}

	for c.Next() {
		var certificateFile, keyFile, loadDir, maxCerts, askURL string
		var onDemand bool

		args := c.RemainingArgs()
		switch len(args) {
		case 1:
			// even if the email is one of the special values below,
			// it is still necessary for future analysis that we store
			// that value in the ACMEEmail field.
			config.ACMEEmail = args[0]

			switch args[0] {
			// user can force-disable managed TLS this way
			case "off":
				config.Enabled = false
				return nil
			// user might want a temporary, in-memory, self-signed cert
			case "self_signed":
				config.SelfSigned = true
			default:
				config.Manager.Email = args[0]
			}
		case 2:
			certificateFile = args[0]
			keyFile = args[1]
			config.Manual = true
		}

		// Optional block with extra parameters
		var hadBlock bool
		for c.NextBlock() {
			hadBlock = true
			switch c.Val() {
			case "ca":
				arg := c.RemainingArgs()
				if len(arg) != 1 {
					return c.ArgErr()
				}
				config.Manager.CA = arg[0]
			case "key_type":
				arg := c.RemainingArgs()
				value, ok := supportedKeyTypes[strings.ToUpper(arg[0])]
				if !ok {
					return c.Errf("Wrong key type name or key type not supported: '%s'", c.Val())
				}
				config.Manager.KeyType = value
			case "protocols":
				args := c.RemainingArgs()
				if len(args) == 1 {
					value, ok := SupportedProtocols[strings.ToLower(args[0])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
					}
					config.ProtocolMinVersion, config.ProtocolMaxVersion = value, value
				} else {
					value, ok := SupportedProtocols[strings.ToLower(args[0])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
					}
					config.ProtocolMinVersion = value
					value, ok = SupportedProtocols[strings.ToLower(args[1])]
					if !ok {
						return c.Errf("Wrong protocol name or protocol not supported: '%s'", args[1])
					}
					config.ProtocolMaxVersion = value
					if config.ProtocolMinVersion > config.ProtocolMaxVersion {
						return c.Errf("Minimum protocol version cannot be higher than maximum (reverse the order)")
					}
				}
			case "ciphers":
				for c.NextArg() {
					value, ok := SupportedCiphersMap[strings.ToUpper(c.Val())]
					if !ok {
						return c.Errf("Wrong cipher name or cipher not supported: '%s'", c.Val())
					}
					config.Ciphers = append(config.Ciphers, value)
				}
			case "curves":
				for c.NextArg() {
					value, ok := supportedCurvesMap[strings.ToUpper(c.Val())]
					if !ok {
						return c.Errf("Wrong curve name or curve not supported: '%s'", c.Val())
					}
					config.CurvePreferences = append(config.CurvePreferences, value)
				}
			case "clients":
				clientCertList := c.RemainingArgs()
				if len(clientCertList) == 0 {
					return c.ArgErr()
				}

				listStart, mustProvideCA := 1, true
				switch clientCertList[0] {
				case "request":
					config.ClientAuth = tls.RequestClientCert
					mustProvideCA = false
				case "require":
					config.ClientAuth = tls.RequireAnyClientCert
					mustProvideCA = false
				case "verify_if_given":
					config.ClientAuth = tls.VerifyClientCertIfGiven
				default:
					config.ClientAuth = tls.RequireAndVerifyClientCert
					listStart = 0
				}
				if mustProvideCA && len(clientCertList) <= listStart {
					return c.ArgErr()
				}

				config.ClientCerts = clientCertList[listStart:]
			case "load":
				c.Args(&loadDir)
				config.Manual = true
			case "max_certs":
				c.Args(&maxCerts)
				onDemand = true
			case "ask":
				c.Args(&askURL)
				onDemand = true
			case "dns":
				args := c.RemainingArgs()
				if len(args) != 1 {
					return c.ArgErr()
				}
				// TODO: we can get rid of DNS provider plugins with this one line
				// of code; however, currently (Dec. 2018) this adds about 20 MB
				// of bloat to the Caddy binary, doubling its size to ~40 MB...!
				// dnsProv, err := dns.NewDNSChallengeProviderByName(args[0])
				// if err != nil {
				// 	return c.Errf("Configuring DNS provider '%s': %v", args[0], err)
				// }
				dnsProvName := args[0]
				dnsProvConstructor, ok := dnsProviders[dnsProvName]
				if !ok {
					return c.Errf("Unknown DNS provider by name '%s'", dnsProvName)
				}
				dnsProv, err := dnsProvConstructor()
				if err != nil {
					return c.Errf("Setting up DNS provider '%s': %v", dnsProvName, err)
				}
				config.Manager.DNSProvider = dnsProv
			case "alpn":
				args := c.RemainingArgs()
				if len(args) == 0 {
					return c.ArgErr()
				}
				for _, arg := range args {
					config.ALPN = append(config.ALPN, arg)
				}
			case "must_staple":
				config.Manager.MustStaple = true
			case "wildcard":
				if !certmagic.HostQualifies(config.Hostname) {
					return c.Errf("Hostname '%s' does not qualify for managed TLS, so cannot manage wildcard certificate for it", config.Hostname)
				}
				if strings.Contains(config.Hostname, "*") {
					return c.Errf("Cannot convert domain name '%s' to a valid wildcard: already has a wildcard label", config.Hostname)
				}
				parts := strings.Split(config.Hostname, ".")
				if len(parts) < 3 {
					return c.Errf("Cannot convert domain name '%s' to a valid wildcard: too few labels", config.Hostname)
				}
				parts[0] = "*"
				config.Hostname = strings.Join(parts, ".")
			default:
				return c.Errf("Unknown subdirective '%s'", c.Val())
			}
		}

		// tls requires at least one argument if a block is not opened
		if len(args) == 0 && !hadBlock {
			return c.ArgErr()
		}

		// configure on-demand TLS, if enabled
		if onDemand {
			config.Manager.OnDemand = new(certmagic.OnDemandConfig)
			if maxCerts != "" {
				maxCertsNum, err := strconv.Atoi(maxCerts)
				if err != nil || maxCertsNum < 1 {
					return c.Err("max_certs must be a positive integer")
				}
				config.Manager.OnDemand.MaxObtain = int32(maxCertsNum)
			}
			if askURL != "" {
				parsedURL, err := url.Parse(askURL)
				if err != nil {
					return c.Err("ask must be a valid url")
				}
				if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
					return c.Err("ask URL must use http or https")
				}
				config.Manager.OnDemand.AskURL = parsedURL
			}
		}

		// don't try to load certificates unless we're supposed to
		if !config.Enabled || !config.Manual {
			continue
		}

		// load a single certificate and key, if specified
		if certificateFile != "" && keyFile != "" {
			err := config.Manager.CacheUnmanagedCertificatePEMFile(certificateFile, keyFile)
			if err != nil {
				return c.Errf("Unable to load certificate and key files for '%s': %v", c.Key, err)
			}
			log.Printf("[INFO] Successfully loaded TLS assets from %s and %s", certificateFile, keyFile)
		}

		// load a directory of certificates, if specified
		if loadDir != "" {
			err := loadCertsInDir(config, c, loadDir)
			if err != nil {
				return err
			}
		}
	}

	SetDefaultTLSParams(config)

	// generate self-signed cert if needed
	if config.SelfSigned {
		ssCert, err := newSelfSignedCertificate(selfSignedConfig{
			SAN:     []string{config.Hostname},
			KeyType: config.Manager.KeyType,
		})
		if err != nil {
			return fmt.Errorf("self-signed certificate generation: %v", err)
		}
		err = config.Manager.CacheUnmanagedTLSCertificate(ssCert)
		if err != nil {
			return fmt.Errorf("self-signed: %v", err)
		}
		telemetry.Increment("tls_self_signed_count")
	}

	// store this as a custom config
	cfgMap, ok := c.Get(configMapKey).(map[string]*Config)
	if !ok || cfgMap == nil {
		cfgMap = make(map[string]*Config)
	}
	cfgMap[config.Hostname] = config
	c.Set(configMapKey, cfgMap)

	return nil
}
228796
func ValidateEtcdConnectionInfo(config config.EtcdConnectionInfo, server *config.EtcdConfig, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	if len(config.URLs) == 0 {
		allErrs = append(allErrs, field.Required(fldPath.Child("urls"), ""))
	}
	for i, u := range config.URLs {
		_, urlErrs := common.ValidateURL(u, fldPath.Child("urls").Index(i))
		if len(urlErrs) > 0 {
			allErrs = append(allErrs, urlErrs...)
		}
	}

	if len(config.CA) > 0 {
		allErrs = append(allErrs, common.ValidateFile(config.CA, fldPath.Child("ca"))...)
	}
	allErrs = append(allErrs, common.ValidateCertInfo(config.ClientCert, false, fldPath)...)

	// If we have server config info, make sure the client connection info will work with it
	if server != nil {
		var builtInAddress = fmt.Sprintf("https://%s", server.Address)

		// Require a client cert to connect to an etcd that requires client certs
		if len(server.ServingInfo.ClientCA) > 0 {
			if len(config.ClientCert.CertFile) == 0 {
				allErrs = append(allErrs, field.Required(fldPath.Child("certFile"), "A client certificate must be provided for this etcd server"))
			}
		}

		// Require the etcdClientInfo to include the address of the internal etcd
		clientURLs := sets.NewString(config.URLs...)
		if !clientURLs.Has(builtInAddress) {
			allErrs = append(allErrs, field.Invalid(fldPath.Child("urls"), strings.Join(clientURLs.List(), ","), fmt.Sprintf("must include the etcd address %s", builtInAddress)))
		}
	}

	return allErrs
}
490792
func (m *TlsCertificate) Validate() error {
	if m == nil {
		return nil
	}

	{
		tmp := m.GetCertificateChain()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TlsCertificateValidationError{
					field:  "CertificateChain",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	{
		tmp := m.GetPrivateKey()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TlsCertificateValidationError{
					field:  "PrivateKey",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	{
		tmp := m.GetPassword()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TlsCertificateValidationError{
					field:  "Password",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	{
		tmp := m.GetOcspStaple()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return TlsCertificateValidationError{
					field:  "OcspStaple",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	for idx, item := range m.GetSignedCertificateTimestamp() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return TlsCertificateValidationError{
						field:  fmt.Sprintf("SignedCertificateTimestamp[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	return nil
}
1112611
func setupTLS(ws *webserver.Server, config *serverinit.Config, hostname string) {
	cert, key := config.HTTPSCert(), config.HTTPSKey()
	if !config.HTTPS() {
		return
	}
	if (cert != "") != (key != "") {
		exitf("httpsCert and httpsKey must both be either present or absent")
	}

	defCert := osutil.DefaultTLSCert()
	defKey := osutil.DefaultTLSKey()
	const hint = "You must add this certificate's fingerprint to your client's trusted certs list to use it. Like so:\n\"trustedCerts\": [\"%s\"],"
	if cert == defCert && key == defKey {
		_, err1 := wkfs.Stat(cert)
		_, err2 := wkfs.Stat(key)
		if err1 != nil || err2 != nil {
			if os.IsNotExist(err1) || os.IsNotExist(err2) {
				sig, err := httputil.GenSelfTLSFiles(hostname, defCert, defKey)
				if err != nil {
					exitf("Could not generate self-signed TLS cert: %q", err)
				}
				log.Printf(hint, sig)
			} else {
				exitf("Could not stat cert or key: %q, %q", err1, err2)
			}
		}
	}
	if cert == "" && key == "" {
		// Use Let's Encrypt if no files are specified, and we have a usable hostname.
		if netutil.IsFQDN(hostname) {
			m := autocert.Manager{
				Prompt:     autocert.AcceptTOS,
				HostPolicy: autocert.HostWhitelist(hostname),
				Cache:      autocert.DirCache(osutil.DefaultLetsEncryptCache()),
			}
			ws.SetTLS(webserver.TLSSetup{
				CertManager: m.GetCertificate,
			})
			log.Printf("Using Let's Encrypt tls-alpn-01 for %v", hostname)
			return
		}
		// Otherwise generate new certificates
		sig, err := httputil.GenSelfTLSFiles(hostname, defCert, defKey)
		if err != nil {
			exitf("Could not generate self signed creds: %q", err)
		}
		log.Printf(hint, sig)
		cert = defCert
		key = defKey
	}
	data, err := wkfs.ReadFile(cert)
	if err != nil {
		exitf("Failed to read pem certificate: %s", err)
	}
	sig, err := httputil.CertFingerprint(data)
	if err != nil {
		exitf("certificate error: %v", err)
	}
	log.Printf("TLS enabled, with SHA-256 certificate fingerprint: %v", sig)
	ws.SetTLS(webserver.TLSSetup{
		CertFile: cert,
		KeyFile:  key,
	})
}
408491
func (mc *multiProvider) ValidatorSet(chainID string, height int64) (valset *types.ValidatorSet, err error) {
	for _, p := range mc.providers {
		valset, err = p.ValidatorSet(chainID, height)
		if err == nil {
			// TODO Log unexpected types of errors.
			return valset, nil
		}
	}
	return nil, lerr.ErrUnknownValidators(chainID, height)
}
286805
func (p *gateway) setupEtcdClient(etcdCfg *embetcd.Config) (err error) {
	var endpoints []string
	if etcdCfg.ClusterState == embed.ClusterStateFlagNew {
		endpoints = embetcd.URLSToStringSlice(etcdCfg.ACUrls)
	} else {
		endpoints = etcdCfg.InitialCluster
	}
	// setup the etcd client
	if etcdCfg.ClusterName != "" && len(endpoints) > 0 {
		p.etcdClient, err = embetcd.NewClient(etcdcli.Config{
			Endpoints:        endpoints,
			AutoSyncInterval: *etcdCfg.AutoSyncInterval,
			DialTimeout:      *etcdCfg.DialTimeout,
		})
	}
	return err
}
318719
func validateExt(configs Config, ext string) error {
	if !strings.HasPrefix(ext, ".") {
		return fmt.Errorf(`mime: invalid extension "%v" (must start with dot)`, ext)
	}
	if _, ok := configs[ext]; ok {
		return fmt.Errorf(`mime: duplicate extension "%v" found`, ext)
	}
	return nil
}
1094325
func ValidTrits(t Trits) error {
	for i, tt := range t {
		if valid := ValidTrit(tt); !valid {
			return errors.Wrapf(ErrInvalidTrit, "at index %d", i)
		}
	}
	return nil
}