本文整理匯總了Golang中crypto/tls.Conn.ConnectionState方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.ConnectionState方法的具體用法?Golang Conn.ConnectionState怎麽用?Golang Conn.ConnectionState使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類crypto/tls.Conn
的用法示例。
在下文中一共展示了Conn.ConnectionState方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: performHandshakeAndValidation
func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
if err := conn.Handshake(); err != nil {
return err
}
cs := conn.ConnectionState()
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
return fmt.Errorf("protocol negotiation error")
}
q := uri.Query()
relayIDs := q.Get("id")
if relayIDs != "" {
relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
if err != nil {
return fmt.Errorf("relay address contains invalid verification id: %s", err)
}
certs := cs.PeerCertificates
if cl := len(certs); cl != 1 {
return fmt.Errorf("unexpected certificate count: %d", cl)
}
remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
if remoteID != relayID {
return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
}
}
return nil
}
示例2: StartTLS
// 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
}
示例3: HandleStartTLS
// 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
}
示例4: getChain
// 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
}
示例5: postVerifyTLSConnection
func postVerifyTLSConnection(conn *tls.Conn, config *TLSConfig) error {
st := conn.ConnectionState()
if !st.HandshakeComplete {
return errors.New("incomplete handshake")
}
// no more checks if no extra configs available
if config == nil {
return nil
}
versions := config.Versions
if versions == nil {
versions = tlsDefaultVersions
}
versionOK := false
for _, version := range versions {
versionOK = versionOK || st.Version == uint16(version)
}
if !versionOK {
return fmt.Errorf("tls version %v not configured", TLSVersion(st.Version))
}
return nil
}
示例6: sessionResumeScan
// 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
})
}
示例7: enrichWithOwnChecks
func enrichWithOwnChecks(conn *tls.Conn, tlsConfig *tls.Config) error {
var err error
if err = conn.Handshake(); err != nil {
conn.Close()
return err
}
opts := x509.VerifyOptions{
Roots: tlsConfig.RootCAs,
CurrentTime: time.Now(),
DNSName: "",
Intermediates: x509.NewCertPool(),
}
certs := conn.ConnectionState().PeerCertificates
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
_, err = certs[0].Verify(opts)
if err != nil {
conn.Close()
return err
}
return nil
}
示例8: connect
func connect(app string, keyFile string, certFile string, sandbox bool) {
defer CapturePanic(fmt.Sprintf("connection to apns server error %s", app))
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Printf("server : loadKeys: %s", err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
endPoint := APNS_ENDPOINT
if sandbox {
endPoint = APNS_SANDBOX_ENDPOINT
}
var conn *tls.Conn
for {
conn, err = tls.Dial("tcp", endPoint, &config)
if err != nil {
log.Println("連接服務器有誤, 2秒後將重連", err)
time.Sleep(time.Second * 2)
} else {
break
}
}
log.Println("client is connect to ", conn.RemoteAddr())
state := conn.ConnectionState()
log.Println("client: hand shake ", state.HandshakeComplete)
log.Println("client: mutual", state.NegotiatedProtocolIsMutual)
if sandbox {
app = app + DEVELOP_SUBFIX
}
info := &ConnectInfo{Connection: conn, App: app, Sandbox: sandbox, lastActivity: time.Now().Unix()}
socketCN <- info
}
示例9: test_conn
func test_conn(conn *tls.Conn, options *ScanOptions, record *ScanRecord) bool {
//check SSL certificate
success := false
for _, cert := range conn.ConnectionState().PeerCertificates {
for _, verifyHost := range options.Config.ScanGoogleIP.SSLCertVerifyHosts {
if cert.VerifyHostname(verifyHost) != nil {
return false
} else {
success = true
}
}
if success {
break
}
}
for _, verifyHost := range options.Config.ScanGoogleIP.HTTPVerifyHosts {
conn.SetReadDeadline(time.Now().Add(record.httpVerifyTimeout))
req, _ := http.NewRequest("HEAD", "https://"+verifyHost, nil)
res, err := httputil.NewClientConn(conn, nil).Do(req)
if nil != err || res.StatusCode >= 400 {
return false
}
}
return true
}
示例10: main
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()
}
}()
}
}
}
示例11: getPublicKey
func getPublicKey(tlsConn *tls.Conn) ([]byte, error) {
state := tlsConn.ConnectionState()
for _, v := range state.PeerCertificates {
return x509.MarshalPKIXPublicKey(v.PublicKey)
}
return []byte{}, nil
}
示例12: handle_tlsconn
func handle_tlsconn(conn *tls.Conn, context *Context) bool {
conn.SetDeadline(time.Now().Add(config.TimeoutTLS))
err := conn.Handshake()
if err != nil {
util.Log(0, "ERROR! [SECURITY] TLS Handshake: %v", err)
return false
}
var no_deadline time.Time
conn.SetDeadline(no_deadline)
state := conn.ConnectionState()
if len(state.PeerCertificates) == 0 {
util.Log(0, "ERROR! [SECURITY] TLS peer has no certificate")
return false
}
cert := state.PeerCertificates[0] // docs are unclear about this but I think leaf certificate is the first entry because that's as it is in tls.Certificate
if util.LogLevel >= 2 { // because creating the dump is expensive
util.Log(2, "DEBUG! [SECURITY] Peer certificate presented by %v:\n%v", conn.RemoteAddr(), CertificateInfo(cert))
}
for _, cacert := range config.CACert {
err = cert.CheckSignatureFrom(cacert)
if err == nil {
if string(cacert.RawSubject) != string(cert.RawIssuer) {
err = fmt.Errorf("Certificate was issued by wrong CA: \"%v\" instead of \"%v\"", cacert.Subject, cert.Issuer)
} else {
break // stop checking if we found a match for a CA. err == nil here!
}
}
}
if err != nil {
util.Log(0, "ERROR! [SECURITY] TLS peer presented certificate not signed by trusted CA: %v", err)
return false
}
for _, e := range cert.Extensions {
if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 && e.Id[3] == 17 {
parseSANExtension(e.Value, context)
} else if len(e.Id) == 9 && e.Id[0] == 1 && e.Id[1] == 3 && e.Id[2] == 6 && e.Id[3] == 1 && e.Id[4] == 4 && e.Id[5] == 1 && e.Id[6] == 45753 && e.Id[7] == 1 {
switch e.Id[8] {
case 5:
err = parseConnectionLimits(e.Value, context)
if err != nil {
util.Log(0, "ERROR! [SECURITY] GosaConnectionLimits: %v", err)
}
case 6: //err = parseAccessControl(e.Value, context)
//if err != nil { util.Log(0, "ERROR! [SECURITY] GosaAccessControl: %v", err) }
}
}
}
context.TLS = true
return true
}
示例13: defaultTlsPeerName
// Default TLS peer name function - returns the CN of the certificate
func defaultTlsPeerName(tlsConn *tls.Conn) (tlsPeer string, ok bool) {
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) <= 0 {
return "", false
}
cn := state.PeerCertificates[0].Subject.CommonName
return cn, true
}
示例14: DialTLSFunc
// DialTLSFunc returns the adequate dial function, when using SSL, depending on
// whether we're using insecure TLS (certificate verification is disabled), or we
// have some trusted certs, or we're on android.1
// If the client's config has some trusted certs, the server's certificate will
// be checked against those in the config after the TLS handshake.
func (c *Client) DialTLSFunc() func(network, addr string) (net.Conn, error) {
if !c.useTLS() {
return nil
}
trustedCerts := c.getTrustedCerts()
var stdTLS bool
if !c.insecureAnyTLSCert && len(trustedCerts) == 0 {
// TLS with normal/full verification.
stdTLS = true
if !android.IsChild() {
// Not android, so let the stdlib deal with it
return nil
}
}
return func(network, addr string) (net.Conn, error) {
var conn *tls.Conn
var err error
if android.IsChild() {
ac, err := android.Dial(network, addr)
if err != nil {
return nil, err
}
var tlsConfig *tls.Config
if stdTLS {
tlsConfig, err = android.TLSConfig()
if err != nil {
return nil, err
}
} else {
tlsConfig = &tls.Config{InsecureSkipVerify: true}
}
conn = tls.Client(ac, tlsConfig)
if err := conn.Handshake(); err != nil {
return nil, err
}
} else {
conn, err = tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return nil, err
}
}
if c.insecureAnyTLSCert {
return conn, nil
}
certs := conn.ConnectionState().PeerCertificates
if len(certs) < 1 {
return nil, fmt.Errorf("no TLS peer certificates from %s", addr)
}
sig := hashutil.SHA256Prefix(certs[0].Raw)
for _, v := range trustedCerts {
if v == sig {
return conn, nil
}
}
return nil, fmt.Errorf("TLS server at %v presented untrusted certificate (signature %q)", addr, sig)
}
}
示例15: DialTLSFunc
// DialTLSFunc returns the adequate dial function, when using SSL, depending on
// whether we're using insecure TLS (certificate verification is disabled), or we
// have some trusted certs, or we're on android.
// If the client's config has some trusted certs, the server's certificate will
// be checked against those in the config after the TLS handshake.
func (c *Client) DialTLSFunc() func(network, addr string) (net.Conn, error) {
if !c.useTLS() {
return nil
}
trustedCerts := c.getTrustedCerts()
var stdTLS bool
if !c.InsecureTLS && len(trustedCerts) == 0 {
// TLS with normal/full verification
stdTLS = true
if !android.IsChild() {
// Not android, so let the stdlib deal with it
return nil
}
}
return func(network, addr string) (net.Conn, error) {
var conn *tls.Conn
var err error
if android.IsChild() {
con, err := android.Dial(network, addr)
if err != nil {
return nil, err
}
var tlsConfig *tls.Config
if stdTLS {
tlsConfig, err = android.TLSConfig()
if err != nil {
return nil, err
}
} else {
tlsConfig = &tls.Config{InsecureSkipVerify: true}
}
conn = tls.Client(con, tlsConfig)
if err = conn.Handshake(); err != nil {
return nil, err
}
} else {
conn, err = tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return nil, err
}
}
if c.InsecureTLS {
return conn, nil
}
certs := conn.ConnectionState().PeerCertificates
if certs == nil || len(certs) < 1 {
return nil, errors.New("Could not get server's certificate from the TLS connection.")
}
sig := hashutil.SHA256Prefix(certs[0].Raw)
for _, v := range trustedCerts {
if v == sig {
return conn, nil
}
}
return nil, fmt.Errorf("Server's certificate %v is not in the trusted list", sig)
}
}