-
Notifications
You must be signed in to change notification settings - Fork 28
/
onion_transport_test.go
100 lines (88 loc) · 1.79 KB
/
onion_transport_test.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
package oniontransport
import (
"crypto/rand"
"crypto/rsa"
"encoding/pem"
ma "github.com/multiformats/go-multiaddr"
"github.com/yawning/bulb/utils/pkcs1"
"os"
"path"
"testing"
)
var key string
func TestMain(m *testing.M) {
setup()
retCode := m.Run()
teardown()
os.Exit(retCode)
}
func setup() {
key, _ = createHiddenServiceKey()
}
func teardown() {
os.RemoveAll(path.Join("./", key+".onion_key"))
}
func TestIsValidOnionMultiAddr(t *testing.T) {
// Test valid
validAddr, err := ma.NewMultiaddr("/onion/erhkddypoy6qml6h:4003")
if err != nil {
t.Fatal(err)
}
valid := IsValidOnionMultiAddr(validAddr)
if !valid {
t.Fatal("IsValidMultiAddr failed")
}
// Test wrong protocol
invalidAddr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/4001")
if err != nil {
t.Fatal(err)
}
valid = IsValidOnionMultiAddr(invalidAddr)
if valid {
t.Fatal("IsValidMultiAddr failed")
}
}
func Test_loadKeys(t *testing.T) {
tpt := &OnionTransport{keysDir: "./"}
keys, err := tpt.loadKeys()
if err != nil {
t.Fatal(err)
}
tpt.keys = keys
k, ok := tpt.keys[key]
if !ok {
t.Fatal("Failed to correctly load keys")
}
id, err := pkcs1.OnionAddr(&k.PublicKey)
if err != nil {
t.Fatal(err)
}
if id != key {
t.Fatal("Failed to correctly load keys")
}
}
func createHiddenServiceKey() (string, error) {
priv, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return "", err
}
id, err := pkcs1.OnionAddr(&priv.PublicKey)
if err != nil {
return "", err
}
f, err := os.Create(id + ".onion_key")
if err != nil {
return "", err
}
defer f.Close()
privKeyBytes, err := pkcs1.EncodePrivateKeyDER(priv)
if err != nil {
return "", err
}
block := pem.Block{Type: "RSA PRIVATE KEY", Bytes: privKeyBytes}
err = pem.Encode(f, &block)
if err != nil {
return "", err
}
return id, nil
}