Ejemplo n.º 1
0
func loadCertFile(roots *x509.CertPool, fname string) error {
	data, err := ioutil.ReadFile(fname)
	if err == nil {
		roots.AppendCertsFromPEM(data)
	}
	return err
}
Ejemplo n.º 2
0
func newHTTPSTransport(tlsCertFile, tlsKeyFile, tlsCACertFile string) etcd.CancelableTransport {
	var cc *tls.Config = nil

	if tlsCertFile != "" && tlsKeyFile != "" {
		var rpool *x509.CertPool
		if tlsCACertFile != "" {
			if pemBytes, err := ioutil.ReadFile(tlsCACertFile); err == nil {
				rpool = x509.NewCertPool()
				rpool.AppendCertsFromPEM(pemBytes)
			}
		}

		if tlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile); err == nil {
			cc = &tls.Config{
				RootCAs:            rpool,
				Certificates:       []tls.Certificate{tlsCert},
				InsecureSkipVerify: true,
			}
		}
	}

	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig:     cc,
	}

	return tr
}
Ejemplo n.º 3
0
func (a *ldapAuther) Dial() error {
	var err error
	var certPool *x509.CertPool
	if a.server.RootCACert != "" {
		certPool := x509.NewCertPool()
		for _, caCertFile := range strings.Split(a.server.RootCACert, " ") {
			if pem, err := ioutil.ReadFile(caCertFile); err != nil {
				return err
			} else {
				if !certPool.AppendCertsFromPEM(pem) {
					return errors.New("Failed to append CA certificate " + caCertFile)
				}
			}
		}
	}
	for _, host := range strings.Split(a.server.Host, " ") {
		address := fmt.Sprintf("%s:%d", host, a.server.Port)
		if a.server.UseSSL {
			tlsCfg := &tls.Config{
				InsecureSkipVerify: a.server.SkipVerifySSL,
				ServerName:         host,
				RootCAs:            certPool,
			}
			a.conn, err = ldap.DialTLS("tcp", address, tlsCfg)
		} else {
			a.conn, err = ldap.Dial("tcp", address)
		}

		if err == nil {
			return nil
		}
	}
	return err
}
Ejemplo n.º 4
0
func (repo CloudControllerBuildpackBitsRepository) downloadBuildpack(url string, cb func(*os.File, error)) {
	fileutils.TempFile("buildpack-download", func(tempfile *os.File, err error) {
		if err != nil {
			cb(nil, err)
			return
		}

		var certPool *x509.CertPool
		if len(repo.TrustedCerts) > 0 {
			certPool = x509.NewCertPool()
			for _, tlsCert := range repo.TrustedCerts {
				cert, _ := x509.ParseCertificate(tlsCert.Certificate[0])
				certPool.AddCert(cert)
			}
		}

		client := &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{RootCAs: certPool},
				Proxy:           http.ProxyFromEnvironment,
			},
		}

		response, err := client.Get(url)
		if err != nil {
			cb(nil, err)
			return
		}

		io.Copy(tempfile, response.Body)
		tempfile.Seek(0, 0)
		cb(tempfile, nil)
	})
}
Ejemplo n.º 5
0
// getTLSConfig constructs a tls.Config that uses keys/certificates in the given files.
func getTLSConfig(certFile, keyFile, caFile string) (*tls.Config, error) {
	var certs []tls.Certificate
	if certFile != "" || keyFile != "" {
		if certFile == "" || keyFile == "" {
			return nil, util.Errorf("TLS client requires both cert file and key file")
		}
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			return nil, util.Errorf("Could not load keypair: %s", err)
		}
		certs = append(certs, cert)
	}

	var cas *x509.CertPool
	if caFile != "" {
		cas = x509.NewCertPool()
		caBytes, err := ioutil.ReadFile(caFile)
		if err != nil {
			return nil, err
		}
		ok := cas.AppendCertsFromPEM(caBytes)
		if !ok {
			return nil, util.Errorf("Could not parse certificate file: %s", caFile)
		}
	}

	tlsConfig := &tls.Config{
		Certificates: certs,
		ClientCAs:    cas,
		RootCAs:      cas,
	}
	return tlsConfig, nil
}
Ejemplo n.º 6
0
// loadTLSClientConfig initializes a *tls.Config using the given WebhookNotifierConfiguration.
//
// If no certificates are given, (nil, nil) is returned.
// The CA certificate is optional and falls back to the system default.
func loadTLSClientConfig(cfg *WebhookNotifierConfiguration) (*tls.Config, error) {
	if cfg.CertFile == "" || cfg.KeyFile == "" {
		return nil, nil
	}

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

	var caCertPool *x509.CertPool
	if cfg.CAFile != "" {
		caCert, err := ioutil.ReadFile(cfg.CAFile)
		if err != nil {
			return nil, err
		}
		caCertPool = x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)
	}

	tlsConfig := &tls.Config{
		ServerName:   cfg.ServerName,
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	}

	return tlsConfig, nil
}
Ejemplo n.º 7
0
func loadPEMCertificate(certPool *x509.CertPool, pemCerts []byte) (ok bool) {
	for len(pemCerts) > 0 {
		var block *pem.Block
		block, pemCerts = pem.Decode(pemCerts)
		if block == nil {
			break
		}
		if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
			continue
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			continue
		}

		// Assumption: CA is self-signed. Not recommended
		// for production environments.
		cert.IsCA = true
		certPool.AddCert(cert)
		ok = true
	}

	return
}
Ejemplo n.º 8
0
// NewRemoteServer generates a RemoteServer with the server address and
// the root CA the server uses to authenticate itself.
func NewRemoteServer(serverAddress, CAFile string) (*RemoteServer, error) {

	var rootCAs *x509.CertPool
	// populate a root CA pool from input CAfile
	// otherwise, use the system's default root CA set
	if CAFile != "" {
		rootCAs = x509.NewCertPool()
		pemBytes, err := ioutil.ReadFile(CAFile)
		if err != nil {
			return nil, errors.New("fail to read CA file: " + err.Error())
		}
		ok := rootCAs.AppendCertsFromPEM(pemBytes)
		if !ok {
			return nil, errors.New("fail to populate CA root pool.")
		}
	}

	tr := &http.Transport{
		TLSClientConfig:    &tls.Config{RootCAs: rootCAs},
		DisableCompression: true,
	}
	server := &RemoteServer{
		client:        &http.Client{Transport: tr},
		serverAddress: serverAddress,
	}
	return server, nil
}
Ejemplo n.º 9
0
/*
main registers this RP's HTTP request handlers; creates the HTTPS client for issuing OP ID Token requests and starts its HTTP server.
*/
func main() {
	var (
		certPool *x509.CertPool
		server   http.Server
		err      error
	)

	//This aeadCipher is used to encrypt/decrypt the Authn Request Cookie that is used to pass the Authn Request State value
	//from the Authn Request to the Authn Response.
	aeadCipher, err = aead.NewAEADCipher()
	if err != nil {
		return
	}

	//Initialize an HTTPS capable client and replace the default aws HTTP client that doesn't support HTTPS
	certPool = x509.NewCertPool()
	certPool.AppendCertsFromPEM([]byte(certbndl.PemCerts))
	opClient = &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{RootCAs: certPool},
		},
	}

	//Start the service
	server = http.Server{Addr: ":443", ReadTimeout: 10 * time.Minute, WriteTimeout: 10 * time.Minute, ErrorLog: logger.Logger()}
	http.HandleFunc("/login", handleLogin)
	http.HandleFunc("/authn-token", handleAuthnToken)
	logger.Println("Starting oidc on " + exthost + ":443")
	err = server.ListenAndServeTLS("resilient-networks.crt", "resilient-networks.key")
	if err != nil {
		logger.Fatal(err)
	}

}
Ejemplo n.º 10
0
func loadStore(roots *x509.CertPool, name string) {
	store, errno := syscall.CertOpenSystemStore(syscall.InvalidHandle, syscall.StringToUTF16Ptr(name))
	if errno != 0 {
		return
	}

	var cert *syscall.CertContext
	for {
		cert = syscall.CertEnumCertificatesInStore(store, cert)
		if cert == nil {
			break
		}

		var asn1Slice []byte
		hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&asn1Slice))
		hdrp.Data = cert.EncodedCert
		hdrp.Len = int(cert.Length)
		hdrp.Cap = int(cert.Length)

		buf := make([]byte, len(asn1Slice))
		copy(buf, asn1Slice)

		if cert, err := x509.ParseCertificate(buf); err == nil {
			roots.AddCert(cert)
		}
	}

	syscall.CertCloseStore(store, 0)
}
Ejemplo n.º 11
0
func GetHttpClient() *http.Client {
	if client != nil {
		return client
	} else {
		var certPool *x509.CertPool
		if pemfile := setting.KeystoneRootCAPEMFile; pemfile != "" {
			certPool = x509.NewCertPool()
			pemFileContent, err := ioutil.ReadFile(pemfile)
			if err != nil {
				panic(err)
			}
			if !certPool.AppendCertsFromPEM(pemFileContent) {
				log.Error(3, "Failed to load any certificates from Root CA PEM file %s", pemfile)
			} else {
				log.Info("Successfully loaded certificate(s) from %s", pemfile)
			}
		}
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{RootCAs: certPool,
				InsecureSkipVerify: !setting.KeystoneVerifySSLCert},
		}
		tr.Proxy = http.ProxyFromEnvironment

		client = &http.Client{Transport: tr}
		return client
	}
}
Ejemplo n.º 12
0
//func (ck *CertKit) GetTLSConfig(AuthRequired bool) (*tls.Config, error) {
func (ck *CertKit) GetTLSConfig(Access uint8) (*tls.Config, error) {
	var atype tls.ClientAuthType
	var tlsConfig *tls.Config
	var roots *x509.CertPool

	switch Access {
	case stonelizard.AccessNone:
		atype = tls.NoClientCert
	case stonelizard.AccessAuth, stonelizard.AccessAuthInfo:
		atype = tls.RequestClientCert
	case stonelizard.AccessVerifyAuth, stonelizard.AccessVerifyAuthInfo:
		atype = tls.RequireAndVerifyClientCert

		// Code adapted from crypto/x509/root_unix.go
		roots = x509.NewCertPool()

		for _, directory := range CertDirectories {
			fis, err := ioutil.ReadDir(directory)
			if err != nil {
				Goose.Auth.Logf(5, "Error scanning certificate directory %s: %s", directory, err)
				continue
			}
			for _, fi := range fis {
				data, err := ioutil.ReadFile(fmt.Sprintf("%s%c%s", directory, os.PathSeparator, fi.Name()))
				if err != nil {
					Goose.Auth.Logf(5, "Error load CA certificate from %s%c%s: %s", directory, os.PathSeparator, fi.Name(), err)
					continue
				}
				Goose.Auth.Logf(5, "Loaded CA certificate from %s%c%s: %s", directory, os.PathSeparator, fi.Name(), err)

				roots.AppendCertsFromPEM(data)
			}
		}
	}

	Goose.Auth.Logf(6, "authtype: %#v", atype)
	Goose.Auth.Logf(6, "CAs: %#v", roots)

	tlsConfig = &tls.Config{
		ClientAuth: atype,
		ClientCAs:  roots,
		//      InsecureSkipVerify: true,
		Certificates: make([]tls.Certificate, 1),
	}

	/*
	   srv.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(svc.PemPath + "/server.crt", svc.PemPath + "/server.key")
	   if err != nil {
	      Goose.InitServe.Logf(1,"Failed reading server certificates: %s",err)
	      return err
	   }
	*/

	tlsConfig.Certificates[0] = ck.ServerX509KeyPair
	Goose.Auth.Logf(5, "X509KeyPair used: %#v", tlsConfig.Certificates[0])
	tlsConfig.BuildNameToCertificate()

	return tlsConfig, nil
}
Ejemplo n.º 13
0
// ExtendedValidateRoute performs an extended validation on the route
// including checking that the TLS config is valid.
func ExtendedValidateRoute(route *routeapi.Route) field.ErrorList {
	tlsConfig := route.Spec.TLS
	result := field.ErrorList{}

	if tlsConfig == nil {
		return result
	}

	tlsFieldPath := field.NewPath("spec").Child("tls")
	if errs := validateTLS(route, tlsFieldPath); len(errs) != 0 {
		result = append(result, errs...)
	}

	// TODO: Check if we can be stricter with validating the certificate
	//       is for the route hostname. Don't want existing routes to
	//       break, so disable the hostname validation for now.
	// hostname := route.Spec.Host
	hostname := ""
	var certPool *x509.CertPool

	if len(tlsConfig.CACertificate) > 0 {
		certPool = x509.NewCertPool()
		if ok := certPool.AppendCertsFromPEM([]byte(tlsConfig.CACertificate)); !ok {
			result = append(result, field.Invalid(tlsFieldPath.Child("caCertificate"), tlsConfig.CACertificate, "failed to parse CA certificate"))
		}
	}

	verifyOptions := &x509.VerifyOptions{
		DNSName: hostname,
		Roots:   certPool,
	}

	if len(tlsConfig.Certificate) > 0 {
		if _, err := validateCertificatePEM(tlsConfig.Certificate, verifyOptions); err != nil {
			result = append(result, field.Invalid(tlsFieldPath.Child("certificate"), tlsConfig.Certificate, err.Error()))
		}

		certKeyBytes := []byte{}
		certKeyBytes = append(certKeyBytes, []byte(tlsConfig.Certificate)...)
		if len(tlsConfig.Key) > 0 {
			certKeyBytes = append(certKeyBytes, byte('\n'))
			certKeyBytes = append(certKeyBytes, []byte(tlsConfig.Key)...)
		}

		if _, err := tls.X509KeyPair(certKeyBytes, certKeyBytes); err != nil {
			result = append(result, field.Invalid(tlsFieldPath.Child("key"), tlsConfig.Key, err.Error()))
		}
	}

	if len(tlsConfig.DestinationCACertificate) > 0 {
		roots := x509.NewCertPool()
		if ok := roots.AppendCertsFromPEM([]byte(tlsConfig.DestinationCACertificate)); !ok {
			result = append(result, field.Invalid(tlsFieldPath.Child("destinationCACertificate"), tlsConfig.DestinationCACertificate, "failed to parse destination CA certificate"))
		}
	}

	return result
}
Ejemplo n.º 14
0
// LoadTLSConfig will load a certificate from config with all TLS based keys
// defined. If Certificate and CertificateKey are configured, client authentication
// will be configured. If no CAs are configured, the host CA will be used by go
// built-in TLS support.
func LoadTLSConfig(config MothershipConfig) (*tls.Config, error) {
	certificate := config.Certificate
	key := config.CertificateKey
	rootCAs := config.CAs
	hasCertificate := certificate != ""
	hasKey := key != ""

	var certs []tls.Certificate
	switch {
	case hasCertificate && !hasKey:
		return nil, ErrCertificateNoKey
	case !hasCertificate && hasKey:
		return nil, ErrKeyNoCertificate
	case hasCertificate && hasKey:
		cert, err := tls.LoadX509KeyPair(certificate, key)
		if err != nil {
			logp.Critical("Failed loading client certificate", err)
			return nil, err
		}
		certs = []tls.Certificate{cert}
	}

	var roots *x509.CertPool
	if len(rootCAs) > 0 {
		roots = x509.NewCertPool()
		for _, caFile := range rootCAs {
			pemData, err := ioutil.ReadFile(caFile)
			if err != nil {
				logp.Critical("Failed reading CA certificate: %s", err)
				return nil, err
			}

			if ok := roots.AppendCertsFromPEM(pemData); !ok {
				return nil, ErrNotACertificate
			}
		}
	}

	insecureSkipVerify := false
	if config.TLSInsecure != nil {
		insecureSkipVerify = *config.TLSInsecure
	}

	// Support minimal TLS 1.0.
	// TODO: check supported JRuby versions for logstash supported
	//       TLS 1.1 and switch
	tlsConfig := tls.Config{
		MinVersion:         tls.VersionTLS10,
		Certificates:       certs,
		RootCAs:            roots,
		InsecureSkipVerify: insecureSkipVerify,
	}
	return &tlsConfig, nil
}
Ejemplo n.º 15
0
func addCertsFromKeychain(pool *x509.CertPool, keychain string) error {
	cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain)
	data, err := cmd.Output()
	if err != nil {
		return err
	}

	pool.AppendCertsFromPEM(data)

	return nil
}
Ejemplo n.º 16
0
func (kvc *KVClient) prepareClient() error {
	hasCA := kvc.certificateAuthority != ""
	hasCert := kvc.clientCertificate != ""
	hasKey := kvc.clientKey != ""

	config := &store.Config{
		ConnectionTimeout: 5 * time.Second,
	}
	if hasCA || hasCert || hasKey {

		var cacert *x509.CertPool
		if kvc.certificateAuthority != "" {
			capem, err := ioutil.ReadFile(kvc.certificateAuthority)
			if err != nil {
				return err
			}
			cacert = x509.NewCertPool()
			if !cacert.AppendCertsFromPEM(capem) {
				return errors.New("unable to load certificate authority")
			}
		}

		var cert tls.Certificate
		if kvc.clientCertificate != "" && kvc.clientKey != "" {
			c := kvc.clientCertificate
			k := kvc.clientKey
			var err error
			cert, err = tls.LoadX509KeyPair(c, k)
			if err != nil {
				return err
			}
		}

		config.ClientTLS = &store.ClientTLSConfig{
			CertFile:   kvc.clientCertificate,
			KeyFile:    kvc.clientKey,
			CACertFile: kvc.certificateAuthority,
		}
		config.TLS = &tls.Config{
			RootCAs:      cacert,
			Certificates: []tls.Certificate{cert},
		}

	}
	store, err := libkv.NewStore(kvc.backend, kvc.addresses, config)
	if err != nil {
		fmt.Println(err)
		logrus.Error("unable to create kvclient. ", err)
		return err
	}
	kvc.store = store
	return nil
}
Ejemplo n.º 17
0
func NewClient() *Client {
	var caData []byte = nil
	var pool *x509.CertPool

	ac := new(Client)
	ac.insecure = false
	ac.host = os.Getenv("KUBERNETES_SERVICE_HOST")
	if ac.host != "" {
		// assume we are always on https
		ac.host = fmt.Sprintf("https://%s", ac.host)
		port := os.Getenv("KUBERNETES_SERVICE_PORT")
		if port != "" {
			ac.host = fmt.Sprintf("%s:%s", ac.host, port)
		}
	}

	ac.userAPI = os.Getenv("KUBERNETES_USER_API")
	if ac.userAPI == "" {
		ac.userAPI = "oapi"
	}

	ac.requireOpenshift, _ = strconv.ParseBool(os.Getenv("REGISTRY_ONLY"))

	ac.insecure, _ = strconv.ParseBool(os.Getenv("KUBERNETES_INSECURE"))
	if !ac.insecure {
		data := os.Getenv("KUBERNETES_CA_DATA")
		if data != "" {
			caData = []byte(data)
		}

		if caData == nil {
			var err error
			caData, err = ioutil.ReadFile(CA_PATH)
			if err != nil {
				log.Println(fmt.Sprintf("Couldn't load CA data: %s", err))
			}
		}

		if caData != nil {
			pool = x509.NewCertPool()
			pool.AppendCertsFromPEM(caData)
			ac.caData = base64.StdEncoding.EncodeToString(caData)
		}
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{RootCAs: pool, InsecureSkipVerify: ac.insecure},
	}
	ac.client = &http.Client{Transport: tr}

	return ac
}
Ejemplo n.º 18
0
func main() {
	configPath := flag.String("config", "", "config file")
	flag.Parse()

	var configs Config
	if _, err := toml.DecodeFile(*configPath, &configs); err != nil {
		log.Fatal(err)
	}
	// TODO: consider supporting multiple endpoints. for now just always
	//       use the first one
	config := configs.Endpoint[0]

	var roots *x509.CertPool

	roots = nil

	if len(config.RootCAs) > 0 {
		roots = x509.NewCertPool()
		for _, CA := range config.RootCAs {
			pem, err := ioutil.ReadFile(CA)
			if err != nil {
				log.Fatal(err)
			}
			ok := roots.AppendCertsFromPEM(pem)
			if !ok {
				log.Fatal("failed to parse CA certificate")
			}
		}
	}

	tr := &http.Transport{
		TLSClientConfig:    &tls.Config{RootCAs: roots},
		DisableCompression: true,
	}

	client = &http.Client{Transport: tr}
	plugin := &SplunkPlugin{Client: client,
		Token: config.AuthToken,
		Url:   "https://" + config.Host + ":" + strconv.Itoa(config.Port) + config.URL}

	p, err := loggerplugin.NewLoggerPlugin(plugin)
	if err != nil {
		log.Fatal(err)
	}

	err = p.Run()
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 19
0
func (c *CLI) GetTLSConfig(ctx *cli.Context) *tls.Config {
	var pool *x509.CertPool
	caCert, err := c.Config.Cluster.GetCertificateAuthority()
	if err != nil {
		// warn user
	} else {
		if caCert != nil {
			pool = x509.NewCertPool()
			pool.AddCert(caCert)
		}
	}
	return &tls.Config{
		RootCAs:            pool,
		InsecureSkipVerify: c.Config.Cluster.InsecureSkipVerify,
	}
}
Ejemplo n.º 20
0
func appendCerts(pool *x509.CertPool, certs []*x509.Certificate) *x509.CertPool {
	if len(certs) == 0 {
		// important to return unmodified (may be nil)
		return pool
	}

	if pool == nil {
		pool = x509.NewCertPool()
	}

	for _, cert := range certs {
		pool.AddCert(cert)
	}

	return pool
}
Ejemplo n.º 21
0
// New creates a new JSON-RPC over HTTPS client which uses the given
// certificate file to communicate with the server if the scheme of the URL is
// https.
func New(URL string, cert []byte) (*URLClient, error) {
	var pool *x509.CertPool
	transport := new(http.Transport)
	urlparsed, err := url.Parse(URL)
	if err != nil {
		return nil, err
	}
	if urlparsed.Scheme == "https" {
		pool = x509.NewCertPool()
		if !pool.AppendCertsFromPEM(cert) {
			return nil, ErrCertLoad
		}
		transport.TLSClientConfig = &tls.Config{RootCAs: pool}
	}
	return &URLClient{transport: transport, curl: URL}, nil
}
Ejemplo n.º 22
0
// AppendCA opens and parses the CA file and adds the certificates to
// the provided CertPool.
func (c *Config) AppendCA(pool *x509.CertPool) error {
	if c.CAFile == "" {
		return nil
	}

	// Read the file
	data, err := ioutil.ReadFile(c.CAFile)
	if err != nil {
		return fmt.Errorf("Failed to read CA file: %v", err)
	}

	if !pool.AppendCertsFromPEM(data) {
		return fmt.Errorf("Failed to parse any CA certificates")
	}

	return nil
}
Ejemplo n.º 23
0
/**
 * This creates a new certificates pool that can be used to validate user
 * certificate and synchronizes concurrent access to that pool.
 * This is expected since ServerHTTP run on their own goroutine
 * @param path is the path to retrieve CA certificates
 * @param c is the channel to write to
 * @see #PopulateCertPool(string)
 */
func CaCertPoolManager(path string, c chan *x509.CertPool) {

	var logger = NewPrefixed("security#CaCertPoolManager")

	caCertPool := new(x509.CertPool)
	caCertPool, err := populateCertPool(path)
	if err != nil {
		logger.Fatal(err.Error())
	}

	for {
		select {
		case c <- caCertPool:
			logger.Finest("Written caCertPool: %v", len(caCertPool.Subjects()))
		}
	}
}
Ejemplo n.º 24
0
func addCACert(path string, roots *x509.CertPool) *x509.CertPool {
	f, err := os.Open(path)
	if err != nil {
		log.Printf("Could not open CA cert: %v", err)
		return roots
	}

	fBytes, err := ioutil.ReadAll(f)
	if err != nil {
		log.Printf("Failed to read CA cert: %v", err)
		return roots
	}

	if !roots.AppendCertsFromPEM(fBytes) {
		log.Printf("Could not add client CA to pool: %v", err)
	}
	return roots
}
Ejemplo n.º 25
0
func (n *ng) newHttpTransport() etcd.CancelableTransport {

	var cc *tls.Config = nil

	if n.options.EtcdCertFile != "" && n.options.EtcdKeyFile != "" {
		var rpool *x509.CertPool = nil
		if n.options.EtcdCaFile != "" {
			if pemBytes, err := ioutil.ReadFile(n.options.EtcdCaFile); err == nil {
				rpool = x509.NewCertPool()
				rpool.AppendCertsFromPEM(pemBytes)
			} else {
				log.Errorf("Error reading Etcd Cert CA File: %v", err)
			}
		}

		if tlsCert, err := tls.LoadX509KeyPair(n.options.EtcdCertFile, n.options.EtcdKeyFile); err == nil {
			cc = &tls.Config{
				RootCAs:            rpool,
				Certificates:       []tls.Certificate{tlsCert},
				InsecureSkipVerify: true,
			}
		} else {
			log.Errorf("Error loading KeyPair for TLS client: %v", err)
		}

	}

	//Copied from etcd.DefaultTransport declaration
	//Wasn't sure how to make a clean reliable deep-copy, and instead
	//creating a new object was the safest and most reliable assurance
	//that we aren't overwriting some global struct potentially
	//shared by other etcd users.
	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig:     cc,
	}

	return tr
}
Ejemplo n.º 26
0
Archivo: setup.go Proyecto: tomzhang/p2
// getTLSClient constructs an HTTP client that uses keys/certificates in the given files.
func getTLSClient(certFile, keyFile, caFile string) (*http.Client, error) {
	var certs []tls.Certificate
	if certFile != "" || keyFile != "" {
		if certFile == "" || keyFile == "" {
			return nil, util.Errorf("TLS client requires both cert file and key file")
		}
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			return nil, err
		}
		certs = append(certs, cert)
	}

	var cas *x509.CertPool
	if caFile != "" {
		cas = x509.NewCertPool()
		caBytes, err := ioutil.ReadFile(caFile)
		if err != nil {
			return nil, err
		}
		ok := cas.AppendCertsFromPEM(caBytes)
		if !ok {
			return nil, util.Errorf("Could not parse certificate file: %s", caFile)
		}
	}

	if len(certs) == 0 && cas == nil {
		return http.DefaultClient, nil
	}

	tlsConfig := &tls.Config{
		Certificates: certs,
		ClientCAs:    cas,
		RootCAs:      cas,
	}
	return &http.Client{Transport: &http.Transport{
		TLSClientConfig: tlsConfig,
		// same dialer as http.DefaultTransport
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
	}}, nil
}
Ejemplo n.º 27
0
func loadSystemCertificates(certPool *x509.CertPool) error {
	if _, err := os.Stat(systemCertPath); os.IsNotExist(err) {
		return nil
	}

	log.Debugf("loading system certificates: dir=%s", systemCertPath)

	return filepath.Walk(systemCertPath, func(path string, fi os.FileInfo, err error) error {
		if !fi.IsDir() {
			cert, err := ioutil.ReadFile(path)
			if err != nil {
				return err
			}

			certPool.AppendCertsFromPEM(cert)
		}
		return nil
	})
}
Ejemplo n.º 28
0
func appendCertsFromPEMData(pool *x509.CertPool, data []byte) *x509.CertPool {
	if len(data) == 0 {
		return pool
	}

	// Bit of a dance, need to ensure if AppendCertsFromPEM fails we still return
	// nil and not an empty pool, so system roots still get used
	var ret *x509.CertPool
	if pool == nil {
		ret = x509.NewCertPool()
	} else {
		ret = pool
	}
	if !ret.AppendCertsFromPEM(data) {
		// Return unmodified input pool (may be nil, do not replace with empty)
		return pool
	}
	return ret

}
Ejemplo n.º 29
0
func (a *ApiClient) prepareClient() error {
	var cacert *x509.CertPool
	if a.certificateAuthority != "" {
		capem, err := ioutil.ReadFile(a.certificateAuthority)
		if err != nil {
			return err
		}
		cacert = x509.NewCertPool()
		if !cacert.AppendCertsFromPEM(capem) {
			return errors.New("unable to load certificate authority")
		}
	}

	var cert tls.Certificate
	if a.clientCertificate != "" && a.clientKey != "" {
		c := a.clientCertificate
		k := a.clientKey
		var err error
		cert, err = tls.LoadX509KeyPair(c, k)
		if err != nil {
			return err
		}
	}

	if cacert != nil || &cert != nil {
		config := &tls.Config{
			RootCAs:      cacert,
			Certificates: []tls.Certificate{cert},
		}
		transport := &http.Transport{
			TLSClientConfig:     config,
			TLSHandshakeTimeout: 5 * time.Second,
		}
		client := &http.Client{Transport: transport}
		a.Client = client
	} else {
		a.Client = &http.Client{}
	}
	return nil
}
Ejemplo n.º 30
0
func loadStore(roots *x509.CertPool, name string) {
	store, err := syscall.CertOpenSystemStore(syscall.InvalidHandle, syscall.StringToUTF16Ptr(name))
	if err != nil {
		return
	}
	defer syscall.CertCloseStore(store, 0)

	var cert *syscall.CertContext
	for {
		cert, err = syscall.CertEnumCertificatesInStore(store, cert)
		if err != nil {
			return
		}

		buf := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
		// ParseCertificate requires its own copy of certificate data to keep.
		buf2 := make([]byte, cert.Length)
		copy(buf2, buf)
		if c, err := x509.ParseCertificate(buf2); err == nil {
			roots.AddCert(c)
		}
	}
}