// Connects the socket, creating a new socket object if necessary.
func (p *TSSLSocket) Open() error {
	var err error
	// If we have a hostname, we need to pass the hostname to tls.Dial for
	// certificate hostname checks.
	if p.hostPort != "" {
		if p.conn, err = tls.Dial("tcp", p.hostPort, p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	} else {
		if p.IsOpen() {
			return NewTTransportException(ALREADY_OPEN, "Socket already connected.")
		}
		if p.addr == nil {
			return NewTTransportException(NOT_OPEN, "Cannot open nil address.")
		}
		if len(p.addr.Network()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad network name.")
		}
		if len(p.addr.String()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad address.")
		}
		if p.conn, err = tls.Dial(p.addr.Network(), p.addr.String(), p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	}
	return nil
}
Ejemplo n.º 2
0
func (t *TLSRedialTransport) dial(network, addr string) (conn net.Conn, err error) {
	t.once.Do(func() {
		conn = t.ServerConn
	})
	if conn != nil {
		return conn, nil
	}

	newConn, err := tls.Dial("tcp", t.serverAddr, &tls.Config{
		ServerName:         t.ServerName,
		InsecureSkipVerify: true,
	})
	if err != nil {
		return nil, err
	}

	if !bytes.Equal(t.publicKey, newConn.ConnectionState().PeerCertificates[0].RawSubjectPublicKeyInfo) {
		newConn.Close()
		log.Printf("TLS private key at %s changed", t.ServerName)

		// Our little certificate-pinning trick failed because the server changed
		// certificates (or we've been MITM'd). See if the server has a valid
		// certificate, even if it's not the same one.
		return tls.Dial("tcp", t.serverAddr, &tls.Config{ServerName: t.ServerName})
	}

	return newConn, nil
}
Ejemplo n.º 3
0
// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState.  If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
	addr := u.Host
	if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
		addr += ":443"
	}

	conn, err := tls.Dial("tcp", addr, config)
	if err != nil {
		switch err.(type) {
		case x509.UnknownAuthorityError:
		case x509.HostnameError:
		default:
			return err
		}

		info.Err = err

		conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
		if err != nil {
			return err
		}
	} else {
		info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
	}

	state := conn.ConnectionState()
	_ = conn.Close()
	info.FromCertificate(state.PeerCertificates[0])

	return nil
}
Ejemplo n.º 4
0
// connect to the server. Here we keep trying every 10 seconds until we manage
// to Dial to the server.
func (bot *ircBot) connect() (conn io.ReadWriteCloser) {

	var (
		err     error
		counter int
	)

	connectTimeout := time.After(0)

	bot.Lock()
	bot.isConnecting = true
	bot.isAuthenticating = false
	bot.Unlock()

	for {
		select {
		case <-connectTimeout:
			counter++
			connectTimeout = nil
			glog.Infoln("[Info] Connecting to IRC server: ", bot.address)
			conn, err = tls.Dial("tcp", bot.address, nil) // Always try TLS first
			if err == nil {
				glog.Infoln("Connected: TLS secure")
				return conn
			} else if _, ok := err.(x509.HostnameError); ok {
				glog.Errorln("Could not connect using TLS because: ", err)
				// Certificate might not match. This happens on irc.cloudfront.net
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)

				if err == nil && isCertValid(conn.(*tls.Conn)) {
					glog.Errorln("Connected: TLS with awkward certificate")
					return conn
				}
			} else if _, ok := err.(x509.UnknownAuthorityError); ok {
				glog.Errorln("x509.UnknownAuthorityError : ", err)
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)
				if err == nil {
					glog.Infoln("Connected: TLS with an x509.UnknownAuthorityError", err)
					return conn
				}
			} else {
				glog.Errorln("Could not establish a tls connection", err)

			}

			conn, err = net.Dial("tcp", bot.address)
			if err == nil {
				glog.Infoln("Connected: Plain text insecure")
				return conn
			}
			// TODO (yml) At some point we might want to panic
			delay := 5 * counter
			glog.Infoln("IRC Connect error. Will attempt to re-connect. ", err, "in", delay, "seconds")
			connectTimeout = time.After(time.Duration(delay) * time.Second)
		}
	}
}
Ejemplo n.º 5
0
// BundleFromRemote fetches the certificate chain served by the server at
// serverName (or ip, if the ip argument is not the empty string). It
// is expected that the method will be able to make a connection at
// port 443. The chain used by the server in this connection is
// used to rebuild the bundle.
func (b *Bundler) BundleFromRemote(serverName, ip string) (*Bundle, error) {
	config := &tls.Config{
		RootCAs:    b.RootPool,
		ServerName: serverName,
	}

	// Dial by IP if present
	var dialName string
	if ip != "" {
		dialName = ip + ":443"
	} else {
		dialName = serverName + ":443"
	}

	log.Debugf("bundling from remote %s", dialName)
	conn, err := tls.Dial("tcp", dialName, config)
	var dialError string
	// If there's an error in tls.Dial, try again with
	// InsecureSkipVerify to fetch the remote bundle to (re-)bundle with.
	// If the bundle is indeed not usable (expired, mismatched hostnames, etc.),
	// report the error.
	// Otherwise, create a working bundle and insert the tls error in the bundle.Status.
	if err != nil {
		log.Debugf("dial failed: %v", err)
		// record the error msg
		dialError = fmt.Sprintf("Failed rigid TLS handshake with %s: %v", dialName, err)
		// dial again with InsecureSkipVerify
		log.Debugf("try again with InsecureSkipVerify.")
		config.InsecureSkipVerify = true
		conn, err = tls.Dial("tcp", dialName, config)
		if err != nil {
			log.Debugf("dial with InsecureSkipVerify failed: %v", err)
			return nil, errors.New(errors.DialError, errors.Unknown, err)
		}
	}

	connState := conn.ConnectionState()

	certs := connState.PeerCertificates

	err = conn.VerifyHostname(serverName)
	if err != nil {
		log.Debugf("failed to verify hostname: %v", err)
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed, err)
	}
	// verify peer intermediates and store them if there is any missing from the bundle.
	// Don't care if there is error, will throw it any way in Bundle() call.
	b.fetchIntermediates(certs)

	// Bundle with remote certs. Inject the initial dial error, if any, to the status reporting.
	bundle, err := b.Bundle(certs, nil, Ubiquitous)
	if err != nil {
		return nil, err
	} else if dialError != "" {
		bundle.Status.Messages = append(bundle.Status.Messages, dialError)
	}
	return bundle, err
}
Ejemplo n.º 6
0
// TestWithClientCertificateAuthentication
// Use two CA:s in two different files and test that clients with client signed by either of them can connect
func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles(c *check.C) {
	cmd := exec.Command(traefikBinary, "--configFile=fixtures/https/clientca/https_2ca2config.toml")
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	time.Sleep(500 * time.Millisecond)

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	// Connection without client certificate should fail
	conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))

	// Connect with client signed by ca1
	cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))

	conn.Close()

	// Connect with client signed by ca2
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
	conn.Close()

	// Connect with client signed by ca3 should fail
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
Ejemplo n.º 7
0
func (s *ServerSuite) TestServerUpdateHTTPS(c *C) {
	var req *http.Request
	e := testutils.NewHandler(func(w http.ResponseWriter, r *http.Request) {
		req = r
		w.Write([]byte("hi https"))
	})
	defer e.Close()

	b := MakeBatch(Batch{
		Addr:     "localhost:41000",
		Route:    `Path("/")`,
		URL:      e.URL,
		Protocol: engine.HTTPS,
		KeyPair:  &engine.KeyPair{Key: localhostKey, Cert: localhostCert},
	})

	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS11"}}
	c.Assert(s.mux.UpsertHost(b.H), IsNil)
	c.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)
	c.Assert(s.mux.UpsertFrontend(b.F), IsNil)
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	c.Assert(s.mux.Start(), IsNil)

	config := &tls.Config{
		InsecureSkipVerify: true,
		// We only support tls 10
		MinVersion: tls.VersionTLS10,
		MaxVersion: tls.VersionTLS10,
	}

	conn, err := tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, NotNil) // we got TLS error

	// Relax the version
	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS10"}}
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	time.Sleep(20 * time.Millisecond)

	conn, err = tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, IsNil)

	fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
	status, err := bufio.NewReader(conn).ReadString('\n')

	c.Assert(status, Equals, "HTTP/1.0 200 OK\r\n")
	state := conn.ConnectionState()
	c.Assert(state.Version, DeepEquals, uint16(tls.VersionTLS10))
	conn.Close()
}
Ejemplo n.º 8
0
func main() {
	config := &tls.Config{nil, nil, []tls.Certificate{}, nil, nil, "google.com", false}

	// config.Rand = nil
	// config.Time = nil
	// config.Certificates = nil
	// config.RootCAs = nil
	// config.NextProtos = nil
	// config.ServerName = "google.com"
	// config.AuthenticateClient = false
	// config.CipherSuites = nil  // Docs wrong?

	conn, err := tls.Dial("tcp", "google.com:443", config)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		buf := make([]uint8, 100)
		fmt.Printf("Reading...\n")
		fmt.Printf("Hangs :-\\\n")
		size, err := conn.Read(buf) // Hangs
		fmt.Printf("Done reading\n")
		if err != nil {
			fmt.Printf("Error: %v\n", err)
		} else {
			fmt.Printf("Data: %v\n", buf[:size])
		}
	}
}
Ejemplo n.º 9
0
/*
Dial opens a new client connection to a Web Socket.

A trivial example client:

	package main

	import (
		"websocket"
		"strings"
	)

	func main() {
	 	ws, err := websocket.Dial("ws://localhost/ws", "", "http://localhost/");
	 	if err != nil {
			panic("Dial: " + err.String())
		}
		if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
			panic("Write: " + err.String())
		}
		var msg = make([]byte, 512);
		if n, err := ws.Read(msg); err != nil {
			panic("Read: " + err.String())
		}
		// use msg[0:n]
	}
*/
func Dial(url, protocol, origin string) (ws *Conn, err os.Error) {
	var client net.Conn

	parsedUrl, err := http.ParseURL(url)
	if err != nil {
		goto Error
	}

	switch parsedUrl.Scheme {
	case "ws":
		client, err = net.Dial("tcp", "", parsedUrl.Host)

	case "wss":
		client, err = tls.Dial("tcp", "", parsedUrl.Host)

	default:
		err = ErrBadScheme
	}
	if err != nil {
		goto Error
	}

	ws, err = newClient(parsedUrl.RawPath, parsedUrl.Host, origin, url, protocol, client, handshake)
	if err != nil {
		goto Error
	}
	return

Error:
	return nil, &DialError{url, protocol, origin, err}
}
Ejemplo n.º 10
0
// golang.org/issue/13924
// This used to fail after many iterations, especially with -race:
// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race
func TestTransportDoubleCloseOnWriteError(t *testing.T) {
	var (
		mu   sync.Mutex
		conn net.Conn // to close if set
	)

	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			mu.Lock()
			defer mu.Unlock()
			if conn != nil {
				conn.Close()
			}
		},
		optOnlyServer,
	)
	defer st.Close()

	tr := &Transport{
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			mu.Lock()
			defer mu.Unlock()
			conn = tc
			return tc, nil
		},
	}
	defer tr.CloseIdleConnections()
	c := &http.Client{Transport: tr}
	c.Get(st.ts.URL)
}
Ejemplo n.º 11
0
// Test concurrent requests with Transport.DisableKeepAlives. We can share connections,
// but when things are totally idle, it still needs to close.
func TestTransportDisableKeepAlives_Concurrency(t *testing.T) {
	const D = 25 * time.Millisecond
	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			time.Sleep(D)
			io.WriteString(w, "hi")
		},
		optOnlyServer,
	)
	defer st.Close()

	var dials int32
	var conns sync.WaitGroup
	tr := &Transport{
		t1: &http.Transport{
			DisableKeepAlives: true,
		},
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			atomic.AddInt32(&dials, 1)
			conns.Add(1)
			return &noteCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil
		},
	}
	c := &http.Client{Transport: tr}
	var reqs sync.WaitGroup
	const N = 20
	for i := 0; i < N; i++ {
		reqs.Add(1)
		if i == N-1 {
			// For the final request, try to make all the
			// others close. This isn't verified in the
			// count, other than the Log statement, since
			// it's so timing dependent. This test is
			// really to make sure we don't interrupt a
			// valid request.
			time.Sleep(D * 2)
		}
		go func() {
			defer reqs.Done()
			res, err := c.Get(st.ts.URL)
			if err != nil {
				t.Error(err)
				return
			}
			if _, err := ioutil.ReadAll(res.Body); err != nil {
				t.Error(err)
				return
			}
			res.Body.Close()
		}()
	}
	reqs.Wait()
	conns.Wait()
	t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N)
}
Ejemplo n.º 12
0
func dialHTTP(hoststring string, scheme string) (cc *http.ClientConn, err os.Error) {
	host, port, err := net.SplitHostPort(hoststring)
	if err != nil {
		return
	}
	if port == "" {
		switch scheme {
		case "http":
			port = "80"
		case "https":
			port = "80"
		case "riak":
			port = "8098"
		default:
			err = os.NewError("Unknown scheme")
		}
	}
	if err != nil {
		return
	}
	var c net.Conn
	switch scheme {
	case "https":
		c, err = tls.Dial("tcp", host+":"+port, nil)
	default:
		c, err = net.Dial("tcp", host+":"+port)
	}
	if err == nil {
		cc = http.NewClientConn(c, nil)
	}
	return
}
Ejemplo n.º 13
0
func newConn(url *url.URL) (*httputil.ClientConn, error) {
	addr := url.Host
	if !hasPort(addr) {
		addr += ":" + url.Scheme
	}
	var conn net.Conn
	var err error
	if url.Scheme == "http" {
		conn, err = net.Dial("tcp", addr)
		if err != nil {
			return nil, err
		}
	} else { // https
		conn, err = tls.Dial("tcp", addr, nil)
		if err != nil {
			return nil, err
		}
		h := url.Host
		if hasPort(h) {
			h = h[0:strings.LastIndex(h, ":")]
		}
		if err := conn.(*tls.Conn).VerifyHostname(h); err != nil {
			return nil, err
		}
	}

	return httputil.NewClientConn(conn, nil), nil
}
Ejemplo n.º 14
0
// Dial initiates a TLS connection to an outbound server. It returns a
// TLS connection to the server.
func Dial(address string, tr *Transport) (*tls.Conn, error) {
	host, _, err := net.SplitHostPort(address)
	if err != nil {
		// Assume address is a hostname, and that it should
		// use the HTTPS port number.
		host = address
		address = net.JoinHostPort(address, "443")
	}

	cfg, err := tr.TLSClientAuthClientConfig(host)
	if err != nil {
		return nil, err
	}

	conn, err := tls.Dial("tcp", address, cfg)
	if err != nil {
		return nil, err
	}

	state := conn.ConnectionState()
	if len(state.VerifiedChains) == 0 {
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
	}

	for _, chain := range state.VerifiedChains {
		for _, cert := range chain {
			revoked, ok := revoke.VerifyCertificate(cert)
			if (!tr.RevokeSoftFail && !ok) || revoked {
				return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
			}
		}
	}

	return conn, nil
}
Ejemplo n.º 15
0
func (f *forwarder) connect() {
	if f.c != nil {
		return
	}

	rate := time.Tick(200 * time.Millisecond)
	for {
		var c net.Conn
		var err error

		if f.Config.TlsConfig != nil {
			c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig)
		} else {
			c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout)
		}

		if err != nil {
			f.cErrors.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error")
			f.disconnect()
		} else {
			f.cSuccesses.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success")
			f.c = c
			return
		}
		<-rate
	}
}
Ejemplo n.º 16
0
// dial connects to the smtp server with the request encryption type
func dial(host string, port string, encryption encryption, config *tls.Config) (*smtp.Client, error) {
	var conn net.Conn
	var err error

	address := host + ":" + port

	// do the actual dial
	switch encryption {
	case EncryptionSSL:
		conn, err = tls.Dial("tcp", address, config)
	default:
		conn, err = net.Dial("tcp", address)
	}

	if err != nil {
		return nil, errors.New("Mail Error on dailing with encryption type " + encryption.String() + ": " + err.Error())
	}

	c, err := smtp.NewClient(conn, host)

	if err != nil {
		return nil, errors.New("Mail Error on smtp dial: " + err.Error())
	}

	return c, err
}
Ejemplo n.º 17
0
// DialConfig opens a new client connection to a WebSocket with a config.
func DialConfig(config *Config) (ws *Conn, err error) {
	var client net.Conn
	if config.Location == nil {
		return nil, &DialError{config, ErrBadWebSocketLocation}
	}
	if config.Origin == nil {
		return nil, &DialError{config, ErrBadWebSocketOrigin}
	}
	switch config.Location.Scheme {
	case "ws":
		client, err = net.Dial("tcp", parseAuthority(config.Location))

	case "wss":
		client, err = tls.Dial("tcp", parseAuthority(config.Location), config.TlsConfig)

	default:
		err = ErrBadScheme
	}
	if err != nil {
		goto Error
	}

	ws, err = NewClient(config, client)
	if err != nil {
		client.Close()
		goto Error
	}
	return

Error:
	return nil, &DialError{config, err}
}
Ejemplo n.º 18
0
func connectToSMTPServer() (net.Conn, *model.AppError) {
	host, _, _ := net.SplitHostPort(Cfg.EmailSettings.SMTPServer)

	var conn net.Conn
	var err error

	if Cfg.EmailSettings.UseTLS {
		tlsconfig := &tls.Config{
			InsecureSkipVerify: true,
			ServerName:         host,
		}

		conn, err = tls.Dial("tcp", Cfg.EmailSettings.SMTPServer, tlsconfig)
		if err != nil {
			return nil, model.NewAppError("SendMail", "Failed to open TLS connection", err.Error())
		}
	} else {
		conn, err = net.Dial("tcp", Cfg.EmailSettings.SMTPServer)
		if err != nil {
			return nil, model.NewAppError("SendMail", "Failed to open connection", err.Error())
		}
	}

	return conn, nil
}
Ejemplo n.º 19
0
func main() {
	addr := flag.String("addr", "", "Address in form of host:port")
	flag.Parse()
	conn, err := tls.Dial("tcp", *addr, &tls.Config{
		InsecureSkipVerify: true,
	})
	if err != nil {
		panic("failed to connect: " + err.Error())
	}
	var nativeChain []certMeta
	chain := conn.ConnectionState().PeerCertificates
	err, root := findRoot(chain)
	if err != nil {
		fmt.Println(err)
	}
	buildNativeChain(chain, root, &nativeChain, len(chain))

	verifyPositions(nativeChain)
	fmt.Printf("%+v\n", nativeChain)
	// for _, cert := range chain {
	// 	fmt.Printf("Certificate: %s, Issued by: %s, Expires at:  %s, Days left: %d\n",
	// 		cert.Subject.CommonName, cert.Issuer.CommonName, cert.NotAfter, cert.NotAfter.Sub(time.Now())/time.Hour/24)
	// }

	conn.Close()
}
Ejemplo n.º 20
0
Archivo: mgo.go Proyecto: jkary/core
// MgoDialInfoTls returns a DialInfo suitable
// for dialling an MgoInstance at any of the
// given addresses, optionally using TLS.
func MgoDialInfoTls(useTls bool, addrs ...string) *mgo.DialInfo {
	var dial func(addr net.Addr) (net.Conn, error)
	if useTls {
		pool := x509.NewCertPool()
		xcert, err := cert.ParseCert(CACert)
		if err != nil {
			panic(err)
		}
		pool.AddCert(xcert)
		tlsConfig := &tls.Config{
			RootCAs:    pool,
			ServerName: "anything",
		}
		dial = func(addr net.Addr) (net.Conn, error) {
			conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
			if err != nil {
				logger.Debugf("tls.Dial(%s) failed with %v", addr, err)
				return nil, err
			}
			return conn, nil
		}
	} else {
		dial = func(addr net.Addr) (net.Conn, error) {
			conn, err := net.Dial("tcp", addr.String())
			if err != nil {
				logger.Debugf("net.Dial(%s) failed with %v", addr, err)
				return nil, err
			}
			return conn, nil
		}
	}
	return &mgo.DialInfo{Addrs: addrs, Dial: dial, Timeout: mgoDialTimeout}
}
Ejemplo n.º 21
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Please specify a host.\n")
		os.Exit(1)
	}
	if len(os.Args) > 3 {
		fmt.Printf("Too many arguments.\n")
		os.Exit(1)
	}
	host := os.Args[1]
	port := "443"
	if len(os.Args) == 3 {
		port = os.Args[2]
	}
	config := &tls.Config{
		InsecureSkipVerify: true,
	}
	conn, err := tls.Dial("tcp", host+":"+port, config)
	if err != nil {
		fmt.Printf("Error dialing host: %v\n", err)
		os.Exit(1)
	}
	go io.Copy(conn, os.Stdin)
	io.Copy(os.Stdout, conn)
}
Ejemplo n.º 22
0
func runClient() {
	cert, err := tls.LoadX509KeyPair(clientTLSCert, clientTLSKey)
	if err != nil {
		log.Fatalf("client: error loading keys: %s", err)
	}
	tlsconf := &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}

	conn, err := tls.Dial("tcp", addr, tlsconf)
	if err != nil {
		log.Fatalf("client: dial: %s", err)
	}
	defer conn.Close()
	log.Println("client: connected to: ", conn.RemoteAddr())

	state := conn.ConnectionState()
	for _, v := range state.PeerCertificates {
		fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey))
		fmt.Println(v.Subject)
	}
	log.Println("client: handshake: ", state.HandshakeComplete)
	log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)

	message := "Hello\n"
	n, err := io.WriteString(conn, message)
	if err != nil {
		log.Fatalf("client: write: %s", err)
	}
	log.Printf("client: wrote %q (%d bytes)", message, n)

	reply := make([]byte, 256)
	n, err = conn.Read(reply)
	log.Printf("client: read %q (%d bytes)", string(reply[:n]), n)
	log.Print("client: exiting")
}
Ejemplo n.º 23
0
func (ui *UI) connect(useNetmon bool) *imap.IMAP {
	user, pass := loadAuth("auth")

	ui.log("connecting...")
	conn, err := tls.Dial("tcp", "imap.gmail.com:993", nil)
	check(err)

	var r io.Reader = conn
	if *dumpProtocol {
		r = newLoggingReader(r, 300)
	}
	if useNetmon {
		ui.netmon = newNetmonReader(r)
		r = ui.netmon
	}
	im := imap.New(r, conn)
	im.Unsolicited = make(chan interface{}, 100)

	hello, err := im.Start()
	check(err)
	ui.log("server hello: %s", hello)

	ui.log("logging in...")
	resp, caps, err := im.Auth(user, pass)
	check(err)
	ui.log("%s", resp)
	ui.log("server capabilities: %s", caps)

	return im
}
Ejemplo n.º 24
0
// Dial connect to mongo, and return an error if there's a problem
func (t *MongoTarget) Dial() error {
	username := t.dstURI.User.Username()
	password, _ := t.dstURI.User.Password()
	parsedQuery, _ := url.ParseQuery(t.dstURI.RawQuery)
	servers := strings.Split(t.dstURI.Host, ",")

	dialInfo := &mgo.DialInfo{
		Addrs:    servers,
		Database: t.dstDB,
		Username: username,
		Password: password,
		Timeout:  time.Second * time.Duration(*connectionTimeout),
	}
	if replicaSet, hasReplicaSet := parsedQuery["replicaSet"]; hasReplicaSet {
		dialInfo.ReplicaSetName = replicaSet[0]
	}
	if ssl, hasSSL := parsedQuery["ssl"]; hasSSL && ssl[0] == "true" {
		dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
			conn, err := tls.Dial("tcp", addr.String(), &tls.Config{InsecureSkipVerify: *ignoreSslError})
			if err != nil {
				logger.Error("tls err, %v", err)
			}
			return conn, err
		}
	}
	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		return fmt.Errorf("Cannot dial with dialInfo %v\n, %v", dialInfo, err)
	}
	t.dst = session
	return nil
}
Ejemplo n.º 25
0
func openTLSClient(ipPort string) (*tls.Conn, error) {

	// Note this loads standard x509 certificates, test keys can be
	// generated with makecert.sh

	log.Printf("Loading certificates from directory: %s\n", *certDir)
	cert, err := tls.LoadX509KeyPair(*certDir+"/server.pem", *certDir+"/server.key")
	if err != nil {
		log.Fatalf("server: loadkeys: %s", err)
	}
	// InsecureSkipVerify required for unsigned certs with Go1 and later.
	config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
	conn, err := tls.Dial("tcp", ipPort, &config)
	if err != nil {
		log.Fatalf("client: dial: %s", err)
	}
	log.Println("client: connected to: ", conn.RemoteAddr())
	// This shows the public key of the server, we will accept any key, but
	// we could terminate the connection based on the public key if desired.
	state := conn.ConnectionState()
	for _, v := range state.PeerCertificates {
		log.Printf("Client: Server public key is:\n%x\n", v.PublicKey.(*rsa.PublicKey).N)

	}
	// Lets verify behind the doubt that both ends of the connection
	// have completed the handshake and negotiated a SSL connection
	log.Println("client: handshake: ", state.HandshakeComplete)
	log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)
	// All TLS handling has completed, now to pass the connection off to
	// go-rpcgen/protobuf/AddService
	return conn, err
}
Ejemplo n.º 26
0
func (p *UpgradeAwareSingleHostReverseProxy) dialBackend(req *http.Request) (net.Conn, error) {
	dialAddr := netutil.CanonicalAddr(req.URL)

	switch p.backendAddr.Scheme {
	case "http":
		return net.Dial("tcp", dialAddr)
	case "https":
		tlsConfig, err := restclient.TLSConfigFor(p.clientConfig)
		if err != nil {
			return nil, err
		}
		tlsConn, err := tls.Dial("tcp", dialAddr, tlsConfig)
		if err != nil {
			return nil, err
		}
		hostToVerify, _, err := net.SplitHostPort(dialAddr)
		if err != nil {
			return nil, err
		}
		err = tlsConn.VerifyHostname(hostToVerify)
		return tlsConn, err
	default:
		return nil, fmt.Errorf("unknown scheme: %s", p.backendAddr.Scheme)
	}
}
Ejemplo n.º 27
0
// dial dials the host specified by req, using TLS if appropriate.
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) {
	dialAddr := netutil.CanonicalAddr(req.URL)

	if req.URL.Scheme == "http" {
		if s.Dialer == nil {
			return net.Dial("tcp", dialAddr)
		} else {
			return s.Dialer.Dial("tcp", dialAddr)
		}
	}

	// TODO validate the TLSClientConfig is set up?
	var conn *tls.Conn
	var err error
	if s.Dialer == nil {
		conn, err = tls.Dial("tcp", dialAddr, s.tlsConfig)
	} else {
		conn, err = tls.DialWithDialer(s.Dialer, "tcp", dialAddr, s.tlsConfig)
	}
	if err != nil {
		return nil, err
	}

	host, _, err := net.SplitHostPort(dialAddr)
	if err != nil {
		return nil, err
	}
	err = conn.VerifyHostname(host)
	if err != nil {
		return nil, err
	}

	return conn, nil
}
Ejemplo n.º 28
0
func (connWriter *connWriter) connect() error {
	if connWriter.innerWriter != nil {
		connWriter.innerWriter.Close()
		connWriter.innerWriter = nil
	}

	if connWriter.useTLS {
		conn, err := tls.Dial(connWriter.net, connWriter.addr, connWriter.configTLS)
		if err != nil {
			return err
		}
		connWriter.innerWriter = conn

		return nil
	}

	conn, err := net.Dial(connWriter.net, connWriter.addr)
	if err != nil {
		return err
	}

	tcpConn, ok := conn.(*net.TCPConn)
	if ok {
		tcpConn.SetKeepAlive(true)
	}

	connWriter.innerWriter = conn

	return nil
}
Ejemplo n.º 29
0
// DialTLS opens a new TLS encrytped connection with the givent configuration
// to the network/address and then beings a muxado client session on it.
func DialTLS(network, addr string, tlsConfig *tls.Config) (sess Session, err error) {
	conn, err := tls.Dial(network, addr, tlsConfig)
	if err != nil {
		return
	}
	return Client(conn), nil
}
Ejemplo n.º 30
0
func (p *apnsPushService) reconnect(psp *PushServiceProvider) (net.Conn, error) {
	name := psp.Name()
	p.connLock.Lock()
	defer p.connLock.Unlock()

	if conn, ok := p.conns[name]; ok {
		conn.Close()
	}
	cert, err := tls.LoadX509KeyPair(psp.FixedData["cert"], psp.FixedData["key"])
	if err != nil {
		return nil, NewBadPushServiceProviderWithDetails(psp, err.Error())
	}
	conf := &tls.Config{
		Certificates:       []tls.Certificate{cert},
		InsecureSkipVerify: true,
	}
	tlsconn, err := tls.Dial("tcp", psp.VolatileData["addr"], conf)
	if err != nil {
		return nil, NewConnectionError(err)
	}
	err = tlsconn.Handshake()
	if err != nil {
		return nil, NewConnectionError(err)
	}
	p.conns[name] = tlsconn
	return tlsconn, nil
}