-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_tls.go
269 lines (248 loc) · 8.79 KB
/
server_tls.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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package quic
import (
"crypto/tls"
"errors"
"fmt"
"net"
"github.com/bifurcation/mint"
"github.com/lucas-clemente/quic-go/internal/crypto"
"github.com/lucas-clemente/quic-go/internal/handshake"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
"github.com/lucas-clemente/quic-go/internal/wire"
"github.com/lucas-clemente/quic-go/qerr"
"github.com/mami-project/plus-lib"
)
type nullAEAD struct {
aead crypto.AEAD
}
var _ quicAEAD = &nullAEAD{}
func (n *nullAEAD) OpenHandshake(dst, src []byte, packetNumber protocol.PacketNumber, associatedData []byte) ([]byte, error) {
return n.aead.Open(dst, src, packetNumber, associatedData)
}
func (n *nullAEAD) Open1RTT(dst, src []byte, packetNumber protocol.PacketNumber, associatedData []byte) ([]byte, error) {
return nil, errors.New("no 1-RTT keys")
}
type tlsSession struct {
connID protocol.ConnectionID
sess packetHandler
}
type serverTLS struct {
conn net.PacketConn
plusConn *PLUS.Connection
config *Config
supportedVersions []protocol.VersionNumber
mintConf *mint.Config
params *handshake.TransportParameters
newMintConn func(*handshake.CryptoStreamConn, protocol.VersionNumber) (handshake.MintTLS, <-chan handshake.TransportParameters, error)
newSession func(connection, sessionRunner, protocol.ConnectionID, protocol.ConnectionID, protocol.PacketNumber, *Config, handshake.MintTLS, *handshake.CryptoStreamConn, crypto.AEAD, *handshake.TransportParameters, protocol.VersionNumber, utils.Logger) (quicSession, error)
sessionRunner sessionRunner
sessionChan chan<- tlsSession
logger utils.Logger
}
func newServerTLS(
conn net.PacketConn,
config *Config,
runner sessionRunner,
cookieHandler *handshake.CookieHandler,
tlsConf *tls.Config,
logger utils.Logger,
) (*serverTLS, <-chan tlsSession, error) {
mconf, err := tlsToMintConfig(tlsConf, protocol.PerspectiveServer)
if err != nil {
return nil, nil, err
}
mconf.RequireCookie = true
cs, err := mint.NewDefaultCookieProtector()
if err != nil {
return nil, nil, err
}
mconf.CookieProtector = cs
mconf.CookieHandler = cookieHandler
sessionChan := make(chan tlsSession)
s := &serverTLS{
conn: conn,
config: config,
supportedVersions: config.Versions,
mintConf: mconf,
sessionRunner: runner,
sessionChan: sessionChan,
params: &handshake.TransportParameters{
StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
IdleTimeout: config.IdleTimeout,
MaxBidiStreams: uint16(config.MaxIncomingStreams),
MaxUniStreams: uint16(config.MaxIncomingUniStreams),
DisableMigration: true,
},
newSession: newTLSServerSession,
logger: logger,
}
s.newMintConn = s.newMintConnImpl
return s, sessionChan, nil
}
func (s *serverTLS) write(data []byte, addr net.Addr) (int, error) {
if !UsePLUS {
return s.conn.WriteTo(data, addr)
} else {
return s.plusConn.Write(data)
}
}
func (s *serverTLS) HandleInitial(plusConn *PLUS.Connection, remoteAddr net.Addr, hdr *wire.Header, data []byte) {
// TODO: add a check that DestConnID == SrcConnID
s.logger.Debugf("Received a Packet. Handling it statelessly.")
sess, connID, err := s.handleInitialImpl(plusConn, remoteAddr, hdr, data)
if err != nil {
s.logger.Errorf("Error occurred handling initial packet: %s", err)
return
}
if sess == nil { // a stateless reset was done
return
}
s.sessionChan <- tlsSession{
connID: connID,
sess: sess,
}
}
// will be set to s.newMintConn by the constructor
func (s *serverTLS) newMintConnImpl(bc *handshake.CryptoStreamConn, v protocol.VersionNumber) (handshake.MintTLS, <-chan handshake.TransportParameters, error) {
extHandler := handshake.NewExtensionHandlerServer(s.params, s.config.Versions, v, s.logger)
conf := s.mintConf.Clone()
conf.ExtensionHandler = extHandler
return newMintController(bc, conf, protocol.PerspectiveServer), extHandler.GetPeerParams(), nil
}
func (s *serverTLS) sendConnectionClose(remoteAddr net.Addr, clientHdr *wire.Header, aead crypto.AEAD, closeErr error) error {
ccf := &wire.ConnectionCloseFrame{
ErrorCode: qerr.HandshakeFailed,
ReasonPhrase: closeErr.Error(),
}
replyHdr := &wire.Header{
IsLongHeader: true,
Type: protocol.PacketTypeHandshake,
SrcConnectionID: clientHdr.DestConnectionID,
DestConnectionID: clientHdr.SrcConnectionID,
PacketNumber: 1, // random packet number
PacketNumberLen: protocol.PacketNumberLen1,
Version: clientHdr.Version,
}
data, err := packUnencryptedPacket(aead, replyHdr, ccf, protocol.PerspectiveServer, s.logger)
if err != nil {
return err
}
_, err = s.write(data, remoteAddr)
return err
}
func (s *serverTLS) handleInitialImpl(plusConn *PLUS.Connection, remoteAddr net.Addr, hdr *wire.Header, data []byte) (packetHandler, protocol.ConnectionID, error) {
if hdr.DestConnectionID.Len() < protocol.MinConnectionIDLenInitial {
return nil, nil, errors.New("dropping Initial packet with too short connection ID")
}
if len(hdr.Raw)+len(data) < protocol.MinInitialPacketSize {
return nil, nil, errors.New("dropping too small Initial packet")
}
// check version, if not matching send VNP
if !protocol.IsSupportedVersion(s.supportedVersions, hdr.Version) {
s.logger.Debugf("Client offered version %s, sending VersionNegotiationPacket", hdr.Version)
vnp, err := wire.ComposeVersionNegotiation(hdr.SrcConnectionID, hdr.DestConnectionID, s.supportedVersions)
if err != nil {
return nil, nil, err
}
_, err = s.write(vnp, remoteAddr)
return nil, nil, err
}
// unpack packet and check stream frame contents
aead, err := crypto.NewNullAEAD(protocol.PerspectiveServer, hdr.DestConnectionID, protocol.VersionTLS)
if err != nil {
return nil, nil, err
}
frame, err := unpackInitialPacket(aead, hdr, data, s.logger, hdr.Version)
if err != nil {
s.logger.Debugf("Error unpacking initial packet: %s", err)
return nil, nil, nil
}
sess, connID, err := s.handleUnpackedInitial(plusConn, remoteAddr, hdr, frame, aead)
if err != nil {
if ccerr := s.sendConnectionClose(remoteAddr, hdr, aead, err); ccerr != nil {
s.logger.Debugf("Error sending CONNECTION_CLOSE: %s", ccerr)
}
return nil, nil, err
}
return sess, connID, nil
}
func (s *serverTLS) handleUnpackedInitial(plusConn *PLUS.Connection, remoteAddr net.Addr, hdr *wire.Header, frame *wire.StreamFrame, aead crypto.AEAD) (packetHandler, protocol.ConnectionID, error) {
version := hdr.Version
bc := handshake.NewCryptoStreamConn(remoteAddr)
bc.AddDataForReading(frame.Data)
tls, paramsChan, err := s.newMintConn(bc, version)
if err != nil {
return nil, nil, err
}
alert := tls.Handshake()
if alert == mint.AlertStatelessRetry {
// the HelloRetryRequest was written to the bufferConn
// Take that data and write send a Retry packet
f := &wire.StreamFrame{
StreamID: version.CryptoStreamID(),
Data: bc.GetDataForWriting(),
}
srcConnID, err := protocol.GenerateConnectionID(s.config.ConnectionIDLength)
if err != nil {
return nil, nil, err
}
replyHdr := &wire.Header{
IsLongHeader: true,
Type: protocol.PacketTypeRetry,
DestConnectionID: hdr.SrcConnectionID,
SrcConnectionID: srcConnID,
PayloadLen: f.Length(version) + protocol.ByteCount(aead.Overhead()),
PacketNumber: hdr.PacketNumber, // echo the client's packet number
PacketNumberLen: hdr.PacketNumberLen,
Version: version,
}
data, err := packUnencryptedPacket(aead, replyHdr, f, protocol.PerspectiveServer, s.logger)
if err != nil {
return nil, nil, err
}
_, err = s.write(data, remoteAddr)
return nil, nil, err
}
if alert != mint.AlertNoAlert {
return nil, nil, alert
}
if tls.State() != mint.StateServerNegotiated {
return nil, nil, fmt.Errorf("Expected mint state to be %s, got %s", mint.StateServerNegotiated, tls.State())
}
if alert := tls.Handshake(); alert != mint.AlertNoAlert {
return nil, nil, alert
}
if tls.State() != mint.StateServerWaitFlight2 {
return nil, nil, fmt.Errorf("Expected mint state to be %s, got %s", mint.StateServerWaitFlight2, tls.State())
}
params := <-paramsChan
connID, err := protocol.GenerateConnectionID(s.config.ConnectionIDLength)
if err != nil {
return nil, nil, err
}
s.logger.Debugf("Changing source connection ID to %s.", connID)
sess, err := s.newSession(
&conn{pconn: s.conn, currentAddr: remoteAddr},
s.sessionRunner,
hdr.SrcConnectionID,
connID,
protocol.PacketNumber(1), // TODO: use a random packet number here
s.config,
tls,
bc,
aead,
¶ms,
version,
s.logger,
)
if err != nil {
return nil, nil, err
}
cs := sess.getCryptoStream()
cs.setReadOffset(frame.DataLen())
bc.SetStream(cs)
go sess.run()
return sess, connID, nil
}