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
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build linux
// +build linux
// This sample creates a stack with TCP and IPv4 protocols on top of a TUN
// device, and connects to a peer. Similar to "nc <address> <port>". While the
// sample is running, attempts to connect to its IPv4 address will result in
// a RST segment.
//
// As an example of how to run it, a TUN device can be created and enabled on
// a linux host as follows (this only needs to be done once per boot):
//
// [sudo] ip tuntap add user <username> mode tun <device-name>
// [sudo] ip link set <device-name> up
// [sudo] ip addr add <ipv4-address>/<mask-length> dev <device-name>
//
// A concrete example:
//
// $ sudo ip tuntap add user wedsonaf mode tun tun0
// $ sudo ip link set tun0 up
// $ sudo ip addr add 192.168.1.1/24 dev tun0
//
// Then one can run tun_tcp_connect as such:
//
// $ ./tun/tun_tcp_connect tun0 192.168.1.2 0 192.168.1.1 1234
//
// This will attempt to connect to the linux host's stack. One can run nc in
// listen mode to accept a connect from tun_tcp_connect and exchange data.
package main
import (
"bytes"
"fmt"
"log"
"math/rand"
"net"
"os"
"strconv"
"time"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
"gvisor.dev/gvisor/pkg/tcpip/link/rawfile"
"gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
"gvisor.dev/gvisor/pkg/tcpip/link/tun"
"gvisor.dev/gvisor/pkg/tcpip/link/tunnel"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/gre"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/waiter"
)
// writer reads from standard input and writes to the endpoint until standard
// input is closed. It signals that it's done by closing the provided channel.
func writer(ch chan struct{}, ep tcpip.Endpoint) {
defer func() {
ep.Shutdown(tcpip.ShutdownWrite)
close(ch)
}()
var b bytes.Buffer
if err := func() error {
for {
if _, err := b.ReadFrom(os.Stdin); err != nil {
return fmt.Errorf("b.ReadFrom failed: %w", err)
}
for b.Len() != 0 {
if _, err := ep.Write(&b, tcpip.WriteOptions{Atomic: true}); err != nil {
return fmt.Errorf("ep.Write failed: %s", err)
}
}
}
}(); err != nil {
fmt.Println(err)
}
}
func parseIP(s string) tcpip.Address {
addr := tcpip.Address(net.ParseIP(s))
ip4addr := addr.To4(); if ip4addr != "" {
return ip4addr
} else {
return addr
}
}
func addAddress(s *stack.Stack, id tcpip.NICID, addr tcpip.Address) *tcpip.Error {
var proto tcpip.NetworkProtocolNumber
if addr.To4() == "" {
proto = ipv6.ProtocolNumber
} else {
proto = ipv4.ProtocolNumber
}
return s.AddAddress(id, proto, addr)
}
func main() {
if len(os.Args) != 8 {
log.Fatal("Usage: ", os.Args[0], " <tun-device> <local-ipv4-address> <local-port> <remote-ipv4-address> <remote-port> <local-gre-address> <remote-gre-address>")
}
tunName := os.Args[1]
addrName := os.Args[2]
portName := os.Args[3]
remoteAddrName := os.Args[4]
remotePortName := os.Args[5]
greAddrName := os.Args[6]
greRemoteAddrName := os.Args[7]
rand.Seed(time.Now().UnixNano())
addr := parseIP(addrName)
greAddr := parseIP(greAddrName)
greRemoteAddr := parseIP(greRemoteAddrName)
remote := tcpip.FullAddress{
NIC: 0,
Addr: parseIP(remoteAddrName),
}
log.Printf("local:%v remote:%v", addr, remote)
var localPort uint16
if v, err := strconv.Atoi(portName); err != nil {
log.Fatalf("Unable to convert port %v: %v", portName, err)
} else {
localPort = uint16(v)
}
if v, err := strconv.Atoi(remotePortName); err != nil {
log.Fatalf("Unable to convert port %v: %v", remotePortName, err)
} else {
remote.Port = uint16(v)
}
// Create the stack with ipv4 and tcp protocols, then add a tun-based
// NIC and ipv4 address.
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, gre.NewProtocol},
})
mtu, err := rawfile.GetMTU(tunName)
if err != nil {
log.Fatal(err)
}
fd, err := tun.Open(tunName)
if err != nil {
log.Fatal(err)
}
linkEP, err := fdbased.New(&fdbased.Options{FDs: []int{fd}, MTU: mtu})
if err != nil {
log.Fatal(err)
}
if err := s.CreateNIC(1, sniffer.New(linkEP)); err != nil {
log.Fatal(err)
}
if err := addAddress(s, 1, greAddr); err != nil {
log.Fatal(err)
}
greEP := tunnel.New(mtu - 24)
if err := s.CreateNIC(2, sniffer.New(greEP)); err != nil {
log.Fatal(err)
}
if err := addAddress(s, 2, addr); err != nil {
log.Fatal(err)
}
// Add default route.
subnet, err := tcpip.NewSubnet(
tcpip.Address(parseIP("10.0.0.0")),
tcpip.AddressMask(parseIP("255.255.255.0")))
if err != nil {
panic(err)
}
s.SetRouteTable([]tcpip.Route{
{
Destination: subnet,
NIC: 1,
},
{
Destination: header.IPv4EmptySubnet,
NIC: 2,
},
{
Destination: header.IPv6EmptySubnet,
NIC: 1,
},
})
log.Printf("Nics enabled 1:%v 2:%v 3:%v", s.CheckNIC(1), s.CheckNIC(2), s.CheckNIC(3))
greEP.Start(s, &greAddr, &greRemoteAddr)
// Create TCP endpoint.
var wq waiter.Queue
ep, e := s.NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &wq)
if e != nil {
log.Fatal(e)
}
// Bind if a port is specified.
if localPort != 0 {
if err := ep.Bind(tcpip.FullAddress{0, "", localPort}); err != nil {
log.Fatal("Bind failed: ", err)
}
}
// Issue connect request and wait for it to complete.
waitEntry, notifyCh := waiter.NewChannelEntry(nil)
wq.EventRegister(&waitEntry, waiter.WritableEvents)
terr := ep.Connect(remote)
if _, ok := terr.(*tcpip.ErrConnectStarted); ok {
fmt.Println("Connect is pending...")
<-notifyCh
terr = ep.LastError()
}
wq.EventUnregister(&waitEntry)
if terr != nil {
log.Fatal("Unable to connect: ", terr)
}
fmt.Println("Connected")
payload := tcpip.SlicePayload([]byte("GET / HTTP/1.0\r\nHost: www.m7n.se\r\n\r\n"))
ep.Write(payload, tcpip.WriteOptions{})
// Start the writer in its own goroutine.
writerCompletedCh := make(chan struct{})
go writer(writerCompletedCh, ep) // S/R-SAFE: sample code.
// Read data and write to standard output until the peer closes the
// connection from its side.
wq.EventRegister(&waitEntry, waiter.ReadableEvents)
for {
_, err := ep.Read(os.Stdout, tcpip.ReadOptions{})
if err != nil {
if _, ok := err.(*tcpip.ErrClosedForReceive); ok {
break
}
if _, ok := err.(*tcpip.ErrWouldBlock); ok {
<-notifyCh
continue
}
log.Fatal("Read() failed:", err)
}
}
wq.EventUnregister(&waitEntry)
// The reader has completed. Now wait for the writer as well.
<-writerCompletedCh
ep.Close()
}
|