作者:herna
项目:syncthin
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
}
作者:jacobx
项目:Gopherbo
// checkErr logs if an error occurs and closes the tlsConn.
func checkErr(err error, tlsConn *tls.Conn) {
if err != nil {
tlsConn.Close()
log.Fatalf("GBNetworkTools: %s\n", err.Error())
}
}
作者:carriercom
项目:syncthin
func (d *relayDialer) Dial(id protocol.DeviceID, uri *url.URL) (IntermediateConnection, error) {
inv, err := client.GetInvitationFromRelay(uri, id, d.tlsCfg.Certificates, 10*time.Second)
if err != nil {
return IntermediateConnection{}, err
}
conn, err := client.JoinSession(inv)
if err != nil {
return IntermediateConnection{}, err
}
err = dialer.SetTCPOptions(conn)
if err != nil {
conn.Close()
return IntermediateConnection{}, err
}
var tc *tls.Conn
if inv.ServerSocket {
tc = tls.Server(conn, d.tlsCfg)
} else {
tc = tls.Client(conn, d.tlsCfg)
}
err = tc.Handshake()
if err != nil {
tc.Close()
return IntermediateConnection{}, err
}
return IntermediateConnection{tc, "Relay (Client)", relayPriority}, nil
}
作者:
项目:riak-go-clien
func (c *connection) startTls() (err error) {
if c.authOptions == nil {
return nil
}
if c.authOptions.TlsConfig == nil {
return ErrAuthMissingConfig
}
c.state = connTlsStarting
startTlsCmd := &StartTlsCommand{}
if err = c.execute(startTlsCmd); err != nil {
return
}
var tlsConn *tls.Conn
if tlsConn = tls.Client(c.conn, c.authOptions.TlsConfig); tlsConn == nil {
err = ErrAuthTLSUpgradeFailed
return
}
if err = tlsConn.Handshake(); err != nil {
return
}
c.conn = tlsConn
authCmd := &AuthCommand{
User: c.authOptions.User,
Password: c.authOptions.Password,
}
err = c.execute(authCmd)
return
}
作者:tomdionysu
项目:trinit
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
}
作者: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
}
作者: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
})
}
作者:borgstro
项目:reev
// 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
}
作者:quexe
项目:apn
func read(client *Client, conn *tls.Conn) {
buffer := make([]byte, ERR_RESPONSE_LEN)
if _, err := conn.Read(buffer); err != nil {
log.Printf("read err %v, %v, %p\n", err, err == io.EOF, client)
client.chConnectionErr <- conn
return
}
errRsp := &errResponse{
Command: uint8(buffer[0]),
Status: uint8(buffer[1]),
}
if err := binary.Read(bytes.NewBuffer(buffer[2:]), binary.BigEndian, &errRsp.Identifier); err != nil {
log.Println("read identifier err", err)
return
}
if errRsp.Command != ERR_RESPONSE_CMD {
log.Println("unknown err response", buffer)
return
}
errMsg, ok := ApplePushResponses[errRsp.Status]
if !ok {
log.Println("unknown err status", buffer)
return
}
log.Printf("get err response : %##v, %s\n", errRsp, errMsg)
client.chErrResponse <- errRsp
}
作者:jacobx
项目:Gopherbo
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)
}
作者:pguelp
项目:riak-go-clien
func (c *connection) startTls() error {
if c.authOptions == nil {
return nil
}
if c.authOptions.TlsConfig == nil {
return ErrAuthMissingConfig
}
c.setState(connTlsStarting)
startTlsCmd := &startTlsCommand{}
if err := c.execute(startTlsCmd); err != nil {
return err
}
var tlsConn *tls.Conn
if tlsConn = tls.Client(c.conn, c.authOptions.TlsConfig); tlsConn == nil {
return ErrAuthTLSUpgradeFailed
}
if err := tlsConn.Handshake(); err != nil {
return err
}
c.conn = tlsConn
authCmd := &authCommand{
user: c.authOptions.User,
password: c.authOptions.Password,
}
return c.execute(authCmd)
}
作者:jeffki
项目:goapn
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
}
作者:skriptbl
项目:nin
func (t *TCP) startTLS() (el element.Element, err error) {
var tlsConn *tls.Conn
if t.mode == stream.Initiating {
err = t.WriteElement(element.StartTLS)
if err != nil {
return
}
el, err = t.Next()
if err != nil || el.Tag != element.TLSProceed.Tag {
return
}
tlsConn = tls.Client(t.Conn, t.conf)
} else {
err = t.WriteElement(element.TLSProceed)
if err != nil {
return
}
tlsConn = tls.Server(t.Conn, t.conf)
}
err = tlsConn.Handshake()
if err != nil {
return
}
conn := net.Conn(tlsConn)
t.Conn = conn
t.Decoder = xml.NewDecoder(conn)
el = element.Element{}
err = stream.ErrRequireRestart
t.secure = true
log.Println("Done upgrading connection")
return
}
作者:jacobx
项目:Gopherbo
func getPublicKey(tlsConn *tls.Conn) ([]byte, error) {
state := tlsConn.ConnectionState()
for _, v := range state.PeerCertificates {
return x509.MarshalPKIXPublicKey(v.PublicKey)
}
return []byte{}, nil
}
作者:gwitmon
项目:ecca-prox
// Start the simple voice app on the encrypted channel.
func startVoiceApp(tlsconn *tls.Conn, remoteCN string) {
// start the speaker part and connect it to our socket
spr := exec.Command("/usr/bin/aplay")
spr.Stdin = tlsconn
err := spr.Start() // start asynchronously
check(err)
// start the microphone too
// defaults: 1 channel 8000 Hz sample rate, WAVE format
mic := exec.Command("/usr/bin/arecord")
mic.Stdout = tlsconn
err = mic.Start() // start asynchronously
check(err)
// TODO: write a ping to signal connection
// mess := text_to_speech("Connected to %s, chat away!\n", remoteCN)
// spr.Write([]byte(mess))
// wait for it to finish
// TODO: find a way to hang up the connection, short of killall arecord/aplay
err = mic.Wait()
check(err)
err = spr.Wait()
check(err)
tlsconn.Close()
}
作者:YaSuena
项目:hsbea
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
}
作者:borgstro
项目:reev
// 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
}
作者:mijo-sj
项目:lanter
func closeAndCountFDs(t *testing.T, conn *tls.Conn, err error, fdStart int) {
if err == nil {
conn.Close()
}
fdEnd := countTCPFiles()
assert.Equal(t, fdStart, fdEnd, "Number of open TCP files should be the same after test as before")
}
作者:weim
项目:Go-Apn
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
}
作者:gwitmon
项目:ecca-prox
// Start the simple chat app on the encrypted channel.
func startChatApp(tlsconn *tls.Conn, remoteCN string) {
// Create listener socket for the simple chat
socket, err := net.Listen("tcp", "[::1]:0")
check(err)
port := getPort(socket.Addr().String())
// start the chat app and point it to our socket
cmd := exec.Command("uxterm", "-e", "nc", "-6", "::1", port)
err = cmd.Start() // start asynchronously
check(err)
// wait for it to connect
app, err := socket.Accept()
check(err)
// show a welcome message
mess := fmt.Sprintf("Connected to %s, chat away!\n", remoteCN)
app.Write([]byte(mess))
app.Write([]byte(fmt.Sprintf("%s\n", strings.Repeat("-", len(mess)-1))))
// copy the TLS-connection to the chat app and back
go io.Copy(app, tlsconn)
go io.Copy(tlsconn, app)
// wait for it to finish
err = cmd.Wait()
check(err)
// Close all, including the socket and the TLS channel.
// We run this only once.
app.Close()
socket.Close()
tlsconn.Close()
}