This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtunnel.go
109 lines (87 loc) · 2.21 KB
/
tunnel.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
package dione
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"github.com/cloudflare/circl/kem/kyber/kyber1024"
"github.com/libp2p/go-libp2p-core/peer"
"io"
)
type tunnel struct {
reader io.Reader
writer io.Writer
netStream io.ReadWriteCloser
}
func (t tunnel) Read(p []byte) (n int, err error) {
n, err = t.reader.Read(p)
return n, err
}
func (t tunnel) Write(p []byte) (n int, err error) {
n, err = t.writer.Write(p)
return n, err
}
func (t tunnel) Close() error {
err := t.netStream.Close()
return err
}
func newTunnel(stream io.ReadWriteCloser, target peer.ID) tunnel {
fmt.Printf("target %v\n", target.String())
generalRequest := new(GeneralRequest)
generalTunnelReq := new(GeneralRequest_InitTunnelRequest)
tunnelReq := new(InitTunnelRequest)
tunnelReq.Target = peer.Encode(target)
keyPub, keyPrv, err := kyber1024.GenerateKeyPair(nil)
if err != nil {
panic(err)
}
keyPubBytes := make([]byte, kyber1024.PublicKeySize)
keyPub.Pack(keyPubBytes)
tunnelReq.Pk = keyPubBytes
generalTunnelReq.InitTunnelRequest = tunnelReq
generalRequest.GeneralRequestKind = generalTunnelReq
handler := &Handler{}
handler.writeMessage(stream, generalRequest)
fmt.Println("Written request")
generalResp := new(GeneralResponse)
err = handler.readMessage(stream, generalResp)
if err != nil {
panic(err)
}
fmt.Println("Response done")
tunnelResp := generalResp.GetInitTunnelResponse()
ct := make([]byte, kyber1024.CiphertextSize)
ss := make([]byte, kyber1024.SharedKeySize)
ct = tunnelResp.Ciphertext
keyPrv.DecapsulateTo(ss, ct)
block, err := aes.NewCipher(ss)
if err != nil {
panic(err)
}
var iv [aes.BlockSize]byte
enc := cipher.NewOFB(block, iv[:])
encReader := &cipher.StreamReader{S: enc, R: stream}
encWriter := &cipher.StreamWriter{S: enc, W: stream}
if err != nil {
panic(err)
}
tun := new(tunnel)
tun.reader = encReader
tun.writer = encWriter
tun.netStream = stream
/*
decrypted := make([]byte, len([]byte("Hello World")))
_, err = encReader.Read(decrypted)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted %v\n", string(decrypted))
*/
return *tun
}
func closeTunnel(tun tunnel) {
fmt.Println("Closing the tunnel")
err := tun.Close()
if err != nil {
panic(err)
}
}