forked from icodeface/grdp
/
socket.go
72 lines (62 loc) · 1.38 KB
/
socket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package core
import (
"crypto/rsa"
"errors"
"math/big"
"net"
"github.com/huin/asn1ber"
"github.com/icodeface/tls"
)
type SocketLayer struct {
conn net.Conn
tlsConn *tls.Conn
}
func NewSocketLayer(conn net.Conn) *SocketLayer {
l := &SocketLayer{
conn: conn,
tlsConn: nil,
}
return l
}
func (s *SocketLayer) Read(b []byte) (n int, err error) {
if s.tlsConn != nil {
return s.tlsConn.Read(b)
}
return s.conn.Read(b)
}
func (s *SocketLayer) Write(b []byte) (n int, err error) {
if s.tlsConn != nil {
return s.tlsConn.Write(b)
}
return s.conn.Write(b)
}
func (s *SocketLayer) Close() error {
if s.tlsConn != nil {
err := s.tlsConn.Close()
if err != nil {
return err
}
}
return s.conn.Close()
}
func (s *SocketLayer) StartTLS() error {
config := &tls.Config{
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS10,
MaxVersion: tls.VersionTLS13,
PreferServerCipherSuites: true,
}
s.tlsConn = tls.Client(s.conn, config)
return s.tlsConn.Handshake()
}
type PublicKey struct {
N *big.Int `asn1:"explicit,tag:0"` // modulus
E int `asn1:"explicit,tag:1"` // public exponent
}
func (s *SocketLayer) TlsPubKey() ([]byte, error) {
if s.tlsConn == nil {
return nil, errors.New("TLS conn does not exist")
}
pub := s.tlsConn.ConnectionState().PeerCertificates[0].PublicKey.(*rsa.PublicKey)
return asn1ber.Marshal(*pub)
}