File: crypto_stream.go

package info (click to toggle)
golang-github-lucas-clemente-quic-go 0.54.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,312 kB
  • sloc: sh: 54; makefile: 7
file content (249 lines) | stat: -rw-r--r-- 6,656 bytes parent folder | download
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
package quic

import (
	"errors"
	"fmt"
	"io"
	"os"
	"slices"
	"strconv"

	"github.com/quic-go/quic-go/internal/protocol"
	"github.com/quic-go/quic-go/internal/qerr"
	"github.com/quic-go/quic-go/internal/wire"
)

const disableClientHelloScramblingEnv = "QUIC_GO_DISABLE_CLIENTHELLO_SCRAMBLING"

// The baseCryptoStream is used by the cryptoStream and the initialCryptoStream.
// This allows us to implement different logic for PopCryptoFrame for the two streams.
type baseCryptoStream struct {
	queue frameSorter

	highestOffset protocol.ByteCount
	finished      bool

	writeOffset protocol.ByteCount
	writeBuf    []byte
}

func newCryptoStream() *cryptoStream {
	return &cryptoStream{baseCryptoStream{queue: *newFrameSorter()}}
}

func (s *baseCryptoStream) HandleCryptoFrame(f *wire.CryptoFrame) error {
	highestOffset := f.Offset + protocol.ByteCount(len(f.Data))
	if maxOffset := highestOffset; maxOffset > protocol.MaxCryptoStreamOffset {
		return &qerr.TransportError{
			ErrorCode:    qerr.CryptoBufferExceeded,
			ErrorMessage: fmt.Sprintf("received invalid offset %d on crypto stream, maximum allowed %d", maxOffset, protocol.MaxCryptoStreamOffset),
		}
	}
	if s.finished {
		if highestOffset > s.highestOffset {
			// reject crypto data received after this stream was already finished
			return &qerr.TransportError{
				ErrorCode:    qerr.ProtocolViolation,
				ErrorMessage: "received crypto data after change of encryption level",
			}
		}
		// ignore data with a smaller offset than the highest received
		// could e.g. be a retransmission
		return nil
	}
	s.highestOffset = max(s.highestOffset, highestOffset)
	return s.queue.Push(f.Data, f.Offset, nil)
}

// GetCryptoData retrieves data that was received in CRYPTO frames
func (s *baseCryptoStream) GetCryptoData() []byte {
	_, data, _ := s.queue.Pop()
	return data
}

func (s *baseCryptoStream) Finish() error {
	if s.queue.HasMoreData() {
		return &qerr.TransportError{
			ErrorCode:    qerr.ProtocolViolation,
			ErrorMessage: "encryption level changed, but crypto stream has more data to read",
		}
	}
	s.finished = true
	return nil
}

// Writes writes data that should be sent out in CRYPTO frames
func (s *baseCryptoStream) Write(p []byte) (int, error) {
	s.writeBuf = append(s.writeBuf, p...)
	return len(p), nil
}

func (s *baseCryptoStream) HasData() bool {
	return len(s.writeBuf) > 0
}

func (s *baseCryptoStream) PopCryptoFrame(maxLen protocol.ByteCount) *wire.CryptoFrame {
	f := &wire.CryptoFrame{Offset: s.writeOffset}
	n := min(f.MaxDataLen(maxLen), protocol.ByteCount(len(s.writeBuf)))
	if n <= 0 {
		return nil
	}
	f.Data = s.writeBuf[:n]
	s.writeBuf = s.writeBuf[n:]
	s.writeOffset += n
	return f
}

type cryptoStream struct {
	baseCryptoStream
}

type clientHelloCut struct {
	start protocol.ByteCount
	end   protocol.ByteCount
}

type initialCryptoStream struct {
	baseCryptoStream

	scramble bool
	end      protocol.ByteCount
	cuts     [2]clientHelloCut
}

func newInitialCryptoStream(isClient bool) *initialCryptoStream {
	var scramble bool
	if isClient {
		disabled, err := strconv.ParseBool(os.Getenv(disableClientHelloScramblingEnv))
		scramble = err != nil || !disabled
	}
	s := &initialCryptoStream{
		baseCryptoStream: baseCryptoStream{queue: *newFrameSorter()},
		scramble:         scramble,
	}
	for i := range len(s.cuts) {
		s.cuts[i].start = protocol.InvalidByteCount
		s.cuts[i].end = protocol.InvalidByteCount
	}
	return s
}

func (s *initialCryptoStream) HasData() bool {
	// The ClientHello might be written in multiple parts.
	// In order to correctly split the ClientHello, we need the entire ClientHello has been queued.
	if s.scramble && s.writeOffset == 0 && s.cuts[0].start == protocol.InvalidByteCount {
		return false
	}
	return s.baseCryptoStream.HasData()
}

func (s *initialCryptoStream) Write(p []byte) (int, error) {
	s.writeBuf = append(s.writeBuf, p...)
	if !s.scramble {
		return len(p), nil
	}
	if s.cuts[0].start == protocol.InvalidByteCount {
		sniPos, sniLen, echPos, err := findSNIAndECH(s.writeBuf)
		if errors.Is(err, io.ErrUnexpectedEOF) {
			return len(p), nil
		}
		if err != nil {
			return len(p), err
		}
		if sniPos == -1 && echPos == -1 {
			// Neither SNI nor ECH found.
			// There's nothing to scramble.
			s.scramble = false
			return len(p), nil
		}
		s.end = protocol.ByteCount(len(s.writeBuf))
		s.cuts[0].start = protocol.ByteCount(sniPos + sniLen/2) // right in the middle
		s.cuts[0].end = protocol.ByteCount(sniPos + sniLen)
		if echPos > 0 {
			// ECH extension found, cut the ECH extension type value (a uint16) in half
			start := protocol.ByteCount(echPos + 1)
			s.cuts[1].start = start
			// cut somewhere (16 bytes), most likely in the ECH extension value
			s.cuts[1].end = min(start+16, s.end)
		}
		slices.SortFunc(s.cuts[:], func(a, b clientHelloCut) int {
			if a.start == protocol.InvalidByteCount {
				return 1
			}
			if a.start > b.start {
				return 1
			}
			return -1
		})
	}
	return len(p), nil
}

func (s *initialCryptoStream) PopCryptoFrame(maxLen protocol.ByteCount) *wire.CryptoFrame {
	if !s.scramble {
		return s.baseCryptoStream.PopCryptoFrame(maxLen)
	}

	// send out the skipped parts
	if s.writeOffset == s.end {
		var foundCuts bool
		var f *wire.CryptoFrame
		for i, c := range s.cuts {
			if c.start == protocol.InvalidByteCount {
				continue
			}
			foundCuts = true
			if f != nil {
				break
			}
			f = &wire.CryptoFrame{Offset: c.start}
			n := min(f.MaxDataLen(maxLen), c.end-c.start)
			if n <= 0 {
				return nil
			}
			f.Data = s.writeBuf[c.start : c.start+n]
			s.cuts[i].start += n
			if s.cuts[i].start == c.end {
				s.cuts[i].start = protocol.InvalidByteCount
				s.cuts[i].end = protocol.InvalidByteCount
				foundCuts = false
			}
		}
		if !foundCuts {
			// no more cuts found, we're done sending out everything up until s.end
			s.writeBuf = s.writeBuf[s.end:]
			s.end = protocol.InvalidByteCount
			s.scramble = false
		}
		return f
	}

	nextCut := clientHelloCut{start: protocol.InvalidByteCount, end: protocol.InvalidByteCount}
	for _, c := range s.cuts {
		if c.start == protocol.InvalidByteCount {
			continue
		}
		if c.start > s.writeOffset {
			nextCut = c
			break
		}
	}
	f := &wire.CryptoFrame{Offset: s.writeOffset}
	maxOffset := nextCut.start
	if maxOffset == protocol.InvalidByteCount {
		maxOffset = s.end
	}
	n := min(f.MaxDataLen(maxLen), maxOffset-s.writeOffset)
	if n <= 0 {
		return nil
	}
	f.Data = s.writeBuf[s.writeOffset : s.writeOffset+n]
	// Don't reslice the writeBuf yet.
	// This is done once all parts have been sent out.
	s.writeOffset += n
	if s.writeOffset == nextCut.start {
		s.writeOffset = nextCut.end
	}

	return f
}