当前位置: 首页>>代码示例>>Golang>>正文


Golang Config.RootCAs方法代码示例

本文整理汇总了Golang中crypto/tls.Config.RootCAs方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.RootCAs方法的具体用法?Golang Config.RootCAs怎么用?Golang Config.RootCAs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在crypto/tls.Config的用法示例。


在下文中一共展示了Config.RootCAs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: performRequest

// performRequest performs an HTTP request r to Synthing API
func performRequest(r *http.Request) (*http.Response, error) {
	request, err := prepareApiRequestForSyncthing(r)
	if request == nil {
		return nil, err
	}
	var tlsCfg tls.Config
	if cert != nil {
		tlsCfg.RootCAs = x509.NewCertPool()
		tlsCfg.RootCAs.AddCert(cert)
		// Always use this certificate
		tlsCfg.ServerName = cert.Subject.CommonName
	}
	tr := &http.Transport{
		TLSClientConfig:       &tlsCfg,
		ResponseHeaderTimeout: requestTimeout,
		DisableKeepAlives:     true,
	}
	client := &http.Client{
		Transport: tr,
		Timeout:   requestTimeout,
	}
	res, err := client.Do(request)
	if res != nil && res.StatusCode == 403 {
		Warning.Printf("Error: HTTP POST forbidden. Missing API key?")
		return res, errors.New("HTTP POST forbidden")
	}
	return res, err
}
开发者ID:syncthing,项目名称:syncthing-inotify,代码行数:29,代码来源:syncwatcher.go

示例2: ClientConfig

func (c Config) ClientConfig() (client.Config, error) {
	if c.InCluster {
		return client.NewConfigInCluster()
	}
	var t *tls.Config
	if c.CAPath != "" {
		t = &tls.Config{}
		caCert, err := ioutil.ReadFile(c.CAPath)
		if err != nil {
			return client.Config{}, errors.Wrapf(err, "failed to read ca-path %q", c.CAPath)
		}
		caCertPool := x509.NewCertPool()
		successful := caCertPool.AppendCertsFromPEM(caCert)
		if !successful {
			return client.Config{}, errors.New("failed to parse ca certificate as PEM encoded content")
		}
		t.RootCAs = caCertPool
	}
	return client.Config{
		URLs:      c.APIServers,
		Namespace: c.Namespace,
		Token:     c.Token,
		TLSConfig: t,
	}, nil
}
开发者ID:influxdata,项目名称:kapacitor,代码行数:25,代码来源:config.go

示例3: TestTLSConnection

func TestTLSConnection(t *testing.T) {
	reactor := NewReactor()
	client := reactor.CreateServer("local")

	initialiseServerConnection(client)

	// generate a test certificate to use
	priv, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)

	duration30Days, _ := time.ParseDuration("-30h")
	notBefore := time.Now().Add(duration30Days) // valid 30 hours ago
	duration1Year, _ := time.ParseDuration("90h")
	notAfter := notBefore.Add(duration1Year) // for 90 hours

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"gIRC-Go Co"},
		},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA: true,
	}

	template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1"))
	template.IPAddresses = append(template.IPAddresses, net.ParseIP("::"))
	template.DNSNames = append(template.DNSNames, "localhost")

	derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)

	c := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	b, _ := x509.MarshalECPrivateKey(priv)
	k := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})

	// we mock up a server connection to test the client
	listenerKeyPair, _ := tls.X509KeyPair(c, k)

	var listenerTLSConfig tls.Config
	listenerTLSConfig.Certificates = make([]tls.Certificate, 0)
	listenerTLSConfig.Certificates = append(listenerTLSConfig.Certificates, listenerKeyPair)
	listener, _ := tls.Listen("tcp", ":0", &listenerTLSConfig)

	// mock up the client side too
	clientTLSCertPool := x509.NewCertPool()
	clientTLSCertPool.AppendCertsFromPEM(c)

	var clientTLSConfig tls.Config
	clientTLSConfig.RootCAs = clientTLSCertPool
	clientTLSConfig.ServerName = "localhost"
	go client.Connect(listener.Addr().String(), true, &clientTLSConfig)
	go client.ReceiveLoop()

	testServerConnection(t, reactor, client, listener)
}
开发者ID:DanielOaks,项目名称:girc-go,代码行数:60,代码来源:reactor_test.go

示例4: NewBuilder

// NewBuilder is the constructor for a new default Builder instance.
func NewBuilder(apiServerURL, username, password, awsKey, awsSecret, awsRegion string, locker locks.Locker, buildScriptsRepo, buildScriptsRepoBranch string) Builder {

	tlsConfig := tls.Config{}
	caCert, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")
	if err != nil {
		Log.Printf("Skipping Kubernetes master TLS verify: %v\n", err)
		tlsConfig.InsecureSkipVerify = true
	} else {
		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)
		tlsConfig.RootCAs = caCertPool
		Log.Println("Kubernetes master secured with TLS")
	}

	apiClient := &http.Client{Transport: &http.Transport{
		TLSClientConfig: &tlsConfig,
	}}

	data, _ := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")

	return DefaultBuilder{
		MasterURL:              apiServerURL,
		apiToken:               string(data),
		UserName:               username,
		Password:               password,
		Locker:                 locker,
		AWSAccessKeyID:         awsKey,
		AWSAccessSecret:        awsSecret,
		AWSRegion:              awsRegion,
		apiClient:              apiClient,
		maxPods:                10,
		buildScriptsRepo:       buildScriptsRepo,
		buildScriptsRepoBranch: buildScriptsRepoBranch,
	}
}
开发者ID:ae6rt,项目名称:decap,代码行数:36,代码来源:buildlauncher.go

示例5: Connect

func (c *tlsClient) Connect(timeout time.Duration) error {
	host, _, err := net.SplitHostPort(c.hostport)
	if err != nil {
		return err
	}

	var tlsconfig tls.Config
	tlsconfig.MinVersion = c.tls.MinVersion
	tlsconfig.RootCAs = c.tls.RootCAs
	tlsconfig.Certificates = c.tls.Certificates
	tlsconfig.ServerName = host

	if err := c.tcpClient.Connect(timeout); err != nil {
		return c.onFail(err)
	}

	socket := tls.Client(c.Conn, &tlsconfig)
	if err := socket.SetDeadline(time.Now().Add(timeout)); err != nil {
		_ = socket.Close()
		return c.onFail(err)
	}
	if err := socket.Handshake(); err != nil {
		_ = socket.Close()
		return c.onFail(err)
	}

	c.Conn = socket
	c.connected = true
	return nil
}
开发者ID:rhoml,项目名称:packetbeat,代码行数:30,代码来源:transport.go

示例6: GetServerTLSConfig

// GetServerTLSConfig returns a TLS config for using with ListenAndServeTLS
// This sets up the Root and Client CAs for verification
func GetServerTLSConfig(caCert, serverCert, serverKey []byte, allowInsecure bool) (*tls.Config, error) {
	// TLS config
	var tlsConfig tls.Config
	tlsConfig.InsecureSkipVerify = allowInsecure
	certPool := x509.NewCertPool()

	// load system certs
	if err := loadSystemCertificates(certPool); err != nil {
		return nil, err
	}

	// append custom CA
	certPool.AppendCertsFromPEM(caCert)

	tlsConfig.RootCAs = certPool
	tlsConfig.ClientCAs = certPool

	log.Debugf("tls root CAs: %d", len(tlsConfig.RootCAs.Subjects()))

	// require client auth
	tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven

	// server cert
	keypair, err := tls.X509KeyPair(serverCert, serverKey)
	if err != nil {
		return &tlsConfig, err

	}
	tlsConfig.Certificates = []tls.Certificate{keypair}

	return &tlsConfig, nil
}
开发者ID:XuesongYang,项目名称:shipyard,代码行数:34,代码来源:tlsutils.go

示例7: ServerConfig

// Generates a tls.Config object for a server from the given files.
func (info TLSInfo) ServerConfig() (*tls.Config, error) {
	// Both the key and cert must be present.
	if info.KeyFile == "" || info.CertFile == "" {
		return nil, fmt.Errorf("KeyFile and CertFile must both be present[key: %v, cert: %v]", info.KeyFile, info.CertFile)
	}

	var cfg tls.Config

	tlsCert, err := tls.LoadX509KeyPair(info.CertFile, info.KeyFile)
	if err != nil {
		return nil, err
	}

	cfg.Certificates = []tls.Certificate{tlsCert}

	if info.CAFile != "" {
		cfg.ClientAuth = tls.RequireAndVerifyClientCert
		cp, err := newCertPool(info.CAFile)
		if err != nil {
			return nil, err
		}

		cfg.RootCAs = cp
		cfg.ClientCAs = cp
	} else {
		cfg.ClientAuth = tls.NoClientCert
	}

	return &cfg, nil
}
开发者ID:kakkartushar1,项目名称:ArangoDB,代码行数:31,代码来源:tls_info.go

示例8: TestTLSAnonymousClient

// TestTLSAnonymousClient asserts that TLS-encrypted communication between the etcd
// server and an anonymous client works
func TestTLSAnonymousClient(t *testing.T) {
	proc, err := startServer([]string{
		"-cert-file=../../fixtures/ca/server.crt",
		"-key-file=../../fixtures/ca/server.key.insecure",
	})
	if err != nil {
		t.Fatal(err.Error())
	}
	defer stopServer(proc)

	cacertfile := "../../fixtures/ca/ca.crt"

	cp := x509.NewCertPool()
	bytes, err := ioutil.ReadFile(cacertfile)
	if err != nil {
		panic(err)
	}
	cp.AppendCertsFromPEM(bytes)

	cfg := tls.Config{}
	cfg.RootCAs = cp

	client := buildTLSClient(&cfg)
	err = assertServerFunctional(client, "https")
	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:joshuaconner,项目名称:etcd,代码行数:30,代码来源:etcd_tls_test.go

示例9: newH2Transport

func (client *Client) newH2Transport() http.RoundTripper {
	tlsConfig := tls.Config{
		InsecureSkipVerify: os.Getenv("TEST_MODE") == "1",
	}

	if client.ServerUrl.Scheme == "tcp" {
		// 1. LoadClientCert
		cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
		if err != nil {
			log.WithError(err).Fatal("loading server certificate")
		}

		// 2. LoadCACert
		caCert, err := ioutil.ReadFile("chain.pem")
		if err != nil {
			log.WithError(err).Fatal("loading CA certificate")
		}
		caPool := x509.NewCertPool()
		caPool.AppendCertsFromPEM(caCert)

		tlsConfig.RootCAs = caPool
		tlsConfig.Certificates = []tls.Certificate{cert}
	}

	return &http2.Transport{
		TLSClientConfig: &tlsConfig,
		DialTLS:         client.DialProxyTLS,
	}
}
开发者ID:empirefox,项目名称:wsh2c,代码行数:29,代码来源:client.go

示例10: buildTLSClientConfig

func buildTLSClientConfig(ca, cert, key []byte, parseKeyPair keypairFunc) (*tls.Config, error) {
	if len(cert) == 0 && len(key) == 0 {
		return &tls.Config{InsecureSkipVerify: true}, nil
	}

	tlsCert, err := parseKeyPair(cert, key)
	if err != nil {
		return nil, err
	}

	cfg := tls.Config{
		Certificates: []tls.Certificate{tlsCert},
		MinVersion:   tls.VersionTLS10,
	}

	if len(ca) != 0 {
		cp, err := newCertPool(ca)
		if err != nil {
			return nil, err
		}
		cfg.RootCAs = cp
	}

	return &cfg, nil
}
开发者ID:ericcapricorn,项目名称:deis,代码行数:25,代码来源:client.go

示例11: Dial

// Makes an outgoing connection using that protocol type to the given node ID.
// Returns a non-nil error if it is unable to connect.
// Panics if it is called with protocol set to CLIENT_PROTOCOL.
func Dial(protocol int, id uint16) (*BaseConn, error) {

	log.Print("dialing node ", id)

	if protocol == CLIENT_PROTOCOL {
		panic("tried to make outgoing client protocol connection")
	}

	ip := config.NodeIP(id)
	ipStr := ip.String()
	port := getProtocolPort(protocol)
	portStr := strconv.FormatInt(int64(port), 10)

	tlsConfig := new(tls.Config)
	tlsConfig.Certificates = []tls.Certificate{*config.Certificate()}
	tlsConfig.RootCAs = config.NodeCertPool(id)

	// We rely on the receiving node to do TLS authentication for now.
	// This is safe because it verifies our identity for us.
	// Backwards to the usual arrangement but should be secure.
	tlsConfig.InsecureSkipVerify = true

	tlsConn, err := tls.Dial("tcp", ipStr+":"+portStr, tlsConfig)
	if err != nil {
		log.Print(err)
		return nil, err
	}

	return newBaseConn(tlsConn), nil
}
开发者ID:jbeshir,项目名称:unanimity,代码行数:33,代码来源:dial.go

示例12: TestTLSHandshake

// Tests that the server has handshaked the connection and seen the client
// protocol announcement.  Does not nest that the connection.open is successful.
func TestTLSHandshake(t *testing.T) {
	srv := startTlsServer()
	defer srv.Close()

	cfg := new(tls.Config)
	cfg.RootCAs = x509.NewCertPool()
	cfg.RootCAs.AppendCertsFromPEM([]byte(caCert))

	cert, _ := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))
	cfg.Certificates = append(cfg.Certificates, cert)

	c, err := amqp.DialTLS(srv.URL, cfg)

	select {
	case <-time.After(10 * time.Millisecond):
		t.Fatalf("did not succeed to handshake the TLS connection after 10ms")
	case header := <-srv.Header:
		if string(header) != "AMQP" {
			t.Fatalf("expected to handshake a TLS connection, got err: %v", err)
		}
	}

	if st := c.ConnectionState(); !st.HandshakeComplete {
		t.Errorf("TLS handshake failed, TLS connection state: %+v", st)
	}
}
开发者ID:streadway,项目名称:amqp,代码行数:28,代码来源:tls_test.go

示例13: getTlsConfig

func getTlsConfig(verify bool, cert, key, ca string) (*tls.Config, error) {
	var config tls.Config
	config.InsecureSkipVerify = true
	if verify {
		certPool := x509.NewCertPool()
		file, err := ioutil.ReadFile(ca)
		if err != nil {
			return nil, err
		}
		certPool.AppendCertsFromPEM(file)
		config.RootCAs = certPool
		config.InsecureSkipVerify = false
	}

	_, errCert := os.Stat(cert)
	_, errKey := os.Stat(key)
	if errCert == nil || errKey == nil {
		tlsCert, err := tls.LoadX509KeyPair(cert, key)
		if err != nil {
			return nil, fmt.Errorf("Couldn't load X509 key pair: %v. Key encrpyted?\n", err)
		}
		config.Certificates = []tls.Certificate{tlsCert}
	}
	config.MinVersion = tls.VersionTLS10

	return &config, nil
}
开发者ID:chenjun3092,项目名称:docker-grand-ambassador,代码行数:27,代码来源:grand_ambassador.go

示例14: ClientConfig

// Generates a tls.Config object for a client from the given files.
func (info TLSInfo) ClientConfig() (*tls.Config, error) {
	var cfg tls.Config

	if info.KeyFile == "" || info.CertFile == "" {
		return &cfg, nil
	}

	tlsCert, err := tls.LoadX509KeyPair(info.CertFile, info.KeyFile)
	if err != nil {
		return nil, err
	}

	cfg.Certificates = []tls.Certificate{tlsCert}

	if info.CAFile != "" {
		cp, err := newCertPool(info.CAFile)
		if err != nil {
			return nil, err
		}

		cfg.RootCAs = cp
	}

	return &cfg, nil
}
开发者ID:kakkartushar1,项目名称:ArangoDB,代码行数:26,代码来源:tls_info.go

示例15: setupTls

func setupTls(caFile, certFile, keyFile string) {
	if caFile == "" || certFile == "" || keyFile == "" {
		return
	}
	caData, err := ioutil.ReadFile(caFile)
	if os.IsNotExist(err) {
		return
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load CA file\t%s\n",
			err)
		os.Exit(1)
	}
	caCertPool := x509.NewCertPool()
	if !caCertPool.AppendCertsFromPEM(caData) {
		fmt.Fprintln(os.Stderr, "Unable to parse CA file")
		os.Exit(1)
	}
	clientConfig := new(tls.Config)
	clientConfig.InsecureSkipVerify = true
	clientConfig.MinVersion = tls.VersionTLS12
	clientConfig.RootCAs = caCertPool
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if os.IsNotExist(err) {
		return
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load keypair\t%s\n",
			err)
		os.Exit(1)
	}
	clientConfig.Certificates = append(clientConfig.Certificates, cert)
	srpc.RegisterClientTlsConfig(clientConfig)
}
开发者ID:datatonic,项目名称:Dominator,代码行数:34,代码来源:tls.go


注:本文中的crypto/tls.Config.RootCAs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。