Example #1
0
// makeTLSConn will wrap an existing Conn using TLS
func (nc *Conn) makeTLSConn() {
	// Allow the user to configure their own tls.Config structure, otherwise
	// default to InsecureSkipVerify.
	// TODO(dlc) - We should make the more secure version the default.
	if nc.Opts.TLSConfig != nil {
		nc.conn = tls.Client(nc.conn, nc.Opts.TLSConfig)
	} else {
		nc.conn = tls.Client(nc.conn, &tls.Config{InsecureSkipVerify: true})
	}
	nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize)
}
Example #2
0
File: xmpp.go Project: ikq/go-xmpp
// NewClient establishes a new Client connection based on a set of Options.
func (o Options) NewClient() (*Client, error) {
	host := o.Host
	c, err := connect(host, o.User, o.Password)
	if err != nil {
		return nil, err
	}

	if strings.LastIndex(o.Host, ":") > 0 {
		host = host[:strings.LastIndex(o.Host, ":")]
	}

	client := new(Client)
	if o.NoTLS {
		if o.Debug {
			client.conn = DebugConn{c}
		} else {
			client.conn = c
		}
	} else {
		var tlsconn *tls.Conn
		if o.TLSConfig != nil {
			tlsconn = tls.Client(c, o.TLSConfig)
		} else {
			DefaultConfig.ServerName = host
			tlsconn = tls.Client(c, &DefaultConfig)
		}
		if err = tlsconn.Handshake(); err != nil {
			return nil, err
		}
		insecureSkipVerify := DefaultConfig.InsecureSkipVerify
		if o.TLSConfig != nil {
			insecureSkipVerify = o.TLSConfig.InsecureSkipVerify
		}
		if !insecureSkipVerify {
			if err = tlsconn.VerifyHostname(host); err != nil {
				return nil, err
			}
		}

		if o.Debug {
			client.conn = DebugConn{tlsconn}
		} else {
			client.conn = tlsconn
		}
	}

	if err := client.init(&o); err != nil {
		client.Close()
		return nil, err
	}

	return client, nil
}
Example #3
0
func dial(host string) (conn *httputil.ClientConn) {
	var tcp net.Conn
	var err error
	fmt.Fprintf(os.Stderr, "http-gonsole: establishing a TCP connection ...\n")
	proxy := os.Getenv("HTTP_PROXY")
	if strings.Split(host, ":")[0] != "localhost" && len(proxy) > 0 {
		proxy_url, _ := url.Parse(proxy)
		tcp, err = net.Dial("tcp", proxy_url.Host)
	} else {
		tcp, err = net.Dial("tcp", host)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, "http-gonsole:", err)
		os.Exit(1)
	}
	if *useSSL {
		if len(proxy) > 0 {
			connReq := &http.Request{
				Method: "CONNECT",
				URL:    &url.URL{Path: host},
				Host:   host,
				Header: make(http.Header),
			}
			connReq.Write(tcp)
			resp, err := http.ReadResponse(bufio.NewReader(tcp), connReq)
			if resp.StatusCode != 200 {
				fmt.Fprintln(os.Stderr, "http-gonsole:", resp.Status)
				os.Exit(1)
			}
			if err != nil {
				fmt.Fprintln(os.Stderr, "http-gonsole:", err)
				os.Exit(1)
			}
			tcp = tls.Client(tcp, nil)
			conn = httputil.NewClientConn(tcp, nil)
		} else {
			tcp = tls.Client(tcp, nil)
			conn = httputil.NewClientConn(tcp, nil)
		}
		if err = tcp.(*tls.Conn).Handshake(); err != nil {
			fmt.Fprintln(os.Stderr, "http-gonsole:", err)
			os.Exit(1)
		}
		if err = tcp.(*tls.Conn).VerifyHostname(strings.Split(host, ":")[0]); err != nil {
			fmt.Fprintln(os.Stderr, "http-gonsole:", err)
			os.Exit(1)
		}
	} else {
		conn = httputil.NewClientConn(tcp, nil)
	}
	return
}
Example #4
0
// NewClient establishes a new Client connection based on a set of Options.
func (o Options) NewClient() (*Client, error) {
	host := o.Host
	c, err := connect(host, o.User, o.Password)
	if err != nil {
		return nil, err
	}

	client := new(Client)
	if o.NoTLS {
		client.conn = c
	} else {
		var tlsconn *tls.Conn
		if o.TLSConfig != nil {
			tlsconn = tls.Client(c, o.TLSConfig)
		} else {
			//from https://github.com/dullgiulio/go-xmpp
			usrServ := strings.Split(o.User, "@")
			if len(usrServ) != 2 {
				return nil, errors.New("xmpp: invalid username (want user@domain): " + o.User)
			}
			DefaultConfig.ServerName = usrServ[1]
			tlsconn = tls.Client(c, &DefaultConfig)
		}
		if err = tlsconn.Handshake(); err != nil {
			return nil, err
		}
		if strings.LastIndex(o.Host, ":") > 0 {
			host = host[:strings.LastIndex(o.Host, ":")]
		}
		insecureSkipVerify := DefaultConfig.InsecureSkipVerify
		if o.TLSConfig != nil {
			insecureSkipVerify = o.TLSConfig.InsecureSkipVerify
		}
		if !insecureSkipVerify {
			if err = tlsconn.VerifyHostname(host); err != nil {
				return nil, err
			}
		}
		client.conn = tlsconn
	}

	if err := client.init(&o); err != nil {
		client.Close()
		return nil, err
	}

	return client, nil
}
Example #5
0
func doTestTLS(buffered bool, t *testing.T) {
	startServers(t, false)

	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get fdcount: %v", err)
	}

	conn, err := prepareConn(httpsAddr, buffered, false, t, nil)
	if err != nil {
		t.Fatalf("Unable to prepareConn: %s", err)
	}

	tlsConn := tls.Client(conn, &tls.Config{
		ServerName: "localhost",
		RootCAs:    cert.PoolContainingCert(),
	})
	defer func() {
		err := conn.Close()
		assert.Nil(t, err, "Closing conn should succeed")
		if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
			DumpConnTrace()
		}
	}()

	err = tlsConn.Handshake()
	if err != nil {
		t.Fatalf("Unable to handshake: %s", err)
	}

	doRequests(tlsConn, t)

	assert.True(t, destsSent[httpsAddr], "https address wasn't recorded as sent destination")
	assert.True(t, destsReceived[httpsAddr], "https address wasn't recorded as received destination")
}
Example #6
0
// Connect to an IRC Server
// Takes the server address as parameter
func (self *IRConn) Dial(host string, sslConf *SSLConfig) error {

	log.Printf("Connecting to %v...", host)
	con, err := net.Dial("tcp", host)
	if err != nil {
		log.Printf("failed %v", err)
		return err
	}

	if sslConf.UseSSL {
		log.Println("Using SSL")
		conf := &tls.Config{InsecureSkipVerify: sslConf.SkipVerify}
		con = tls.Client(con, conf)
	}

	log.Printf("Connected successfully to %v", host)
	self.con = con
	self.write = make(chan string)
	self.read = make(chan string)

	go func() {
		reader := bufio.NewReader(con)
		defer con.Close()

		self.read <- "connected"
		for {
			if msg, err := reader.ReadString('\n'); err == nil {
				self.read <- msg
			} else {
				log.Printf("%v", err)
				close(self.read)
				break
			}
		}
	}()

	go func() {
		defer con.Close()

		for {
			msg, ok := <-self.write
			if !ok {
				break
			}

			if len(msg) > 510 {
				msg = msg[0:510]
			}

			if _, err := self.con.Write([]byte(msg + "\r\n")); err != nil {
				log.Printf("%v", err)
				break
			}

			log.Printf("--> %v", msg)
		}
	}()

	return nil
}
Example #7
0
func (c *tlsCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ AuthInfo, err error) {
	// borrow some code from tls.DialWithDialer
	var errChannel chan error
	if timeout != 0 {
		errChannel = make(chan error, 2)
		time.AfterFunc(timeout, func() {
			errChannel <- timeoutError{}
		})
	}
	if c.config.ServerName == "" {
		colonPos := strings.LastIndex(addr, ":")
		if colonPos == -1 {
			colonPos = len(addr)
		}
		c.config.ServerName = addr[:colonPos]
	}
	conn := tls.Client(rawConn, &c.config)
	if timeout == 0 {
		err = conn.Handshake()
	} else {
		go func() {
			errChannel <- conn.Handshake()
		}()
		err = <-errChannel
	}
	if err != nil {
		rawConn.Close()
		return nil, nil, err
	}
	// TODO(zhaoq): Omit the auth info for client now. It is more for
	// information than anything else.
	return conn, nil, nil
}
Example #8
0
func (c *staticClient) connect() error {
	if c.uri.Scheme != "relay" {
		return fmt.Errorf("Unsupported relay schema: %v", c.uri.Scheme)
	}

	t0 := time.Now()
	tcpConn, err := dialer.DialTimeout("tcp", c.uri.Host, c.connectTimeout)
	if err != nil {
		return err
	}

	c.mut.Lock()
	c.latency = time.Since(t0)
	c.mut.Unlock()

	conn := tls.Client(tcpConn, c.config)

	if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
		conn.Close()
		return err
	}

	if err := performHandshakeAndValidation(conn, c.uri); err != nil {
		conn.Close()
		return err
	}

	c.conn = conn
	return nil
}
Example #9
0
// NewClient creates a new connection to a host given as "hostname" or "hostname:port".
// If host is not specified, the  DNS SRV should be used to find the host from the domainpart of the JID.
// Default the port to 5222.
func NewClient(host, user, passwd string, debug bool) (*Client, error) {
	c, err := connect(host, user, passwd)
	if err != nil {
		return nil, err
	}

	tlsconn := tls.Client(c, &DefaultConfig)
	if err = tlsconn.Handshake(); err != nil {
		return nil, err
	}

	if strings.LastIndex(host, ":") > 0 {
		host = host[:strings.LastIndex(host, ":")]
	}
	if err = tlsconn.VerifyHostname(host); err != nil {
		return nil, err
	}

	client := new(Client)
	client.conn = tlsconn
	client.debug = debug

	if err := client.init(user, passwd); err != nil {
		client.Close()
		return nil, err
	}
	return client, nil
}
Example #10
0
func dialVictim(hostPort string, isTls bool) io.ReadWriteCloser {
	// TODO hint: add support for dialing the victim via a random proxy
	// from the given pool.
	conn, err := net.Dial("tcp", hostPort)
	if err != nil {
		log.Printf("Couldn't esablish connection to [%s]: [%s]\n", hostPort, err)
		return nil
	}
	tcpConn := conn.(*net.TCPConn)
	if err = tcpConn.SetReadBuffer(128); err != nil {
		log.Fatalf("Cannot shrink TCP read buffer: [%s]\n", err)
	}
	if err = tcpConn.SetWriteBuffer(128); err != nil {
		log.Fatalf("Cannot shrink TCP write buffer: [%s]\n", err)
	}
	if err = tcpConn.SetLinger(0); err != nil {
		log.Fatalf("Cannot disable TCP lingering: [%s]\n", err)
	}
	if !isTls {
		return tcpConn
	}

	tlsConn := tls.Client(conn, tlsConfig)
	if err = tlsConn.Handshake(); err != nil {
		conn.Close()
		log.Printf("Couldn't establish tls connection to [%s]: [%s]\n", hostPort, err)
		return nil
	}
	return tlsConn
}
Example #11
0
func makeTCPDialer(network string) DialerFactory {
	return func(uri *url.URL, tlsCfg *tls.Config) (*tls.Conn, error) {
		// Check that there is a port number in uri.Host, otherwise add one.
		host, port, err := net.SplitHostPort(uri.Host)
		if err != nil && strings.HasPrefix(err.Error(), "missing port") {
			// addr is on the form "1.2.3.4"
			uri.Host = net.JoinHostPort(uri.Host, "22000")
		} else if err == nil && port == "" {
			// addr is on the form "1.2.3.4:"
			uri.Host = net.JoinHostPort(host, "22000")
		}

		// Don't try to resolve the address before dialing. The dialer may be a
		// proxy, and we should let the proxy do the resolving in that case.
		conn, err := dialer.Dial(network, uri.Host)
		if err != nil {
			l.Debugln(err)
			return nil, err
		}

		tc := tls.Client(conn, tlsCfg)
		err = tc.Handshake()
		if err != nil {
			tc.Close()
			return nil, err
		}

		return tc, nil
	}
}
Example #12
0
func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
	// use local cfg to avoid clobbering ServerName if using multiple endpoints
	cfg := cloneTLSConfig(c.config)
	if cfg.ServerName == "" {
		colonPos := strings.LastIndex(addr, ":")
		if colonPos == -1 {
			colonPos = len(addr)
		}
		cfg.ServerName = addr[:colonPos]
	}
	conn := tls.Client(rawConn, cfg)
	errChannel := make(chan error, 1)
	go func() {
		errChannel <- conn.Handshake()
	}()
	select {
	case err := <-errChannel:
		if err != nil {
			return nil, nil, err
		}
	case <-ctx.Done():
		return nil, nil, ctx.Err()
	}
	// TODO(zhaoq): Omit the auth info for client now. It is more for
	// information than anything else.
	return conn, nil, nil
}
Example #13
0
// ListenForFeedback connects to the Apple Feedback Service
// and checks for device tokens.
//
// Feedback consists of device tokens that should
// not be sent to in the future; Apple *does* monitor that
// you respect this so you should be checking it ;)
func (client *Client) ListenForFeedback() (err error) {
	var cert tls.Certificate

	if len(client.CertificateBase64) == 0 && len(client.KeyBase64) == 0 {
		// The user did not specify raw block contents, so check the filesystem.
		cert, err = tls.LoadX509KeyPair(client.CertificateFile, client.KeyFile)
	} else {
		// The user provided the raw block contents, so use that.
		cert, err = tls.X509KeyPair([]byte(client.CertificateBase64), []byte(client.KeyBase64))
	}

	if err != nil {
		return err
	}

	conf := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   strings.Split(client.Gateway, ":")[0],
	}

	conn, err := net.DialTimeout("tcp", client.Gateway, time.Minute)
	if err != nil {
		return err
	}
	defer conn.Close()
	conn.SetDeadline(time.Now().Add(FeedbackTimeoutSeconds * time.Second))

	tlsConn := tls.Client(conn, conf)
	err = tlsConn.Handshake()
	if err != nil {
		return err
	}

	var tokenLength uint16
	buffer := make([]byte, 38, 38)
	deviceToken := make([]byte, 32, 32)

	for {
		_, err := tlsConn.Read(buffer)
		if err != nil {
			ShutdownChannel <- true
			break
		}

		resp := NewFeedbackResponse()

		r := bytes.NewReader(buffer)
		binary.Read(r, binary.BigEndian, &resp.Timestamp)
		binary.Read(r, binary.BigEndian, &tokenLength)
		binary.Read(r, binary.BigEndian, &deviceToken)
		if tokenLength != 32 {
			return errors.New("token length should be equal to 32, but isn't")
		}
		resp.DeviceToken = hex.EncodeToString(deviceToken)

		FeedbackChannel <- resp
	}

	return nil
}
Example #14
0
func (client *ApnsConn) connect() (err error) {
	if client.connected {
		return nil
	}

	if client.tlsconn != nil {
		client.shutdown()
	}

	conn, err := net.Dial("tcp", client.endpoint)

	if err != nil {
		return err
	}

	client.tlsconn = tls.Client(conn, &client.tls_cfg)

	err = client.tlsconn.Handshake()

	if err == nil {
		client.connected = true
	}

	return err
}
Example #15
0
func Connect(cert_filename string, key_filename string, server string) (*Apn, error) {
	rchan := make(chan NotificationError)

	cert, cert_err := tls.LoadX509KeyPair(cert_filename, key_filename)
	if cert_err != nil {
		return nil, cert_err
	}

	conn, err := net.Dial("tcp", server)
	if err != nil {
		return nil, err
	}

	certificate := []tls.Certificate{cert}
	conf := tls.Config{
		Certificates: certificate,
	}

	var client_conn *tls.Conn = tls.Client(conn, &conf)
	err = client_conn.Handshake()
	if err != nil {
		return nil, err
	}

	go readError(client_conn, rchan)

	return &Apn{cert, server, client_conn, rchan}, nil
}
Example #16
0
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
}
Example #17
0
func dialHTTP(network, address, codecName string, cFactory ClientCodecFactory, auth bool, connectTimeout time.Duration, config *tls.Config) (*rpc.Client, error) {
	var err error
	var conn net.Conn
	if connectTimeout != 0 {
		conn, err = net.DialTimeout(network, address, connectTimeout)
	} else {
		conn, err = net.Dial(network, address)
	}
	if err != nil {
		return nil, err
	}

	if config != nil {
		conn = tls.Client(conn, config)
	}

	_, err = io.WriteString(conn, "CONNECT "+GetRpcPath(codecName, auth)+" HTTP/1.0\n\n")
	if err != nil {
		return nil, err
	}

	// Require successful HTTP response
	// before switching to RPC protocol.
	buffered := NewBufferedConnection(conn)
	resp, err := http.ReadResponse(buffered.Reader, &http.Request{Method: "CONNECT"})
	if err == nil && resp.Status == connected {
		return rpc.NewClientWithCodec(cFactory(buffered)), nil
	}
	if err == nil {
		err = errors.New("unexpected HTTP response: " + resp.Status)
	}
	conn.Close()
	return nil, &net.OpError{Op: "dial-http", Net: network + " " + address, Addr: nil, Err: err}
}
Example #18
0
// Dial is used to create a new outgoing connection
func (l *RaftLayer) Dial(address string, timeout time.Duration) (net.Conn, error) {
	conn, err := net.DialTimeout("tcp", address, timeout)
	if err != nil {
		return nil, err
	}

	// Check for tls mode
	if l.tlsConfig != nil {
		// Switch the connection into TLS mode
		if _, err := conn.Write([]byte{byte(rpcTLS)}); err != nil {
			conn.Close()
			return nil, err
		}

		// Wrap the connection in a TLS client
		conn = tls.Client(conn, l.tlsConfig)
	}

	// Write the Raft byte to set the mode
	_, err = conn.Write([]byte{byte(rpcRaft)})
	if err != nil {
		conn.Close()
		return nil, err
	}
	return conn, err
}
Example #19
0
func (r *invitationReceiver) Serve() {
	for {
		select {
		case inv := <-r.invitations:
			l.Debugln("Received relay invitation", inv)
			conn, err := client.JoinSession(inv)
			if err != nil {
				l.Debugf("Failed to join relay session %s: %v", inv, err)
				continue
			}

			var tc *tls.Conn

			if inv.ServerSocket {
				tc = tls.Server(conn, r.tlsCfg)
			} else {
				tc = tls.Client(conn, r.tlsCfg)
			}
			err = tc.Handshake()
			if err != nil {
				l.Infof("TLS handshake (BEP/relay %s): %v", inv, err)
				tc.Close()
				continue
			}
			r.conns <- tc

		case <-r.stop:
			return
		}
	}
}
Example #20
0
func (c *client) Run() {
	go func() {
		var err error
		conn, err := net.Dial(c.addr.Network(), c.addr.String())
		if err != nil {
			c.connected <- err
			return
		}
		if c.tls {
			conn = tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
		}
		c.connected <- nil
		for <-c.sendrequest {
			_, err = conn.Write([]byte("GET / HTTP/1.1\nHost: localhost:8000\n\n"))
			if err != nil {
				c.idle <- err
			}
			// Read response; no content
			scanner := bufio.NewScanner(conn)
			for scanner.Scan() {
				// our null handler doesn't send a body, so we know the request is
				// done when we reach the blank line after the headers
				if scanner.Text() == "" {
					break
				}
			}
			c.idle <- scanner.Err()
			<-c.idlerelease
		}
		conn.Close()
		ioutil.ReadAll(conn)
		c.closed <- true
	}()
}
Example #21
0
func doHTTP(s *shim, conf *tls.Config) error {
	// TODO: support http proxies
	c := tls.Client(s, conf)
	s.Start()
	err := c.Handshake()
	s.Stop()
	if err != nil {
		return fmt.Errorf("http handshake failed: %s", err)
	}
	req, _ := http.NewRequest("GET", "/", nil)
	req.Host = conf.ServerName
	req.Header = httpHeaders
	if err := req.Write(c); err != nil {
		return fmt.Errorf("http request write failed: %s", err)
	}
	b := bufio.NewReader(c)
	resp, err := http.ReadResponse(b, req)
	if err != nil {
		return fmt.Errorf("http response read failed: %s", err)
	}
	resp.Body.Close()
	if err := c.Close(); err != nil {
		return fmt.Errorf("http close failed: %s", err)
	}
	return nil
}
Example #22
0
func createTLSClient(socket net.Conn, config *APNSConfig) (net.Conn, error) {
	x509Cert, err := tls.X509KeyPair(config.CertificateBytes, config.KeyBytes)
	if err != nil {
		//failed to validate key pair
		return nil, err
	}

	tlsConf := &tls.Config{
		Certificates:       []tls.Certificate{x509Cert},
		ServerName:         config.GatewayHost,
		InsecureSkipVerify: config.UseInsecureSkipVerify,
	}

	tlsSocket := tls.Client(socket, tlsConf)
	tlsSocket.SetDeadline(time.Now().Add(time.Duration(config.TlsTimeout) * time.Second))
	err = tlsSocket.Handshake()
	if err != nil {
		//failed to handshake with tls information
		return nil, err
	}

	//hooray! we're connected
	//reset the deadline so it doesn't fail subsequent writes
	tlsSocket.SetDeadline(time.Time{})

	return tlsSocket, nil
}
Example #23
0
func (d *tcpDialer) Dial(id protocol.DeviceID, uri *url.URL) (internalConn, error) {
	uri = fixupPort(uri)

	conn, err := dialer.DialTimeout(uri.Scheme, uri.Host, 10*time.Second)
	if err != nil {
		l.Debugln(err)
		return internalConn{}, err
	}

	err = dialer.SetTCPOptions(conn)
	if err != nil {
		l.Infoln(err)
	}

	err = dialer.SetTrafficClass(conn, d.cfg.Options().TrafficClass)
	if err != nil {
		l.Debugf("failed to set traffic class: %s", err)
	}

	tc := tls.Client(conn, d.tlsCfg)
	err = tlsTimedHandshake(tc)
	if err != nil {
		tc.Close()
		return internalConn{}, err
	}

	return internalConn{tc, connTypeTCPClient, tcpPriority}, nil
}
// Worker function
func getcert(in chan WorkTodo, done chan PTRrecord) {
	config := tls.Config{InsecureSkipVerify: true}
	// Keep waiting for work
	for {
		target := <-in
		//ip := strings.Split(target.Host, ":")
		//go lookup_PTRrecord(done, ip[0])

		tcpconn, err := net.DialTimeout("tcp", target.Host, 2*time.Second)
		if err != nil {
			continue
		}
		conn := tls.Client(tcpconn, &config)
		err = conn.Handshake()
		if err != nil {
			continue
		}
		err = conn.Handshake()
		if err != nil {
			continue
		}
		state := conn.ConnectionState()
		// TODO: store certificate
		for _, cert := range state.PeerCertificates {
			handle_cert(cert, target.Host)
		}
		conn.Close()
	}
}
Example #25
0
func (c *Client) startTls() error {
	fmt.Fprintf(c.conn, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>")
	var proceed tlsProceed
	if err := c.p.DecodeElement(&proceed, nil); err != nil {
		return err
	}

	tlsconn := tls.Client(c.conn, &DefaultConfig)
	if err := tlsconn.Handshake(); err != nil {
		return err
	}
	c.conn = tlsconn
	if Debug {
		fmt.Println("===xmpp===TLS shake hand success.")
	}
	c.p = xml.NewDecoder(c.conn)
	//if strings.LastIndex(host, ":") > 0 {
	//	host = host[:strings.LastIndex(host, ":")]
	//}
	//if err = tlsconn.VerifyHostname(host); err != nil {
	//	return nil, err
	//}

	return nil
}
Example #26
0
func (c *ProtocolClient) connect() error {
	if c.URI.Scheme != "relay" {
		return fmt.Errorf("Unsupported relay schema: %v", c.URI.Scheme)
	}

	t0 := time.Now()
	tcpConn, err := net.Dial("tcp", c.URI.Host)
	if err != nil {
		return err
	}

	c.mut.Lock()
	c.latency = time.Since(t0)
	c.mut.Unlock()

	conn := tls.Client(tcpConn, c.config)
	if err = conn.Handshake(); err != nil {
		return err
	}

	if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
		conn.Close()
		return err
	}

	if err := performHandshakeAndValidation(conn, c.URI); err != nil {
		conn.Close()
		return err
	}

	c.conn = conn
	return nil
}
Example #27
0
File: conn.go Project: 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)
}
Example #28
0
func (c *HostClient) dialHost() (net.Conn, error) {
	dial := c.Dial
	addr := c.Addr
	if dial == nil {
		if c.DialDualStack {
			dial = DialDualStack
		} else {
			dial = Dial
		}
		addr = addMissingPort(addr, c.IsTLS)
	}
	conn, err := dial(addr)
	if err != nil {
		return nil, err
	}
	if conn == nil {
		panic("BUG: DialFunc returned (nil, nil)")
	}
	if c.IsTLS {
		tlsConfig := c.TLSConfig
		if tlsConfig == nil {
			tlsConfig = defaultTLSConfig
		}
		conn = tls.Client(conn, tlsConfig)
	}
	return conn, nil
}
Example #29
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 #30
0
func (c *Conn) proceedTLS(cfg *tls.Config) (state tls.ConnectionState, err error) {
	tlsc := tls.Client(c.Conn, cfg)
	err = tlsc.Handshake()
	state = tlsc.ConnectionState()
	c.Conn = tlsc
	return
}