Debian Codegraph @

packet.go

raw
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package sctp
5
6 import (
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "hash/crc32"
11 "strings"
12 )
13
14 // Create the crc32 table we'll use for the checksum.
15 var castagnoliTable = crc32.MakeTable(crc32.Castagnoli) // nolint:gochecknoglobals
16
17 // Allocate and zero this data once.
18 // We need to use it for the checksum and don't want to allocate/clear each time.
19 var fourZeroes [4]byte // nolint:gochecknoglobals
20
21 /*
22 Packet represents an SCTP packet, defined in https://tools.ietf.org/html/rfc4960#section-3
23 An SCTP packet is composed of a common header and chunks. A chunk
24 contains either control information or user data.
25
26 SCTP Packet Format
27 0 1 2 3
28 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
29 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30 | Common Header |
31 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32 | Chunk #1 |
33 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34 | ... |
35 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36 | Chunk #n |
37 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
38
39 SCTP Common Header Format
40 0 1 2 3
41 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
42 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
43 | Source Value Number | Destination Value Number |
44 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
45 | Verification Tag |
46 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
47 | Checksum |
48 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
49 */
50 type packet struct {
51 sourcePort uint16
52 destinationPort uint16
53 verificationTag uint32
54 chunks []chunk
55 }
56
57 const (
58 packetHeaderSize = 12
59 )
60
61 // SCTP packet errors.
62 var (
63 ErrPacketRawTooSmall = errors.New("raw is smaller than the minimum length for a SCTP packet")
64 ErrParseSCTPChunkNotEnoughData = errors.New("unable to parse SCTP chunk, not enough data for complete header")
65 ErrUnmarshalUnknownChunkType = errors.New("failed to unmarshal, contains unknown chunk type")
66 ErrChecksumMismatch = errors.New("checksum mismatch theirs")
67 )
68
69 func (p *packet) unmarshal(doChecksum bool, raw []byte) error { //nolint:cyclop
70 if len(raw) < packetHeaderSize {
71 return fmt.Errorf("%w: raw only %d bytes, %d is the minimum length", ErrPacketRawTooSmall, len(raw), packetHeaderSize)
72 }
73
74 offset := packetHeaderSize
75
76 // Check if doing CRC32c is required.
77 // Without having SCTP AUTH implemented, this depends only on the type
78 // og the first chunk.
79 if offset+chunkHeaderSize <= len(raw) {
80 switch chunkType(raw[offset]) {
81 case ctInit, ctCookieEcho:
82 doChecksum = true
83 default:
84 }
85 }
86 theirChecksum := binary.LittleEndian.Uint32(raw[8:])
87 if theirChecksum != 0 || doChecksum {
88 ourChecksum := generatePacketChecksum(raw)
89 if theirChecksum != ourChecksum {
90 return fmt.Errorf("%w: %d ours: %d", ErrChecksumMismatch, theirChecksum, ourChecksum)
91 }
92 }
93
94 p.sourcePort = binary.BigEndian.Uint16(raw[0:])
95 p.destinationPort = binary.BigEndian.Uint16(raw[2:])
96 p.verificationTag = binary.BigEndian.Uint32(raw[4:])
97
98 for offset < len(raw) {
99 // guaranteed to be safe by loop condition
100 remaining := raw[offset:] // nolint:gosec
101
102 // must have at least a full chunk header to continue.
103 if len(remaining) < chunkHeaderSize {
104 return fmt.Errorf("%w: offset %d remaining %d", ErrParseSCTPChunkNotEnoughData, offset, len(remaining))
105 }
106
107 ctype := chunkType(remaining[0])
108
109 var dataChunk chunk
110 switch ctype {
111 case ctInit:
112 dataChunk = &chunkInit{}
113 case ctInitAck:
114 dataChunk = &chunkInitAck{}
115 case ctAbort:
116 dataChunk = &chunkAbort{}
117 case ctCookieEcho:
118 dataChunk = &chunkCookieEcho{}
119 case ctCookieAck:
120 dataChunk = &chunkCookieAck{}
121 case ctHeartbeat:
122 dataChunk = &chunkHeartbeat{}
123 case ctPayloadData:
124 dataChunk = &chunkPayloadData{}
125 case ctIData:
126 dataChunk = &chunkPayloadData{}
127 case ctSack:
128 dataChunk = &chunkSelectiveAck{}
129 case ctReconfig:
130 dataChunk = &chunkReconfig{}
131 case ctForwardTSN:
132 dataChunk = &chunkForwardTSN{}
133 case ctIForwardTSN:
134 dataChunk = &chunkIForwardTSN{}
135 case ctError:
136 dataChunk = &chunkError{}
137 case ctShutdown:
138 dataChunk = &chunkShutdown{}
139 case ctShutdownAck:
140 dataChunk = &chunkShutdownAck{}
141 case ctShutdownComplete:
142 dataChunk = &chunkShutdownComplete{}
143 default:
144 return fmt.Errorf("%w: %s", ErrUnmarshalUnknownChunkType, ctype.String())
145 }
146
147 if err := dataChunk.unmarshal(remaining); err != nil {
148 return err
149 }
150
151 p.chunks = append(p.chunks, dataChunk)
152 chunkValuePadding := getPadding(dataChunk.valueLength())
153 offset += chunkHeaderSize + dataChunk.valueLength() + chunkValuePadding
154 }
155
156 // if we overshot then should error.
157 if offset != len(raw) {
158 if offset > len(raw) {
159 overshoot := offset - len(raw)
160
161 return fmt.Errorf("%w: parsed past end of buffer by %d bytes (offset %d, length %d)",
162 ErrParseSCTPChunkNotEnoughData, overshoot, offset, len(raw))
163 }
164
165 remaining := len(raw) - offset
166
167 return fmt.Errorf("%w: unparsed data remaining: %d bytes (offset %d, length %d)",
168 ErrParseSCTPChunkNotEnoughData, remaining, offset, len(raw))
169 }
170
171 return nil
172 }
173
174 func (p *packet) marshal(doChecksum bool) ([]byte, error) {
175 raw := make([]byte, packetHeaderSize)
176
177 // Populate static headers
178 // 8-12 is Checksum which will be populated when packet is complete
179 binary.BigEndian.PutUint16(raw[0:], p.sourcePort)
180 binary.BigEndian.PutUint16(raw[2:], p.destinationPort)
181 binary.BigEndian.PutUint32(raw[4:], p.verificationTag)
182
183 // Populate chunks
184 for _, c := range p.chunks {
185 chunkRaw, err := c.marshal()
186 if err != nil {
187 return nil, err
188 }
189 raw = append(raw, chunkRaw...) //nolint:makezero // todo:fix
190
191 paddingNeeded := getPadding(len(raw))
192 if paddingNeeded != 0 {
193 raw = append(raw, make([]byte, paddingNeeded)...) //nolint:makezero // todo:fix
194 }
195 }
196
197 if doChecksum {
198 // golang CRC32C uses reflected input and reflected output, the
199 // net result of this is to have the bytes flipped compared to
200 // the non reflected variant that the spec expects.
201 //
202 // Use LittleEndian.PutUint32 to avoid flipping the bytes in to
203 // the spec compliant checksum order
204 binary.LittleEndian.PutUint32(raw[8:], generatePacketChecksum(raw))
205 }
206
207 return raw, nil
208 }
209
210 func generatePacketChecksum(raw []byte) (sum uint32) {
211 // Fastest way to do a crc32 without allocating.
212 sum = crc32.Update(sum, castagnoliTable, raw[0:8])
213 sum = crc32.Update(sum, castagnoliTable, fourZeroes[:])
214 sum = crc32.Update(sum, castagnoliTable, raw[12:])
215
216 return sum
217 }
218
219 // String makes packet printable.
220 func (p *packet) String() string {
221 format := `Packet:
222 sourcePort: %d
223 destinationPort: %d
224 verificationTag: %d
225 `
226 var res strings.Builder
227 fmt.Fprintf(&res, format,
228 p.sourcePort,
229 p.destinationPort,
230 p.verificationTag,
231 )
232 for i, chunk := range p.chunks {
233 fmt.Fprintf(&res, "Chunk %d:\n %s", i, chunk)
234 }
235
236 return res.String()
237 }
238
239 // TryMarshalUnmarshal attempts to marshal and unmarshal a message. Added for fuzzing.
240 func TryMarshalUnmarshal(msg []byte) int {
241 p := &packet{}
242 err := p.unmarshal(false, msg)
243 if err != nil {
244 return 0
245 }
246
247 _, err = p.marshal(false)
248 if err != nil {
249 return 0
250 }
251
252 return 1
253 }