-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.go
348 lines (288 loc) · 10.2 KB
/
tcp.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package packemon
import (
"bytes"
"context"
"encoding/binary"
"golang.org/x/sys/unix"
)
const (
TCP_FLAGS_SYN = 0x02
TCP_FLAGS_SYN_ACK = 0x12
TCP_FLAGS_ACK = 0x10
TCP_FLAGS_FIN_ACK = 0x11
TCP_FLAGS_PSH_ACK = 0x18 // データを上位層へ渡してという信号
TCP_FLAGS_FIN_PSH_ACK = 0x19
)
type TCP struct {
SrcPort uint16
DstPort uint16
Sequence uint32
Acknowledgment uint32
// Data Offset (DOffset)(4bit. TCPヘッダ長. 32bit整数倍) と Reserved (Rsrvd)(4bit. すべて0)
// ref: https://www.rfc-editor.org/rfc/rfc9293.html#section-3.1
HeaderLength uint8
// Control bits(8bit)
// ref: https://www.rfc-editor.org/rfc/rfc9293.html#section-3.1-6.14.1
Flags uint8
Window uint16
Checksum uint16
UrgentPointer uint16
Options []byte // optionsをセットする用の関数あった方がいいかも?
Data []byte
}
func ParsedTCP(payload []byte) *TCP {
tcp := &TCP{
SrcPort: binary.BigEndian.Uint16(payload[0:2]),
DstPort: binary.BigEndian.Uint16(payload[2:4]),
Sequence: binary.BigEndian.Uint32(payload[4:8]),
Acknowledgment: binary.BigEndian.Uint32(payload[8:12]),
HeaderLength: payload[12] & 0b11110000,
Flags: payload[13],
Window: binary.BigEndian.Uint16(payload[14:16]),
Checksum: binary.BigEndian.Uint16(payload[16:18]),
UrgentPointer: binary.BigEndian.Uint16(payload[18:20]),
}
// Wiresharkとpackemonのパケット詳細見比べるに、
// ( tcpヘッダーのheader lengthを10進数に変換した値 / 4 ) - 20 = options のbyte数 になるよう
// optionLength := tcp.HeaderLength>>2 - 20
// if optionLength > 0 {
// tcp.Options = payload[20 : optionLength+20]
// }
// tcp.Data = payload[optionLength+20:]
tcp.Data = payload[20:]
return tcp
}
func newTCP(flags uint8, srcPort, dstPort uint16, sequence, acknowledgment uint32, data []byte) *TCP {
return &TCP{
SrcPort: srcPort,
DstPort: dstPort,
Sequence: sequence,
Acknowledgment: acknowledgment,
HeaderLength: 0x0050,
Flags: flags,
Window: 0xfaf0,
Checksum: 0x0000,
UrgentPointer: 0x0000,
// Options: Options(),
Data: data,
}
}
// tcpパケット単発で連続で送るときは port/sequence 変えること
func NewTCPSyn(srcPort, dstPort uint16) *TCP {
return newTCP(0x02 /** syn **/, srcPort, dstPort, 0x091f58f9, 0x00000000, nil)
}
// tcpパケット連続で送るときは port 変えること
func NewTCPAck(srcPort, dstPort uint16, prevSequence uint32, prevAcknowledgment uint32) *TCP {
return newTCP(0x10 /** ack **/, srcPort, dstPort, prevAcknowledgment, prevSequence+0x00000001, nil)
}
// tcpパケット連続で送るときは port 変えること
func NewTCPAckForPassiveData(srcPort, dstPort uint16, prevSequence uint32, prevAcknowledgment uint32, tcpPayloadLength int) *TCP {
return newTCP(0x10 /** ack **/, srcPort, dstPort, prevAcknowledgment, prevSequence+uint32(tcpPayloadLength), nil)
}
// tcpパケット連続で送るときは port 変えること
func NewTCPWithData(srcPort, dstPort uint16, data []byte, prevSequence uint32, prevAcknowledgment uint32) *TCP {
return newTCP(0x18 /** push/ack **/, srcPort, dstPort, prevSequence, prevAcknowledgment, data)
}
// tcpパケット連続で送るときは port 変えること
func NewTCPFinAck(srcPort, dstPort uint16, prevSequence uint32, prevAcknowledgment uint32) *TCP {
return newTCP(0x11 /** fin/ack **/, srcPort, dstPort, prevSequence, prevAcknowledgment, nil)
}
// https://atmarkit.itmedia.co.jp/ait/articles/0401/29/news080_2.html
// 「「チェックサム」フィールド:16bit幅」
func (t *TCP) CalculateChecksum(ipv4 *IPv4) {
t.Checksum = func() uint16 {
pseudoTCPHeader := func() []byte {
buf := &bytes.Buffer{}
WriteUint32(buf, ipv4.SrcAddr)
WriteUint32(buf, ipv4.DstAddr)
padding := byte(0x00)
buf.WriteByte(padding)
buf.WriteByte(ipv4.Protocol)
WriteUint16(buf, uint16(len(t.Bytes())))
return buf.Bytes()
}()
forTCPChecksum := &bytes.Buffer{}
forTCPChecksum.Write(pseudoTCPHeader)
forTCPChecksum.Write(t.Bytes())
if len(t.Data)%2 != 0 {
forTCPChecksum.WriteByte(0x00)
}
return binary.BigEndian.Uint16(t.checksum(forTCPChecksum.Bytes()))
}()
}
func (*TCP) checksum(packet []byte) []byte {
return calculateChecksum(packet)
}
// https://www.infraexpert.com/study/tcpip8.html
func (t *TCP) Bytes() []byte {
buf := &bytes.Buffer{}
buf.Write(t.headerToBytes())
buf.Write(t.Data)
return buf.Bytes()
}
func (t *TCP) headerToBytes() []byte {
buf := &bytes.Buffer{}
WriteUint16(buf, t.SrcPort)
WriteUint16(buf, t.DstPort)
WriteUint32(buf, t.Sequence)
WriteUint32(buf, t.Acknowledgment)
buf.WriteByte(t.HeaderLength)
buf.WriteByte(t.Flags)
WriteUint16(buf, t.Window)
WriteUint16(buf, t.Checksum)
WriteUint16(buf, t.UrgentPointer)
buf.Write(t.Options)
return buf.Bytes()
}
// with tcp 3 way handshake
func EstablishConnectionAndSendPayload(nwInterface string, dstIPAddr []byte, dstPort uint16, payload []byte) error {
nwt, err := NewNetworkInterfaceForTCP(nwInterface)
if err != nil {
return err
}
if err := nwt.Connect(dstIPAddr, dstPort); err != nil {
return err
}
defer nwt.Close()
if _, err := nwt.Write(payload); err != nil {
return err
}
return nil
}
// このなかで、ログ出力などしないこと。Monitor の下に出てくる
// 挙動を詳細に確認する場合は、internal内の SendTCP3wayhandshake 関数でやること
// TODO: 対向からRST,RST/ACKが来た時にreturnするようにする
// TODO: http専用になっちゃってるから、他のプロトコルでも使えるよう汎用的にする
func EstablishConnectionAndSendPayloadXxx(ctx context.Context, nwInterface string, fEthrh *EthernetHeader, fIpv4 *IPv4, fTcp *TCP, fHttp *HTTP) error {
nw, err := NewNetworkInterface(nwInterface)
if err != nil {
return err
}
var srcPort uint16 = fTcp.SrcPort
var dstPort uint16 = fTcp.DstPort
var srcIPAddr uint32 = fIpv4.SrcAddr
var dstIPAddr uint32 = fIpv4.DstAddr
dstMACAddr := fEthrh.Dst
srcMACAddr := fEthrh.Src
tcp := NewTCPSyn(srcPort, dstPort)
ipv4 := NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame := NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
for {
select {
case <-ctx.Done():
return nil
default:
recieved := make([]byte, 1500)
n, _, err := unix.Recvfrom(nw.Socket, recieved, 0)
if err != nil {
if n == -1 {
continue
}
return err
}
ethernetFrame := ParsedEthernetFrame(recieved)
switch ethernetFrame.Header.Typ {
case ETHER_TYPE_IPv4:
ipv4 := ParsedIPv4(ethernetFrame.Data)
switch ipv4.Protocol {
case IPv4_PROTO_TCP:
tcp := ParsedTCP(ipv4.Data)
switch tcp.DstPort {
case srcPort: // synパケットの送信元ポート
if tcp.Flags == TCP_FLAGS_SYN_ACK {
// log.Println("passive TCP_FLAGS_SYN_ACK")
// syn/ackを受け取ったのでack送信
tcp := NewTCPAck(srcPort, dstPort, tcp.Sequence, tcp.Acknowledgment)
ipv4 := NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame := NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
tcp = NewTCPWithData(srcPort, dstPort, fHttp.Bytes(), tcp.Sequence, tcp.Acknowledgment)
ipv4 = NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame = NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
continue
}
if tcp.Flags == TCP_FLAGS_ACK {
// log.Println("passive TCP_FLAGS_ACK")
continue
}
if tcp.Flags == TCP_FLAGS_PSH_ACK {
lineLength := bytes.Index(tcp.Data, []byte{0x0d, 0x0a}) // "\r\n"
if lineLength == -1 {
// log.Println("-1")
continue
}
// log.Println("passive TCP_FLAGS_PSH_ACK")
// HTTPレスポンス受信
if tcp.SrcPort == PORT_HTTP {
resp := ParsedHTTPResponse(tcp.Data)
// log.Printf("%+v\n", resp)
// そのackを返す
// log.Printf("Length of http resp: %d\n", resp.Len())
tcp := NewTCPAckForPassiveData(srcPort, dstPort, tcp.Sequence, tcp.Acknowledgment, resp.Len())
ipv4 := NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame := NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
// 続けてFinAck
tcp = NewTCPFinAck(srcPort, dstPort, tcp.Sequence, tcp.Acknowledgment)
ipv4 = NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame = NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
}
continue
}
if tcp.Flags == TCP_FLAGS_FIN_ACK {
// log.Println("passive TCP_FLAGS_FIN_ACK")
// それにack
tcp := NewTCPAck(srcPort, dstPort, tcp.Sequence, tcp.Acknowledgment)
ipv4 := NewIPv4(IPv4_PROTO_TCP, srcIPAddr, dstIPAddr)
tcp.CalculateChecksum(ipv4)
ipv4.Data = tcp.Bytes()
ipv4.CalculateTotalLength()
ipv4.CalculateChecksum()
ethernetFrame := NewEthernetFrame(dstMACAddr, srcMACAddr, ETHER_TYPE_IPv4, ipv4.Bytes())
if err := nw.Send(ethernetFrame); err != nil {
return err
}
return nil
}
continue
default:
// noop
}
}
}
}
}
}