// configureNATSServerTLS sets up TLS for the NATS Server.
// Additional TLS parameters (e.g. cipher suites) will need to be placed
// in a configuration file specified through the -config parameter.
510847
func (s *StanServer) configureNATSServerTLS() error {
	opts := s.natsOpts
	tlsSet := false
	tc := server.TLSConfigOpts{}
	if opts.TLSCert != "" {
		tc.CertFile = opts.TLSCert
		tlsSet = true
	}
	if opts.TLSKey != "" {
		tc.KeyFile = opts.TLSKey
		tlsSet = true
	}
	if opts.TLSCaCert != "" {
		tc.CaFile = opts.TLSCaCert
		tlsSet = true
	}

	if opts.TLSVerify {
		tc.Verify = true
		tlsSet = true
	}

	var err error
	if tlsSet {
		if opts.TLSConfig, err = server.GenTLSConfig(&tc); err != nil {
			// The connection will fail later if the problem is severe enough.
			return fmt.Errorf("unable to setup NATS Server TLS:  %v", err)
		}
	}
	return nil
}
1120355
func (s *ModifyEndpointInput) SetDmsTransferSettings(v *DmsTransferSettings) *ModifyEndpointInput {
	s.DmsTransferSettings = v
	return s
}
319167
func (i *Instance) ConfigureRules(version int, contextID string, pu *policy.PUInfo) error {

	var err error
	var cfg *ACLInfo

	// First we create an IPSet for destination matching ports. This only
	// applies to Linux type PUs. A port set is associated with every PU,
	// and packets matching this destination get associated with the context
	// of the PU.
	if err = i.createPortSet(contextID, pu); err != nil {
		return err
	}

	// We create the generic ACL object that is used for all the templates.
	cfg, err = i.newACLInfo(version, contextID, pu, pu.Runtime.PUType())
	if err != nil {
		return err
	}

	// Create the proxy sets. These are the target sets that will match
	// traffic towards the L4 and L4 services. There are two sets created
	// for every PU in this context (for outgoing and incoming traffic).
	// The outgoing sets capture all traffic towards specific destinations
	// as proxied traffic. Incoming sets correspond to the listening
	// services.
	if err = i.createProxySets(cfg.ProxySetName); err != nil {
		return err
	}

	// At this point we can install all the ACL rules that will direct
	// traffic to user space, allow for external access or direct
	// traffic towards the proxies
	if err = i.installRules(cfg, pu); err != nil {
		return err
	}

	// We commit the ACLs at the end. Note, that some of the ACLs in the
	// NAT table are not committed as a group. The commit function only
	// applies when newer versions of tables are installed (1.6.2 and above).
	if err = i.ipt.Commit(); err != nil {
		zap.L().Error("unable to configure rules", zap.Error(err))
		return err
	}

	i.conntrackCmd(i.cfg.UDPTargetNetworks)

	return nil
}
1315239
func NewServerTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool) (*tls.Config, error) {
	if rootCAPool == nil {
		return nil, errors.New("valid root CA pool required")
	}

	return &tls.Config{
		Certificates: certs,
		// Since we're using the same CA server to issue Certificates to new nodes, we can't
		// use tls.RequireAndVerifyClientCert
		ClientAuth:               tls.VerifyClientCertIfGiven,
		RootCAs:                  rootCAPool,
		ClientCAs:                rootCAPool,
		PreferServerCipherSuites: true,
		MinVersion:               tls.VersionTLS12,
	}, nil
}
827254
func InitializeTLS(kf *options.KubeletFlags, kc *kubeletconfiginternal.KubeletConfiguration) (*server.TLSOptions, error) {
	if !kc.ServerTLSBootstrap && kc.TLSCertFile == "" && kc.TLSPrivateKeyFile == "" {
		kc.TLSCertFile = path.Join(kf.CertDirectory, "kubelet.crt")
		kc.TLSPrivateKeyFile = path.Join(kf.CertDirectory, "kubelet.key")

		canReadCertAndKey, err := certutil.CanReadCertAndKey(kc.TLSCertFile, kc.TLSPrivateKeyFile)
		if err != nil {
			return nil, err
		}
		if !canReadCertAndKey {
			hostName, err := nodeutil.GetHostname(kf.HostnameOverride)
			if err != nil {
				return nil, err
			}
			cert, key, err := certutil.GenerateSelfSignedCertKey(hostName, nil, nil)
			if err != nil {
				return nil, fmt.Errorf("unable to generate self signed cert: %v", err)
			}

			if err := certutil.WriteCert(kc.TLSCertFile, cert); err != nil {
				return nil, err
			}

			if err := keyutil.WriteKey(kc.TLSPrivateKeyFile, key); err != nil {
				return nil, err
			}

			klog.V(4).Infof("Using self-signed cert (%s, %s)", kc.TLSCertFile, kc.TLSPrivateKeyFile)
		}
	}

	tlsCipherSuites, err := cliflag.TLSCipherSuites(kc.TLSCipherSuites)
	if err != nil {
		return nil, err
	}

	minTLSVersion, err := cliflag.TLSVersion(kc.TLSMinVersion)
	if err != nil {
		return nil, err
	}

	tlsOptions := &server.TLSOptions{
		Config: &tls.Config{
			MinVersion:   minTLSVersion,
			CipherSuites: tlsCipherSuites,
		},
		CertFile: kc.TLSCertFile,
		KeyFile:  kc.TLSPrivateKeyFile,
	}

	if len(kc.Authentication.X509.ClientCAFile) > 0 {
		clientCAs, err := certutil.NewPool(kc.Authentication.X509.ClientCAFile)
		if err != nil {
			return nil, fmt.Errorf("unable to load client CA file %s: %v", kc.Authentication.X509.ClientCAFile, err)
		}
		// Specify allowed CAs for client certificates
		tlsOptions.Config.ClientCAs = clientCAs
		// Populate PeerCertificates in requests, but don't reject connections without verified certificates
		tlsOptions.Config.ClientAuth = tls.RequestClientCert
	}

	return tlsOptions, nil
}
305480
func TLSServer(config *tls.Config, srv ListenServer) Detector {
	// TODO: isTLSClientHello can really benefit from more bytes
	return Detector{
		Needed:  minBytes,
		Test:    isTLSClientHello,
		Handler: newTLSShim(config, srv),
	}
}
226893
func (s *HlsGroupSettings) SetHlsCdnSettings(v *HlsCdnSettings) *HlsGroupSettings {
	s.HlsCdnSettings = v
	return s
}
294135
func (gs *Server) ListenAndServeTLS(certFile, keyFile string) error {
	// direct lift from net/http/server.go
	addr := gs.Addr
	if addr == "" {
		addr = ":https"
	}
	config := &tls.Config{}
	if gs.TLSConfig != nil {
		*config = *gs.TLSConfig
	}
	if config.NextProtos == nil {
		// "h2" is required in order to enable HTTP 2: https://golang.org/src/net/http/server.go
		config.NextProtos = []string{"h2", "http/1.1"}
	}

	var err error
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return err
	}

	return gs.ListenAndServeTLSWithConfig(config)
}
695585
func WebsocketTLSClientConfig(tcc *tls.Config) optSetter {
	return func(f *Forwarder) error {
		f.httpForwarder.tlsClientConfig = tcc
		return nil
	}
}
1356340
func (s *Input) SetDecryptionSettings(v *InputDecryptionSettings) *Input {
	s.DecryptionSettings = v
	return s
}
1004428
func (cniReq *cniServer) configureNetNs(ovsEpDriver *drivers.OperEndpointState,
	mResp *master.CreateEndpointResponse,
	nwState *mastercfg.CfgNetworkState) error {

	os.MkdirAll(netNsDir, 644)

	// link new name space
	if _, err := os.Stat(netNsDir + cniReq.pluginArgs.CniContainerid); err != nil {
		if err := os.Symlink(cniReq.pluginArgs.CniNetns, netNsDir+cniReq.pluginArgs.CniContainerid); err != nil {
			cniLog.Errorf("failed to link pid to namespace : %s", err.Error())
			return err
		}
	}
	cniLog.Infof("linked %s --> %s ", cniReq.pluginArgs.CniNetns, netNsDir+cniReq.pluginArgs.CniContainerid)

	// move interface to new namespace
	if _, err := exec.Command("ip", "link", "set", ovsEpDriver.PortName, "netns",
		cniReq.pluginArgs.CniContainerid).CombinedOutput(); err != nil {
		cniLog.Errorf("failed to move intf %s to namespace %s: %s",
			ovsEpDriver.PortName, cniReq.pluginArgs.CniContainerid, err.Error())
		cniReq.unlinkNetNs()
		return err
	}

	nsCmds := [][]string{
		{"ip", "link", "set", ovsEpDriver.PortName, "name", cniReq.pluginArgs.CniIfname, "up"},
		{"ip", "address", "add", fmt.Sprintf("%s/%d", ovsEpDriver.IPAddress, nwState.SubnetLen), "dev",
			cniReq.pluginArgs.CniIfname},
	}

	cniReq.ipv4Addr = ovsEpDriver.IPAddress
	cniReq.cniSuccessResp.IP4.IPAddress = fmt.Sprintf("%s/%d", ovsEpDriver.IPAddress, nwState.SubnetLen)

	// gateway
	if len(nwState.Gateway) > 0 {
		gwCmd := []string{"ip", "route", "add", "default", "via", fmt.Sprintf("%s", nwState.Gateway)}
		nsCmds = append(nsCmds, gwCmd)
		cniReq.cniSuccessResp.IP4.Gateway = nwState.Gateway
		cniLog.Infof("ipv4 default gateway of endpoint %s", nwState.Gateway)
	}

	// ipv6
	if len(mResp.EndpointConfig.IPv6Address) > 0 {
		ipv6Cmd := []string{"ip", "-6", "addr", "add",
			fmt.Sprintf("%s/%d", mResp.EndpointConfig.IPv6Address, nwState.IPv6SubnetLen),
			"dev", cniReq.pluginArgs.CniIfname}
		nsCmds = append(nsCmds, ipv6Cmd)
		cniReq.cniSuccessResp.IP6.IPAddress = fmt.Sprintf("%s/%d", mResp.EndpointConfig.IPv6Address, nwState.IPv6SubnetLen)
		cniLog.Infof("ipv6 address of endpoint %s", mResp.EndpointConfig.IPv6Address)

	}

	if len(nwState.IPv6Gateway) > 0 {
		ipv6gwCmd := []string{"ip", "-6", "route", "add", "default", "via",
			fmt.Sprintf("%s", nwState.IPv6Gateway)}
		nsCmds = append(nsCmds, ipv6gwCmd)
		cniReq.cniSuccessResp.IP6.Gateway = nwState.IPv6Gateway
		cniLog.Infof("ipv6 gateway of endpoint %s", nwState.IPv6Gateway)
	}

	if _, err := cniReq.ipnsBatchExecute(cniReq.pluginArgs.CniContainerid, nsCmds); err != nil {
		cniLog.Errorf("failed to execute commands in namespace %s: %s",
			cniReq.pluginArgs.CniNetns, err.Error())
		cniReq.unlinkNetNs()
		return err
	}

	return nil
}
503623
func (conf Config) ToSecureOptions(newSelfSignedTLSCert genTLSCertFunc) (*comm.SecureOptions, error) {
	if conf.PeerCACertPath == "" {
		return &comm.SecureOptions{}, nil
	}
	caBytes, err := loadFile(conf.PeerCACertPath)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	var keyBytes, certBytes []byte
	// If TLS key and certificate aren't given, generate a self signed one on the fly
	if conf.KeyPath == "" && conf.CertPath == "" {
		tlsCert, err := newSelfSignedTLSCert()
		if err != nil {
			return nil, err
		}
		keyBytes, certBytes = tlsCert.Key, tlsCert.Cert
	} else {
		keyBytes, err = loadFile(conf.KeyPath)
		if err != nil {
			return nil, errors.WithStack(err)
		}
		certBytes, err = loadFile(conf.CertPath)
		if err != nil {
			return nil, errors.WithStack(err)
		}
	}
	return &comm.SecureOptions{
		Key:               keyBytes,
		Certificate:       certBytes,
		UseTLS:            true,
		ServerRootCAs:     [][]byte{caBytes},
		RequireClientCert: true,
	}, nil
}
840586
func parseTLS(v interface{}) (*TLSConfigOpts, error) {
	var (
		tlsm map[string]interface{}
		tc   = TLSConfigOpts{}
	)
	_, v = unwrapValue(v)
	tlsm = v.(map[string]interface{})
	for mk, mv := range tlsm {
		tk, mv := unwrapValue(mv)
		switch strings.ToLower(mk) {
		case "cert_file":
			certFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'cert_file' to be filename")}
			}
			tc.CertFile = certFile
		case "key_file":
			keyFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'key_file' to be filename")}
			}
			tc.KeyFile = keyFile
		case "ca_file":
			caFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'ca_file' to be filename")}
			}
			tc.CaFile = caFile
		case "insecure":
			insecure, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'insecure' to be a boolean")}
			}
			tc.Insecure = insecure
		case "verify":
			verify, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'verify' to be a boolean")}
			}
			tc.Verify = verify
		case "verify_and_map":
			verify, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, expected 'verify_and_map' to be a boolean")}
			}
			tc.Verify = verify
			tc.Map = verify
		case "cipher_suites":
			ra := mv.([]interface{})
			if len(ra) == 0 {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'cipher_suites' cannot be empty")}
			}
			tc.Ciphers = make([]uint16, 0, len(ra))
			for _, r := range ra {
				tk, r := unwrapValue(r)
				cipher, err := parseCipher(r.(string))
				if err != nil {
					return nil, &configErr{tk, err.Error()}
				}
				tc.Ciphers = append(tc.Ciphers, cipher)
			}
		case "curve_preferences":
			ra := mv.([]interface{})
			if len(ra) == 0 {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'curve_preferences' cannot be empty")}
			}
			tc.CurvePreferences = make([]tls.CurveID, 0, len(ra))
			for _, r := range ra {
				tk, r := unwrapValue(r)
				cps, err := parseCurvePreferences(r.(string))
				if err != nil {
					return nil, &configErr{tk, err.Error()}
				}
				tc.CurvePreferences = append(tc.CurvePreferences, cps)
			}
		case "timeout":
			at := float64(0)
			switch mv := mv.(type) {
			case int64:
				at = float64(mv)
			case float64:
				at = mv
			}
			tc.Timeout = at
		default:
			return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, unknown field [%q]", mk)}
		}
	}

	// If cipher suites were not specified then use the defaults
	if tc.Ciphers == nil {
		tc.Ciphers = defaultCipherSuites()
	}

	// If curve preferences were not specified, then use the defaults
	if tc.CurvePreferences == nil {
		tc.CurvePreferences = defaultCurvePreferences()
	}

	return &tc, nil
}
1088875
func (v *vserver) configureVIPs() {
	ncc := v.engine.ncc
	if err := ncc.Dial(); err != nil {
		log.Fatalf("%v: failed to connect to NCC: %v", v, err)
	}
	defer ncc.Close()

	// TODO(ncope): Return to iterating over v.services once they contain seesaw.VIPs.
	for _, vip := range v.config.VIPs {
		if _, ok := v.vips[*vip]; ok {
			continue
		}
		// TODO(angusc): Set up anycast Vservers here as well (without bringing up the VIP).
		if vip.Type == seesaw.AnycastVIP {
			continue
		}

		// TODO(jsing): Create a ncc.LBVserver that only encapsulates
		// the necessary state, rather than storing a full vserver
		// snapshot.
		lbVserver := v.snapshot()
		lbVserver.Services = nil
		lbVserver.Warnings = nil
		if err := v.engine.lbInterface.AddVserver(lbVserver, vip.IP.AF()); err != nil {
			log.Fatalf("%v: failed to add Vserver: %v", v, err)
		}
		v.lbVservers[vip.IP] = lbVserver

		if err := v.engine.lbInterface.AddVIP(vip); err != nil {
			log.Fatalf("%v: failed to add VIP %v: %v", v, vip.IP, err)
		}
		v.vips[*vip] = true
	}
}
999976
func (s *PutBucketEncryptionInput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *PutBucketEncryptionInput {
	s.ServerSideEncryptionConfiguration = v
	return s
}
1135114
func (s *EnvSettings) AddFlagsTLS(fs *pflag.FlagSet) {
	fs.StringVar(&s.TLSServerName, "tls-hostname", s.TillerHost, "the server name used to verify the hostname on the returned certificates from the server")
	fs.StringVar(&s.TLSCaCertFile, "tls-ca-cert", DefaultTLSCaCert, "path to TLS CA certificate file")
	fs.StringVar(&s.TLSCertFile, "tls-cert", DefaultTLSCert, "path to TLS certificate file")
	fs.StringVar(&s.TLSKeyFile, "tls-key", DefaultTLSKeyFile, "path to TLS key file")
	fs.BoolVar(&s.TLSVerify, "tls-verify", DefaultTLSVerify, "enable TLS for request and verify remote")
	fs.BoolVar(&s.TLSEnable, "tls", DefaultTLSEnable, "enable TLS for request")
}
850201
func NewServerTLS(addr string,
	handler func(conn Conn, cmd Command),
	accept func(conn Conn) bool,
	closed func(conn Conn, err error),
	config *tls.Config,
) *TLSServer {
	return NewServerNetworkTLS("tcp", addr, handler, accept, closed, config)
}