コード例 #1
0
func ServerTLSListen(service string, f func(conn net.Conn)) {

	// Load x509 certificates for our private/public key, makecert.sh will
	// generate them for you.

	cert, err := tls.LoadX509KeyPair("certs/server.pem", "certs/server.key")
	if err != nil {
		log.Fatalf("server: loadkeys: %s", err)
	}
	// Note if we don't tls.RequireAnyClientCert client side certs are ignored.
	config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert}
	config.Rand = rand.Reader
	listener, err := tls.Listen("tcp", service, &config)
	if err != nil {
		log.Fatalf("server: listen: %s", err)
	}
	log.Print("server: listening")
	// Keep this loop simple/fast as to be able to handle new connections
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("server: accept: %s", err)
			break
		}
		log.Printf("server: accepted from %s", conn.RemoteAddr())
		// Fire off go routing to handle rest of connection.
		go handleClient(conn, f)
	}
}
コード例 #2
0
ファイル: server.go プロジェクト: rawlingsj/gofabric8
// 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
}
コード例 #3
0
ファイル: conn.go プロジェクト: jpoz/pq
func (cn *conn) ssl(o values) {
	tlsConf := tls.Config{}
	switch mode := o.Get("sslmode"); mode {
	case "require", "":
		tlsConf.InsecureSkipVerify = true
	case "verify-full":
		// fall out
	case "disable":
		return
	default:
		errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode)
	}

	cn.setupSSLCertKey(&tlsConf, o)

	w := cn.writeBuf(0)
	w.int32(80877103)
	cn.send(w)

	b := cn.scratch[:1]
	_, err := io.ReadFull(cn.c, b)
	if err != nil {
		panic(err)
	}

	if b[0] != 'S' {
		panic(ErrSSLNotSupported)
	}

	cn.c = tls.Client(cn.c, &tlsConf)
}
コード例 #4
0
ファイル: conn.go プロジェクト: chinna1986/vitess
// DialTablet creates and initializes TabletBson.
func DialTablet(context context.Context, endPoint topo.EndPoint, keyspace, shard string, timeout time.Duration) (tabletconn.TabletConn, error) {
	var addr string
	var config *tls.Config
	if *tabletBsonEncrypted {
		addr = fmt.Sprintf("%v:%v", endPoint.Host, endPoint.NamedPortMap["_vts"])
		config = &tls.Config{}
		config.InsecureSkipVerify = true
	} else {
		addr = fmt.Sprintf("%v:%v", endPoint.Host, endPoint.NamedPortMap["_vtocc"])
	}

	conn := &TabletBson{endPoint: endPoint}
	var err error
	if *tabletBsonUsername != "" {
		conn.rpcClient, err = bsonrpc.DialAuthHTTP("tcp", addr, *tabletBsonUsername, *tabletBsonPassword, timeout, config)
	} else {
		conn.rpcClient, err = bsonrpc.DialHTTP("tcp", addr, timeout, config)
	}
	if err != nil {
		return nil, tabletError(err)
	}

	var sessionInfo tproto.SessionInfo
	if err = conn.rpcClient.Call("SqlQuery.GetSessionId", tproto.SessionParams{Keyspace: keyspace, Shard: shard}, &sessionInfo); err != nil {
		conn.rpcClient.Close()
		return nil, tabletError(err)
	}
	conn.sessionID = sessionInfo.SessionId
	return conn, nil
}
コード例 #5
0
ファイル: conn.go プロジェクト: pranjal5215/vitess
// DialTablet creates and initializes TabletBson.
func DialTablet(ctx context.Context, endPoint topo.EndPoint, keyspace, shard string, timeout time.Duration) (tabletconn.TabletConn, error) {
	var addr string
	var config *tls.Config
	if *tabletBsonEncrypted {
		addr = netutil.JoinHostPort(endPoint.Host, endPoint.NamedPortMap["vts"])
		config = &tls.Config{}
		config.InsecureSkipVerify = true
	} else {
		addr = netutil.JoinHostPort(endPoint.Host, endPoint.NamedPortMap["vt"])
	}

	conn := &TabletBson{endPoint: endPoint}
	var err error
	if *tabletBsonUsername != "" {
		conn.rpcClient, err = bsonrpc.DialAuthHTTP("tcp", addr, *tabletBsonUsername, *tabletBsonPassword, timeout, config)
	} else {
		conn.rpcClient, err = bsonrpc.DialHTTP("tcp", addr, timeout, config)
	}
	if err != nil {
		return nil, tabletError(err)
	}

	var sessionInfo tproto.SessionInfo
	if err = conn.rpcClient.Call(ctx, "SqlQuery.GetSessionId", tproto.SessionParams{Keyspace: keyspace, Shard: shard}, &sessionInfo); err != nil {
		conn.rpcClient.Close()
		return nil, tabletError(err)
	}
	// SqlQuery.GetSessionId might return an application error inside the SessionInfo
	if err = vterrors.FromRPCError(sessionInfo.Err); err != nil {
		conn.rpcClient.Close()
		return nil, tabletError(err)
	}
	conn.sessionID = sessionInfo.SessionId
	return conn, nil
}
コード例 #6
0
ファイル: server.go プロジェクト: gembler/blade-libs
func runServer(transportFactory thrift.TTransportFactory, protocolFactory thrift.TProtocolFactory, addr string, secure bool) error {
	var transport thrift.TServerTransport
	var err error
	if secure {
		cfg := new(tls.Config)
		if cert, err := tls.LoadX509KeyPair("server.crt", "server.key"); err == nil {
			cfg.Certificates = append(cfg.Certificates, cert)
		} else {
			return err
		}
		transport, err = thrift.NewTSSLServerSocket(addr, cfg)
	} else {
		transport, err = thrift.NewTServerSocket(addr)
	}

	if err != nil {
		return err
	}
	fmt.Printf("%T\n", transport)
	handler := NewCalculatorHandler()
	processor := tutorial.NewCalculatorProcessor(handler)
	server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)

	fmt.Println("Starting the simple server... on ", addr)
	return server.Serve()
}
コード例 #7
0
ファイル: sslserver.go プロジェクト: gr0gmint/gocon
func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
コード例 #8
0
ファイル: listener.go プロジェクト: kubernetes/heapster
// ClientConfig generates a tls.Config object for use by an HTTP client.
func (info TLSInfo) ClientConfig() (*tls.Config, error) {
	var cfg *tls.Config
	var err error

	if !info.Empty() {
		cfg, err = info.baseConfig()
		if err != nil {
			return nil, err
		}
	} else {
		cfg = &tls.Config{ServerName: info.ServerName}
	}

	CAFiles := info.cafiles()
	if len(CAFiles) > 0 {
		cfg.RootCAs, err = tlsutil.NewCertPool(CAFiles)
		if err != nil {
			return nil, err
		}
		// if given a CA, trust any host with a cert signed by the CA
		cfg.ServerName = ""
	}

	if info.selfCert {
		cfg.InsecureSkipVerify = true
	}
	return cfg, nil
}
コード例 #9
0
ファイル: listener.go プロジェクト: mhurne/vault
// ClientConfig generates a tls.Config object for use by an HTTP client.
func (info TLSInfo) ClientConfig() (*tls.Config, error) {
	var cfg *tls.Config
	var err error

	if !info.Empty() {
		cfg, err = info.baseConfig()
		if err != nil {
			return nil, err
		}
	} else {
		cfg = &tls.Config{}
	}

	CAFiles := info.cafiles()
	if len(CAFiles) > 0 {
		cfg.RootCAs, err = tlsutil.NewCertPool(CAFiles)
		if err != nil {
			return nil, err
		}
	}

	if info.selfCert {
		cfg.InsecureSkipVerify = true
	}
	return cfg, nil
}
コード例 #10
0
ファイル: client.go プロジェクト: empirefox/wsh2c
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,
	}
}
コード例 #11
0
ファイル: tls_info.go プロジェクト: kakkartushar1/ArangoDB
// 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
}
コード例 #12
0
ファイル: protocol.go プロジェクト: borgstrom/reeve
// HandleStartTLS is the companion to StartTLS, and will do the connection upgrade.  It assumes
// that the TLS command byte has already been read.  Like StartTLS it returns the peer name, or
// an error
func (p *Protocol) HandleStartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
	var (
		err     error
		tlsConn *tls.Conn
	)

	// Build the config
	config := new(tls.Config)
	config.ClientAuth = tls.RequireAndVerifyClientCert

	// Setup the tls connection
	if err := p.tlsSetup(config, identity, caCertificate); err != nil {
		return "", err
	}

	// Upgrade the connection to TLS
	// TODO: Add a deadline here?
	tlsConn = tls.Server(p.conn, config)
	if err = tlsConn.Handshake(); err != nil {
		return "", err
	}

	// Capture the connection state
	cs := tlsConn.ConnectionState()

	// And replace the original connection
	p.conn = net.Conn(tlsConn)
	p.setupBuffers()

	// Send an Ack
	p.Ack()

	return cs.PeerCertificates[0].Subject.CommonName, nil
}
コード例 #13
0
ファイル: protocol.go プロジェクト: borgstrom/reeve
// StartTLS takes an identity and an authority certificate and upgrades the net.Conn on the protocol to TLS
// It returns the CommonName from the peer certitifcate, or an error
func (p *Protocol) StartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
	var (
		err     error
		tlsConn *tls.Conn
	)

	if err = p.WriteBytesWithDeadline([]byte{TLS}); err != nil {
		return "", err
	}

	// Build the config
	config := new(tls.Config)
	config.ServerName = p.serverName

	// Setup the tls connection
	if err = p.tlsSetup(config, identity, caCertificate); err != nil {
		return "", err
	}

	// Upgrade the connection to TLS
	// TODO: Add a deadline here?
	tlsConn = tls.Client(p.conn, config)
	if err = tlsConn.Handshake(); err != nil {
		return "", err
	}

	// Capture the connection state
	cs := tlsConn.ConnectionState()

	// And replace the original connection
	p.conn = net.Conn(tlsConn)
	p.setupBuffers()

	return cs.PeerCertificates[0].Subject.CommonName, nil
}
コード例 #14
0
ファイル: metrics.go プロジェクト: cfibmers/bbs
func NewETCDMetrics(logger lager.Logger, etcdOptions *ETCDOptions) (*ETCDMetrics, error) {
	var tlsConfig *tls.Config
	if etcdOptions.CertFile != "" && etcdOptions.KeyFile != "" {
		var err error
		tlsConfig, err = cfhttp.NewTLSConfig(etcdOptions.CertFile, etcdOptions.KeyFile, etcdOptions.CAFile)
		if err != nil {
			return nil, err
		}
		tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(etcdOptions.ClientSessionCacheSize)
	}

	client := cfhttp.NewClient()
	client.CheckRedirect = func(*http.Request, []*http.Request) error {
		return errRedirected
	}

	if tr, ok := client.Transport.(*http.Transport); ok {
		tr.TLSClientConfig = tlsConfig
	} else {
		return nil, errors.New("Invalid transport")
	}

	return &ETCDMetrics{
		logger: logger,

		etcdCluster: etcdOptions.ClusterUrls,

		client: client,
	}, nil
}
コード例 #15
0
ファイル: secure.go プロジェクト: rjammala/vitess
// SecureListen obtains a listener that accepts
// secure connections
func SecureServe(addr string, certFile, keyFile, caFile string) {
	config := tls.Config{}

	// load the server cert / key
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalf("%s", err)
	}
	config.Certificates = []tls.Certificate{cert}

	// load the ca if necessary
	// FIXME(alainjobart) this doesn't quite work yet, have
	// to investigate
	if caFile != "" {
		config.ClientCAs = x509.NewCertPool()

		pemCerts, err := ioutil.ReadFile(caFile)
		if err != nil {
			log.Fatalf("%s", err)
		}
		if !config.ClientCAs.AppendCertsFromPEM(pemCerts) {
			log.Fatalf("%s", err)
		}

		config.ClientAuth = tls.RequireAndVerifyClientCert
	}
	l, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("%s", err)
	}
	throttled := NewThrottledListener(l, *secureThrottle, *secureMaxBuffer)
	cl := proc.Published(throttled, "SecureConnections", "SecureAccepts")
	go http.Serve(cl, nil)
}
コード例 #16
0
// This is like a combination of http.ListenAndServe and http.ListenAndServeTLS, which also
// uses ThrottledListen to limit the number of open HTTP connections.
func ListenAndServeHTTP(addr string, connLimit int, certFile *string, keyFile *string, handler http.Handler, readTimeout *int, writeTimeout *int) error {
	var config *tls.Config
	if certFile != nil {
		config = &tls.Config{}
		config.MinVersion = tls.VersionTLS10 // Disable SSLv3 due to POODLE vulnerability
		config.NextProtos = []string{"http/1.1"}
		config.Certificates = make([]tls.Certificate, 1)
		var err error
		config.Certificates[0], err = tls.LoadX509KeyPair(*certFile, *keyFile)
		if err != nil {
			return err
		}
	}
	listener, err := ThrottledListen("tcp", addr, connLimit)
	if err != nil {
		return err
	}
	if config != nil {
		listener = tls.NewListener(listener, config)
	}
	defer listener.Close()
	server := &http.Server{Addr: addr, Handler: handler}
	if readTimeout != nil {
		server.ReadTimeout = time.Duration(*readTimeout) * time.Second
	}
	if writeTimeout != nil {
		server.WriteTimeout = time.Duration(*writeTimeout) * time.Second
	}

	return server.Serve(listener)
}
コード例 #17
0
ファイル: ws.go プロジェクト: henrydh/quick-know
// If http.ListenandServe return an error,
// it will throws a panic.
func wsListener() {
	if err := func() error {
		httpServeMux := http.NewServeMux()
		httpServeMux.Handle("/pub", websocket.Handler(WsHandle))
		var (
			l   net.Listener
			err error
		)
		if Conf.Tls {
			tlsConf := new(tls.Config)
			tlsConf.Certificates = make([]tls.Certificate, 1)
			tlsConf.Certificates[0], err = tls.X509KeyPair(Conf.Cert, Conf.Key)
			if err != nil {
				return err
			}
			l, err = tls.Listen("tcp", Conf.WebSocket_addr, tlsConf)
			if err != nil {
				return err
			}
			return http.Serve(l, httpServeMux)
		} else {
			return http.ListenAndServe(Conf.WebSocket_addr, httpServeMux)
		}
	}(); err != nil {
		panic(err)
	}
}
コード例 #18
0
ファイル: amqp.go プロジェクト: justone/pmb
func connectToAMQP(uri string) (*amqp.Connection, error) {

	var conn *amqp.Connection
	var err error

	if strings.Contains(uri, "amqps") {
		cfg := new(tls.Config)

		if len(os.Getenv("PMB_SSL_INSECURE_SKIP_VERIFY")) > 0 {
			cfg.InsecureSkipVerify = true
		}

		logrus.Debugf("calling DialTLS")
		conn, err = amqp.DialTLS(uri, cfg)
		logrus.Debugf("Connection obtained")
	} else {
		conn, err = amqp.Dial(uri)
	}

	if err != nil {
		return nil, err
	}

	//logrus.Debugf("Conn: ", conn)
	return conn, nil
}
コード例 #19
0
ファイル: server.go プロジェクト: ricardoshimoda/caddy
// setupClientAuth sets up TLS client authentication only if
// any of the TLS configs specified at least one cert file.
func setupClientAuth(tlsConfigs []TLSConfig, config *tls.Config) error {
	var clientAuth bool
	for _, cfg := range tlsConfigs {
		if len(cfg.ClientCerts) > 0 {
			clientAuth = true
			break
		}
	}

	if clientAuth {
		pool := x509.NewCertPool()
		for _, cfg := range tlsConfigs {
			for _, caFile := range cfg.ClientCerts {
				caCrt, err := ioutil.ReadFile(caFile) // Anyone that gets a cert from Matt Holt can connect
				if err != nil {
					return err
				}
				if !pool.AppendCertsFromPEM(caCrt) {
					return fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
				}
			}
		}
		config.ClientCAs = pool
		config.ClientAuth = tls.RequireAndVerifyClientCert
	}

	return nil
}
コード例 #20
0
ファイル: dial.go プロジェクト: jbeshir/unanimity
// 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
}
コード例 #21
0
ファイル: httpsserver.go プロジェクト: wmydz1/https
func main() {
	cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalf("server : loadkeys :%s", err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	config.Time = time.Now
	config.Rand = rand.Reader

	service := "127.0.0.1:10000"
	listener, err := tls.Listen("tcp", service, &config)
	if err != nil {
		log.Fatalf("server : listen: %s", err)
	}
	log.Print("server: listening")
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Panicf("server:accept :%s", err)
			break
		}
		log.Printf("server : accepted from %s", conn.RemoteAddr())
		go handleClient(conn)
	}
}
コード例 #22
0
func (s *ConnectionXmppSuite) Test_Dial_worksIfTheHandshakeSucceedsButSucceedsOnValidCertHash(c *C) {
	rw := &mockMultiConnIOReaderWriter{read: validTLSExchange}
	conn := &fullMockedConn{rw: rw}
	var tlsC tls.Config
	tlsC.Rand = fixedRand([]string{
		"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F",
		"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F",
		"000102030405060708090A0B0C0D0E0F",
		"000102030405060708090A0B0C0D0E0F",
	})

	d := &dialer{
		JID:           "*****@*****.**",
		password:      "******",
		serverAddress: "www.olabini.se:443",
		verifier:      &basicTLSVerifier{bytesFromHex("82454418cb04854aa721bb0596528ff802b1e18a4e3a7767412ac9f108c9d3a7")},

		config: data.Config{
			TLSConfig: &tlsC,
		},
	}
	_, err := d.setupStream(conn)

	c.Assert(err, Equals, io.EOF)
}
コード例 #23
0
ファイル: conn.go プロジェクト: samuelyao314/mygo
func (c *Conn) upgradeTLS(tlsConf *tls.Config) error {
	// create a local copy of the config to set ServerName for this connection
	var conf tls.Config
	if tlsConf != nil {
		conf = *tlsConf
	}
	host, _, err := net.SplitHostPort(c.addr)
	if err != nil {
		return err
	}
	conf.ServerName = host

	c.tlsConn = tls.Client(c.conn, &conf)
	err = c.tlsConn.Handshake()
	if err != nil {
		return err
	}
	c.r = c.tlsConn
	c.w = c.tlsConn
	frameType, data, err := ReadUnpackedResponse(c)
	if err != nil {
		return err
	}
	if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) {
		return errors.New("invalid response from TLS upgrade")
	}
	return nil
}
コード例 #24
0
func listenWithCert(hostname string, address string) {

	listening.Add(1)
	go func() {
		log.Println("DEBUG - start mock server ..")
		// Establish a dummy TLS server
		var serverConfig tls.Config
		kp := makeCert(hostname)

		serverConfig.Certificates = []tls.Certificate{kp}

		listener, err := tls.Listen("tcp", address, &serverConfig)
		if err != nil {
			panic(err)
		}
		// Listen and handshake for a single connection
		defer listener.Close()
		listening.Done()

		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		defer conn.Close()
		tlsconn, ok := conn.(*tls.Conn)
		if !ok {
			panic("conn should of *tls.Conn")
		}
		if err := tlsconn.Handshake(); err != nil {
			return
		}
	}()
	listening.Wait()
}
コード例 #25
0
ファイル: dockercli.go プロジェクト: gpxl/deis
// NewClient returns a new docker test client.
func NewClient() (
	cli *client.DockerCli, stdout *io.PipeReader, stdoutPipe *io.PipeWriter) {
	proto, addr, _ := DockerHost()
	stdout, stdoutPipe = io.Pipe()

	dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
	// Boot2docker use TLS per default, Jenkins not
	if dockerCertPath != "" {
		var (
			tlsConfig tls.Config
		)
		tlsConfig.InsecureSkipVerify = true

		flCert := filepath.Join(dockerCertPath, defaultCertFile)
		flKey := filepath.Join(dockerCertPath, defaultKeyFile)

		_, errCert := os.Stat(flCert)
		_, errKey := os.Stat(flKey)
		if errCert == nil && errKey == nil {
			cert, err := tls.LoadX509KeyPair(flCert, flKey)
			if err != nil {
				log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err)
			}
			tlsConfig.Certificates = []tls.Certificate{cert}
		}
		// Avoid fallback to SSL protocols < TLS1.0
		tlsConfig.MinVersion = tls.VersionTLS10
		cli = client.NewDockerCli(nil, stdoutPipe, nil, nil, proto, addr, &tlsConfig)
	} else {
		cli = client.NewDockerCli(nil, stdoutPipe, nil, nil, proto, addr, nil)
	}
	return
}
コード例 #26
0
func runClient(transportFactory thrift.TTransportFactory, protocolFactory thrift.TProtocolFactory, addr string, secure bool) error {
	var transport thrift.TTransport
	var err error
	if secure {
		cfg := new(tls.Config)
		cfg.InsecureSkipVerify = true
		transport, err = thrift.NewTSSLSocket(addr, cfg)
	} else {
		transport, err = thrift.NewTSocket(addr)
	}
	if err != nil {
		fmt.Println("Error opening socket:", err)
		return err
	}
	transport = transportFactory.GetTransport(transport)
	defer transport.Close()
	if err := transport.Open(); err != nil {
		return err
	}

	client := example.NewMtExampleServiceClientFactory(transport, protocolFactory)

	oProfile, err := client.GetUserProfile(0)

	if err != nil {
		fmt.Println("GetUserProfile(0) ok " + oProfile.UseName)
	}
	return err
}
コード例 #27
0
ファイル: orchard.go プロジェクト: BillTheBest/libswarm
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
}
コード例 #28
0
func runClient(transportFactory thrift.TTransportFactory, protocolFactory thrift.TProtocolFactory, addr string, secure bool) error {
	var transport thrift.TTransport
	var err error
	if secure {
		cfg := new(tls.Config)
		cfg.InsecureSkipVerify = true
		transport, err = thrift.NewTSSLSocket(addr, cfg)
	} else {
		transport, err = thrift.NewTSocket(addr)
	}
	if err != nil {
		fmt.Println("Error opening socket:", err)
		return err
	}
	if transport == nil {
		return fmt.Errorf("Error opening socket, got nil transport. Is server available?")
	}
	transport = transportFactory.GetTransport(transport)
	if transport == nil {
		return fmt.Errorf("Error from transportFactory.GetTransport(), got nil transport. Is server available?")
	}

	err = transport.Open()
	if err != nil {
		return err
	}
	defer transport.Close()

	return handleClient(tutorial.NewCalculatorClientFactory(transport, protocolFactory))
}
コード例 #29
0
ファイル: transport.go プロジェクト: rhoml/packetbeat
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
}
コード例 #30
0
ファイル: etcd_tls_test.go プロジェクト: joshuaconner/etcd
// 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)
	}
}