Example #1
1
// Starts listening for client connections.
// When a new application connects, launches listeners in a goroutine.
// Returns an error when error occurs.
func StartListen(port int, useTls bool, crtPath string, keyPath string, sname string) error {
	// Create a listening address
	addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		return err
	}

	// start a new server and listen on the address
	var l net.Listener
	l, err = net.ListenTCP("tcp", addr)
	if err != nil {
		return err
	}

	// wrap with TLS if required
	if useTls {
		cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
		if err != nil {
			return err
		}
		conf := tls.Config{}

		certs := make([]tls.Certificate, 1)
		certs[0] = cert
		conf.Certificates = certs

		cp := x509.NewCertPool()
		caCert, err := ioutil.ReadFile(crtPath)
		if err != nil {
			return err
		}
		if !cp.AppendCertsFromPEM(caCert) {
			return errors.New("Could not append PEM cert")
		}
		conf.RootCAs = cp

		conf.ServerName = sname

		conf.ClientAuth = tls.RequireAndVerifyClientCert

		conf.ClientCAs = cp

		l = tls.NewListener(l, &conf)
	}

	// at the end of this function close the server connection
	defer l.Close()

	logging.Debug("Starting listen loop")
	for {
		a, err := acceptApp(l)
		if err != nil {
			return err
		} else {
			logging.Debug("Got connection")
			go ListenForCommands(a)
		}
	}
	return nil
}
Example #2
1
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
}
Example #3
1
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)
}
Example #4
1
// 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,
	}
}
// 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
}
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
}
Example #7
0
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
}
Example #8
0
// 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)
	}
}
Example #9
0
func getTLSConfig() (*tls.Config, error) {
	// TLS config
	var tlsConfig tls.Config
	tlsConfig.InsecureSkipVerify = true
	certPool := x509.NewCertPool()

	file, err := ioutil.ReadFile(config.CACertificate)
	if err != nil {
		return nil, err
	}

	certPool.AppendCertsFromPEM(file)
	tlsConfig.RootCAs = certPool
	_, errCert := os.Stat(config.SSLCertificate)
	_, errKey := os.Stat(config.SSLKey)
	if errCert == nil && errKey == nil {
		cert, err := tls.LoadX509KeyPair(config.SSLCertificate, config.SSLKey)
		if err != nil {
			return &tlsConfig, err
		}
		tlsConfig.Certificates = []tls.Certificate{cert}
	}

	return &tlsConfig, nil
}
Example #10
0
// 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
}
Example #11
0
// 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)
	}
}
Example #12
0
// 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
}
Example #13
0
// 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
}
Example #14
0
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)
}
Example #15
0
func (host *Host) getTLSConfig() (*tls.Config, error) {
	var tlsConfig tls.Config

	if !host.TLS {
		return nil, nil
	}

	tlsConfig.InsecureSkipVerify = !host.TLSVerify

	if host.TLSVerify {
		certPool := x509.NewCertPool()
		file, err := ioutil.ReadFile(host.TLSCaCert)
		if err != nil {
			return nil, err
		}
		certPool.AppendCertsFromPEM(file)
		tlsConfig.RootCAs = certPool
	}

	cert, err := tls.LoadX509KeyPair(host.TLSCert, host.TLSKey)
	if err != nil {
		return nil, err
	}
	tlsConfig.Certificates = []tls.Certificate{cert}
	tlsConfig.MinVersion = tls.VersionTLS10

	return &tlsConfig, nil
}
Example #16
0
// 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
}
Example #17
0
// NewTLSServer creates and starts a TLS-enabled testing server.
func NewTLSServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request), tlsConfig TLSConfig) (*DockerServer, error) {
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		return nil, err
	}
	defaultCertificate, err := tls.LoadX509KeyPair(tlsConfig.CertPath, tlsConfig.CertKeyPath)
	if err != nil {
		return nil, err
	}
	tlsServerConfig := new(tls.Config)
	tlsServerConfig.Certificates = []tls.Certificate{defaultCertificate}
	if tlsConfig.RootCAPath != "" {
		rootCertPEM, err := ioutil.ReadFile(tlsConfig.RootCAPath)
		if err != nil {
			return nil, err
		}
		certsPool := x509.NewCertPool()
		certsPool.AppendCertsFromPEM(rootCertPEM)
		tlsServerConfig.RootCAs = certsPool
	}
	tlsListener := tls.NewListener(listener, tlsServerConfig)
	server := buildDockerServer(tlsListener, containerChan, hook)
	go http.Serve(tlsListener, server)
	return server, nil
}
Example #18
0
func getTlsConfig(endpointOpts EndpointOptions) (*tls.Config, error) {
	var tlsConfig *tls.Config

	if endpointOpts.TLS {

		tlsConfig = &tls.Config{
			InsecureSkipVerify: !endpointOpts.TLSVerify,
		}

		if endpointOpts.tlsCert() != "" && endpointOpts.tlsKey() != "" {

			cert, err := tls.LoadX509KeyPair(endpointOpts.tlsCert(), endpointOpts.tlsKey())
			if err != nil {
				return nil, err
			}
			tlsConfig.Certificates = []tls.Certificate{cert}
		}

		// Load CA cert
		if endpointOpts.tlsCaCert() != "" {

			caCert, err := ioutil.ReadFile(endpointOpts.tlsCaCert())
			if err != nil {
				return nil, err
			}
			caCertPool := x509.NewCertPool()
			caCertPool.AppendCertsFromPEM(caCert)

			tlsConfig.RootCAs = caCertPool
		}
	}
	return tlsConfig, nil
}
Example #19
0
func getTLSConfig(clientCertPEMData, clientKeyPEMData []byte) (*tls.Config, error) {
	certPool := x509.NewCertPool()

	certChainPath := os.Getenv("ORCHARD_HOST_CA")
	if certChainPath != "" {
		certChainData, err := ioutil.ReadFile(certChainPath)
		if err != nil {
			return nil, err
		}
		certPool.AppendCertsFromPEM(certChainData)
	} else {
		certPool.AppendCertsFromPEM([]byte(orchardCerts))
	}

	clientCert, err := tls.X509KeyPair(clientCertPEMData, clientKeyPEMData)
	if err != nil {
		return nil, err
	}

	config := new(tls.Config)
	config.RootCAs = certPool
	config.Certificates = []tls.Certificate{clientCert}
	config.BuildNameToCertificate()

	return config, nil
}
Example #20
0
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,
	}
}
Example #21
0
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
}
Example #22
0
func main() {
	flag.Parse()

	if *port == 0 {
		xport, err := strconv.Atoi(os.Getenv("PORT"))
		if err != nil {
			fmt.Println("Please specify the HTTP port (either flag or environment)")
			os.Exit(1)
		}
		*port = xport
	}

	if flag.NArg() < 1 {
		fmt.Println("Specify remote URL on the command line")
		os.Exit(1)
	}

	remote, err := url.Parse(flag.Arg(0))
	if err != nil {
		fmt.Println("error parsing remote URL", err)
		os.Exit(1)
	}

	transport := new(http.Transport)

	switch remote.Scheme {
	case "http":
		if *ca != "" {
			log.Println("ignoring ca flag for non-https remote")
		}

	case "https":
		if *ca != "" {
			pool := x509.NewCertPool()
			data, err := ioutil.ReadFile(*ca)
			if err != nil {
				log.Fatal(err)
				os.Exit(1)
			}
			pool.AppendCertsFromPEM(data)
			tlsconfig := new(tls.Config)
			tlsconfig.RootCAs = pool
			transport.TLSClientConfig = tlsconfig
		}

	default:
		fmt.Println("unsupported remote scheme:", remote.Scheme)
		os.Exit(1)
	}

	rp := &ReverseProxy{
		remote,
		transport,
	}

	log.Fatal(http.ListenAndServe(
		fmt.Sprintf(":%v", *port), rp))
}
Example #23
0
func convertTLSConfig(config *transport.TLSConfig) *tls.Config {
	var tlsConfig *tls.Config
	tlsConfig.Certificates = config.Certificates
	tlsConfig.CipherSuites = config.CipherSuites
	tlsConfig.RootCAs = config.RootCAs
	tlsConfig.CurvePreferences = config.CurvePreferences
	return tlsConfig

}
Example #24
0
func (c *Cluster) makeAgentConfig(bucket, password string, mt bool) (*gocbcore.AgentConfig, error) {
	authFn := func(srv gocbcore.AuthClient, deadline time.Time) error {
		// Build PLAIN auth data
		userBuf := []byte(bucket)
		passBuf := []byte(password)
		authData := make([]byte, 1+len(userBuf)+1+len(passBuf))
		authData[0] = 0
		copy(authData[1:], userBuf)
		authData[1+len(userBuf)] = 0
		copy(authData[1+len(userBuf)+1:], passBuf)

		// Execute PLAIN authentication
		_, err := srv.ExecSaslAuth([]byte("PLAIN"), authData, deadline)

		return err
	}

	memdHosts, httpHosts, isSslHosts := specToHosts(c.spec)

	var tlsConfig *tls.Config
	if isSslHosts {

		certpath := c.spec.Options.Get("certpath")

		tlsConfig = &tls.Config{}
		if certpath == "" {
			tlsConfig.InsecureSkipVerify = true
		} else {
			cacert, err := ioutil.ReadFile(certpath)
			if err != nil {
				return nil, err
			}

			roots := x509.NewCertPool()
			ok := roots.AppendCertsFromPEM(cacert)
			if !ok {
				return nil, ErrInvalidCert
			}
			tlsConfig.RootCAs = roots
		}
	}

	return &gocbcore.AgentConfig{
		MemdAddrs:            memdHosts,
		HttpAddrs:            httpHosts,
		TlsConfig:            tlsConfig,
		BucketName:           bucket,
		Password:             password,
		AuthHandler:          authFn,
		UseMutationTokens:    mt,
		ConnectTimeout:       c.connectTimeout,
		ServerConnectTimeout: c.serverConnectTimeout,
		NmvRetryDelay:        c.nmvRetryDelay,
	}, nil
}
// Retrieves the configuration from the config json
// builds the TaskConfig object and returns it
func (t *Tasks) GetConfig() *TaskConfig {

	if t.Config == nil {
		configuration := MainConfig{}

		if _, err := os.Stat(t.ConfigFile); os.IsNotExist(err) == false {
			log.Printf("Config file found - loading configuration")

			file, _ := os.Open(t.ConfigFile)
			decoder := json.NewDecoder(file)
			err := decoder.Decode(&configuration)
			if err != nil {
				log.Printf("Error decoding configuration: %s\n", err)
			}
		} else {
			//setup defaults
			log.Printf("No config file found, using defaults.")
			configuration.Cafile = "/vagrant/ssl/cacert.pem"
			configuration.Keyfile = "/vagrant/ssl/key.pem"
			configuration.Certfile = "/vagrant/ssl/cert.pem"
			configuration.Username = "******"
			configuration.Password = "******"
			configuration.Host = "proxy"
			configuration.Port = "5671"
			configuration.CN = "rabbit"
		}

		rootCa, err := ioutil.ReadFile(configuration.Cafile)
		if err != nil {
			panic(err)
		}
		clientKey, err := ioutil.ReadFile(configuration.Keyfile)
		if err != nil {
			panic(err)
		}
		clientCert, err := ioutil.ReadFile(configuration.Certfile)
		if err != nil {
			panic(err)
		}

		cfg := new(tls.Config)
		cfg.RootCAs = x509.NewCertPool()
		cfg.RootCAs.AppendCertsFromPEM([]byte(rootCa))
		cfg.ServerName = configuration.CN

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

		result := new(TaskConfig)
		result.TlsConfig = cfg
		result.Uri = fmt.Sprintf("amqps://%s:%s@%s:%s/", configuration.Username, configuration.Password, configuration.Host, configuration.Port)
		t.Config = result
	}
	return t.Config
}
Example #26
0
// ConfigureTLS sets up the RootCAs on the provided tls.Config based on the
// Config specified.
func ConfigureTLS(t *tls.Config, c *Config) error {
	if t == nil {
		return nil
	}
	pool, err := LoadCACerts(c)
	if err != nil {
		return err
	}
	t.RootCAs = pool
	return nil
}
Example #27
0
func newDockerClient() *client.DockerCli {
	// Set terminal emulation based on platform as required.
	stdin, stdout, stderr := term.StdStreams()

	setDefaultConfFlag(flTrustKey, defaultTrustKeyFile)

	if len(flHosts) > 1 {
		log.Fatal("Please specify only one -H")
	}
	protoAddrParts := strings.SplitN(flHosts[0], "://", 2)

	var (
		cli       *client.DockerCli
		tlsConfig tls.Config
	)
	tlsConfig.InsecureSkipVerify = true

	// Regardless of whether the user sets it to true or false, if they
	// specify --tlsverify at all then we need to turn on tls
	if flag.IsSet("-tlsverify") {
		*flTls = true
	}

	// If we should verify the server, we need to load a trusted ca
	if *flTlsVerify {
		certPool := x509.NewCertPool()
		file, err := ioutil.ReadFile(*flCa)
		if err != nil {
			log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err)
		}
		certPool.AppendCertsFromPEM(file)
		tlsConfig.RootCAs = certPool
		tlsConfig.InsecureSkipVerify = false
	}

	// If tls is enabled, try to load and send client certificates
	if *flTls || *flTlsVerify {
		_, errCert := os.Stat(*flCert)
		_, errKey := os.Stat(*flKey)
		if errCert == nil && errKey == nil {
			*flTls = true
			cert, err := tls.LoadX509KeyPair(*flCert, *flKey)
			if err != nil {
				log.Fatalf("Couldn't load X509 key pair: %q. Make sure the key is encrypted", err)
			}
			tlsConfig.Certificates = []tls.Certificate{cert}
		}
		// Avoid fallback to SSL protocols < TLS1.0
		tlsConfig.MinVersion = tls.VersionTLS10
	}

	cli = client.NewDockerCli(stdin, stdout, stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
	return cli
}
Example #28
0
File: conn.go Project: jpoz/pq
func (cn *conn) setupSSLCertKey(tlsConf *tls.Config, o values) {
	sslkey := o.Get("sslkey")
	sslcert := o.Get("sslcert")

	if sslkey != "" && sslcert != "" {
		// If the user has set a sslkey and sslcert make sure they exist
		files := []string{sslkey, sslcert}
		for _, f := range files {
			_, err := os.Stat(f)
			if err != nil {
				panic(err)
			}
		}
	} else {
		// Automatically load certificates from ~/.postgresql
		user, err := user.Current()
		if err == nil {
			sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
			sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
		}
	}

	kstat, kerr := os.Stat(sslkey)

	if kerr == nil {
		kmode := kstat.Mode()
		if kmode == kmode&0600 {
			cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
			if err != nil {
				panic(err)
			}
			tlsConf.Certificates = []tls.Certificate{cert}
		} else {
			panic(ErrSSLKeyHasWorldPermissions)
		}
	}

	if o.Get("sslrootcert") != "" {
		tlsConf.RootCAs = x509.NewCertPool()

		cert, err := ioutil.ReadFile(o.Get("sslrootcert"))

		if err != nil {
			panic(err)
		}

		ok := tlsConf.RootCAs.AppendCertsFromPEM(cert)

		if !ok {
			errorf("couldn't parse pem in sslrootcert")
		}
	}
}
Example #29
0
func configureTLS(t *testing.T) *tls.Config {
	cert, err := tls.X509KeyPair(localhostCert, localhostKey)
	if err != nil {
		t.Fatal("failed to load x509 key pair", err)
	}

	cfg := tls.Config{Certificates: []tls.Certificate{cert}}
	x509Cert, err := x509.ParseCertificate(cfg.Certificates[0].Certificate[0])
	cfg.RootCAs = x509.NewCertPool()
	cfg.RootCAs.AddCert(x509Cert)
	return &cfg
}
Example #30
0
// tlsConfig translates the command-line options into a tls.Config struct
func tlsConfig(c *cli.Context) (*tls.Config, error) {
	var tlsConfig *tls.Config
	var err error
	caCertFlag := c.GlobalString("tlscacert")
	certFlag := c.GlobalString("tlscert")
	keyFlag := c.GlobalString("tlskey")

	if c.GlobalBool("tls") || c.GlobalBool("tlsverify") {
		tlsConfig = &tls.Config{
			InsecureSkipVerify: !c.GlobalBool("tlsverify"),
		}

		// Load CA cert
		if caCertFlag != "" {
			var caCert []byte

			if strings.HasPrefix(caCertFlag, "/") {
				caCert, err = ioutil.ReadFile(caCertFlag)
				if err != nil {
					return nil, err
				}
			} else {
				caCert = []byte(caCertFlag)
			}

			caCertPool := x509.NewCertPool()
			caCertPool.AppendCertsFromPEM(caCert)

			tlsConfig.RootCAs = caCertPool
		}

		// Load client certificate
		if certFlag != "" && keyFlag != "" {
			var cert tls.Certificate

			if strings.HasPrefix(certFlag, "/") && strings.HasPrefix(keyFlag, "/") {
				cert, err = tls.LoadX509KeyPair(certFlag, keyFlag)
				if err != nil {
					return nil, err
				}
			} else {
				cert, err = tls.X509KeyPair([]byte(certFlag), []byte(keyFlag))
				if err != nil {
					return nil, err
				}
			}
			tlsConfig.Certificates = []tls.Certificate{cert}
		}
	}

	return tlsConfig, nil
}