Пример #1
0
func NewConnectingPeer(logger *util.Logger, server *TLSServer, connection *tls.Conn) *Peer {
	inst := NewPeer(logger, server, connection.RemoteAddr().String())
	inst.Connection = connection
	inst.State = PeerStateHandshake
	inst.Incoming = true
	return inst
}
Пример #2
0
func HandleUserTimeout(UserCollection *mgo.Collection, username, RSA_Public_Key string, conn *tls.Conn, timeout_sec int) {
	log.Printf("Timeout:\tUser '%s' at %s\n", username, conn.RemoteAddr())
	err := GBServerDatabase.UpdateLastAccessedTime(UserCollection, username, string(RSA_Public_Key), 5)
	checkErr(err)
	err = GBServerDatabase.UpdateCurrentlyBeingUsed(UserCollection, username, string(RSA_Public_Key), false)
	checkErr(err)
}
Пример #3
0
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
}
Пример #4
0
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()
				}
			}()
		}
	}
}
Пример #5
0
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
}
Пример #6
0
func verifyClientAddrMatch(c *tls.Conn) error {
	err := c.Handshake()
	if err != nil {
		return err
	}
	addr, _, err := net.SplitHostPort(c.RemoteAddr().String())
	if err != nil {
		return err
	}
	return c.ConnectionState().VerifiedChains[0][0].VerifyHostname(addr)
}
Пример #7
0
func clientSessionCacheKey(conn *tls.Conn, config *tls.Config) string {
	if len(config.ServerName) > 0 {
		return config.ServerName
	}
	addr := conn.RemoteAddr().String()
	colonPos := strings.LastIndex(addr, ":")
	if colonPos == -1 {
		colonPos = len(addr)
	}
	hostname := addr[:colonPos]
	return hostname
}
Пример #8
0
// tlsConnectionStateString выводит в лог информацию о TLS-соединении.
func tlsConnectionStateString(conn *tls.Conn) string {
	var state = conn.ConnectionState()
	return fmt.Sprint("Connection state:",
		"\n------------------------------------------------------------",
		"\n  Local Address:       ", conn.LocalAddr(),
		"\n  Remote Address:      ", conn.RemoteAddr(),
		"\n  TLS version:         ", state.Version,
		"\n  Handshake Complete:  ", state.HandshakeComplete,
		"\n  Did Resume:          ", state.DidResume,
		"\n  Cipher Suite:        ", state.CipherSuite,
		"\n------------------------------------------------------------")
}
Пример #9
0
func NewTLSRedialTransport(conn *tls.Conn, serverName string) *TLSRedialTransport {
	t := &TLSRedialTransport{
		ServerConn: conn,
		ServerName: serverName,
		serverAddr: conn.RemoteAddr().String(),
		publicKey:  conn.ConnectionState().PeerCertificates[0].RawSubjectPublicKeyInfo,
	}

	t.Dial = t.dial
	t.timeout = time.AfterFunc(10*time.Second, t.CloseIdleConnections)

	return t
}
func tryConnect(addr string, strict bool) (errchan chan error) {
	errchan = make(chan error)
	go func() {

		caCertFile, err := ioutil.TempFile("", "logstash-forwarder-cacert")
		if err != nil {
			panic(err)
		}
		defer func() { os.Remove(caCertFile.Name()) }()
		ioutil.WriteFile(caCertFile.Name(), []byte(caCert), os.ModeTemporary)

		// this can be messy because of localhost resolving to ipv6 addresses
		// but there's no easy way to disable v6 resolution here
		const wait = 5
		const retryLimit = 3
		tryAttempt := 0
		exinfo := ""
		config := &NetworkConfig{
			SSLCA:   caCertFile.Name(),
			Servers: []string{addr},
			Timeout: wait,
			timeout: time.Second * wait,
		}

		var socket *tls.Conn
		for socket == nil && tryAttempt < retryLimit {
			select {
			case socket = <-doConnect(config):
			case <-time.After(time.Second * wait):
				log.Printf("INFO: Connect timeout: attempt: %d\n", tryAttempt)
				tryAttempt++
			}
		}
		if socket == nil {
			errchan <- errors.New("Client connect failed. " + exinfo)
			return
		}
		defer socket.Close()
		log.Printf("INFO: Connected to %s\n", socket.RemoteAddr())

		if !socket.ConnectionState().HandshakeComplete {
			errchan <- errors.New("handshake should be complete")
			return
		}
		errchan <- nil
	}()
	return errchan
}
Пример #11
0
/* Check that the TLS connection's certficate can be applied to this connection.
Because irc.coldfront.net presents a certificate not as irc.coldfront.net, but as it's actual host (e.g. snow.coldfront.net),

We do this by comparing the IP address of the certs name to the IP address of our connection.
If they match we're OK.
*/
func isCertValid(conn *tls.Conn) bool {
	connAddr := strings.Split(conn.RemoteAddr().String(), ":")[0]
	cert := conn.ConnectionState().PeerCertificates[0]

	if len(cert.DNSNames) == 0 {
		// Cert has single name, the usual case
		return isIPMatch(cert.Subject.CommonName, connAddr)

	}
	// Cert has several valid names
	for _, certname := range cert.DNSNames {
		if isIPMatch(certname, connAddr) {
			return true
		}
	}

	return false
}
Пример #12
0
func tlsConnLog(conn *tls.Conn) *log.Entry {
	return log.WithFields(log.Fields{
		"addr": conn.RemoteAddr(),
	})
}