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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
package steam
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"fmt"
"io"
"net"
"sync"
"github.com/Philipp15b/go-steam/cryptoutil"
. "github.com/Philipp15b/go-steam/protocol"
)
type connection interface {
Read() (*Packet, error)
Write([]byte) error
Close() error
SetEncryptionKey([]byte)
IsEncrypted() bool
}
const tcpConnectionMagic uint32 = 0x31305456 // "VT01"
type tcpConnection struct {
conn *net.TCPConn
ciph cipher.Block
cipherMutex sync.RWMutex
}
func dialTCP(laddr, raddr *net.TCPAddr) (*tcpConnection, error) {
conn, err := net.DialTCP("tcp", laddr, raddr)
if err != nil {
return nil, err
}
return &tcpConnection{
conn: conn,
}, nil
}
func (c *tcpConnection) Read() (*Packet, error) {
// All packets begin with a packet length
var packetLen uint32
err := binary.Read(c.conn, binary.LittleEndian, &packetLen)
if err != nil {
return nil, err
}
// A magic value follows for validation
var packetMagic uint32
err = binary.Read(c.conn, binary.LittleEndian, &packetMagic)
if err != nil {
return nil, err
}
if packetMagic != tcpConnectionMagic {
return nil, fmt.Errorf("Invalid connection magic! Expected %d, got %d!", tcpConnectionMagic, packetMagic)
}
buf := make([]byte, packetLen, packetLen)
_, err = io.ReadFull(c.conn, buf)
if err == io.ErrUnexpectedEOF {
return nil, io.EOF
}
if err != nil {
return nil, err
}
// Packets after ChannelEncryptResult are encrypted
c.cipherMutex.RLock()
if c.ciph != nil {
buf = cryptoutil.SymmetricDecrypt(c.ciph, buf)
}
c.cipherMutex.RUnlock()
return NewPacket(buf)
}
// Writes a message. This may only be used by one goroutine at a time.
func (c *tcpConnection) Write(message []byte) error {
c.cipherMutex.RLock()
if c.ciph != nil {
message = cryptoutil.SymmetricEncrypt(c.ciph, message)
}
c.cipherMutex.RUnlock()
err := binary.Write(c.conn, binary.LittleEndian, uint32(len(message)))
if err != nil {
return err
}
err = binary.Write(c.conn, binary.LittleEndian, tcpConnectionMagic)
if err != nil {
return err
}
_, err = c.conn.Write(message)
return err
}
func (c *tcpConnection) Close() error {
return c.conn.Close()
}
func (c *tcpConnection) SetEncryptionKey(key []byte) {
c.cipherMutex.Lock()
defer c.cipherMutex.Unlock()
if key == nil {
c.ciph = nil
return
}
if len(key) != 32 {
panic("Connection AES key is not 32 bytes long!")
}
var err error
c.ciph, err = aes.NewCipher(key)
if err != nil {
panic(err)
}
}
func (c *tcpConnection) IsEncrypted() bool {
c.cipherMutex.RLock()
defer c.cipherMutex.RUnlock()
return c.ciph != nil
}
|