-
Notifications
You must be signed in to change notification settings - Fork 1
/
hidden_service.go
288 lines (240 loc) · 7.83 KB
/
hidden_service.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
package descriptor
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/csucu/onionspread/common"
)
// HiddenServiceDescriptor represents a v2 hidden service descriptor as defined in
// https://github.com/torproject/torspec/blob/master/rend-spec-v2.txt
type HiddenServiceDescriptor struct {
DescriptorID string
Version int
PermanentKey string
SecretID string
Published time.Time
ProtocolVersions []int
IntroductionPointsRaw string
IntroductionPoints []IntroductionPoint
Signature string
}
// IntroductionPoint represents a introduction point
type IntroductionPoint struct {
Identifier string
Address net.IP
Port int
OnionKey string
ServiceKey string
Raw string
}
func ParseHiddenServiceDescriptor(descriptorRaw string) (*HiddenServiceDescriptor, error) {
descriptor := &HiddenServiceDescriptor{}
lines := strings.Split(descriptorRaw, "\n")
var err error
for i, line := range lines {
words := strings.Split(line, " ")
switch words[0] {
case "rendezvous-service-descriptor":
descriptor.DescriptorID = words[1]
case "version":
descriptor.Version, err = strconv.Atoi(words[1])
case "permanent-key":
descriptor.PermanentKey, err = extractEntry("-----END RSA PUBLIC KEY-----", lines[i:])
case "secret-id-part":
descriptor.SecretID = words[1]
case "publication-time":
descriptor.Published, err = time.Parse("2006-01-02 15:04:05", strings.Join(words[1:], " "))
case "protocol-versions":
for _, versionStr := range strings.Split(words[1], ",") {
version, err := strconv.Atoi(versionStr)
if err != nil {
return nil, err
}
descriptor.ProtocolVersions = append(descriptor.ProtocolVersions, version)
}
case "introduction-points":
descriptor.IntroductionPointsRaw, err = extractEntry("-----END MESSAGE-----", lines[i:])
descriptor.IntroductionPoints, err = parseIntroductionPoints(descriptor.IntroductionPointsRaw)
case "signature":
descriptor.Signature, err = extractEntry("-----END SIGNATURE-----", lines[i:])
}
if err != nil {
return nil, err
}
}
return descriptor, nil
}
// parseIntroductionPoints parses the introduction points block given in a descriptor
func parseIntroductionPoints(data string) ([]IntroductionPoint, error) {
var introductionPoints []IntroductionPoint
block, rest := pem.Decode([]byte(data))
if len(rest) > 0 {
return introductionPoints, errors.New("trailing bytes when decoding introduction points PEM")
}
raw := string(block.Bytes)
for {
var EOF bool
var err error
var introductionPoint *IntroductionPoint
introductionPoint, raw, EOF, err = extractIntroductionPoints(raw)
if err != nil {
return introductionPoints, err
}
introductionPoints = append(introductionPoints, *introductionPoint)
if EOF {
break
}
}
return introductionPoints, nil
}
// extractIntroductionPoints extracts a single introduction point from the provided raw introduction point block
func extractIntroductionPoints(data string) (*IntroductionPoint, string, bool, error) {
if len(data) == 0 {
return nil, data, true, nil
}
start := 0
if !strings.HasPrefix(data, string("introduction-point")) {
start = strings.Index(data, string("introduction-point"))
if start < 0 {
return nil, data, false, errors.New("cannot find any introduction points")
}
}
end := strings.Index(data[start:], string("\nintroduction-point "))
if end >= 0 {
introductionPoint, err := parseIntroductionPoint(data[start : start+end+1])
if err != nil {
return nil, "", false, err
}
return introductionPoint, data[start+end+1:], false, nil
}
introductionPoint, err := parseIntroductionPoint(data[start:])
if err != nil {
return nil, "", false, err
}
return introductionPoint, "", true, nil
}
// parseIntroductionPoint returns an introduction point object given its raw representation
func parseIntroductionPoint(data string) (*IntroductionPoint, error) {
introductionPoint := &IntroductionPoint{}
lines := strings.Split(data, "\n")
var err error
for i, line := range lines {
words := strings.Split(line, " ")
switch words[0] {
case "introduction-point":
introductionPoint.Identifier = words[1]
case "ip-address":
introductionPoint.Address = net.ParseIP(words[1])
case "onion-port":
introductionPoint.Port, err = strconv.Atoi(words[1])
case "onion-key":
introductionPoint.OnionKey, err = extractEntry("-----END RSA PUBLIC KEY-----", lines[i:])
if err != nil {
return nil, err
}
case "service-key":
introductionPoint.ServiceKey, err = extractEntry("-----END RSA PUBLIC KEY-----", lines[i:])
}
if err != nil {
return nil, err
}
}
introductionPoint.Raw = data
return introductionPoint, nil
}
func extractEntry(end string, lines []string) (string, error) {
entry := ""
for _, line := range lines[1:] {
entry += line
entry += "\n"
if strings.Contains(line, end) {
break
}
}
if entry == "" {
return "", fmt.Errorf("could not find entry while parsing descriptor")
}
return entry, nil
}
// GenerateDescriptorRaw generates a raw signed hidden service descriptor
func GenerateDescriptorRaw(introductionPoints []IntroductionPoint, publishedTime time.Time, replica byte,
deviation uint8, descriptorCookie string, permanentKey *rsa.PublicKey, privateKey *rsa.PrivateKey, permID []byte, descriptorID []byte) ([]byte, error) {
var err error
if permID == nil {
permID, err = common.CalculatePermanentID(*permanentKey)
if err != nil {
return nil, fmt.Errorf("failed to calculate permanent id: %v", err)
}
}
timeUnix := publishedTime.Unix()
if descriptorID == nil {
descriptorID, err = common.CalculateDescriptorID(permID, timeUnix, replica, deviation, descriptorCookie)
if err != nil {
return nil, err
}
}
// Public key bloc
publicKeyBlock, err := createPublicKeyBloc(permanentKey)
if err != nil {
return nil, fmt.Errorf("failed to calculate publicKeyBlock: %v", err)
}
// secret id
secretIDPart := common.GetSecretID(permID, timeUnix, descriptorCookie, replica)
// Introduction point block
introBlock := createIntroductionPointsBloc(introductionPoints)
// Published time
formattedTime := time.Unix(timeUnix-timeUnix%(60*60), 0).Format("2006-01-02 15:04:05")
var b bytes.Buffer
b.WriteString("rendezvous-service-descriptor ")
b.Write(bytes.ToLower(descriptorID))
b.WriteString("\nversion 2\npermanent-key\n")
b.Write(publicKeyBlock)
b.WriteString("secret-id-part ")
b.Write(secretIDPart)
b.WriteByte('\n')
b.WriteString("publication-time " + formattedTime + "\n")
b.WriteString("protocol-versions 2,3\n")
b.WriteString("introduction-points\n")
b.Write(introBlock)
b.WriteString("signature\n")
// Signature block
signatureBlock, err := createSignatureBlock(b.Bytes(), privateKey)
if err != nil {
return nil, err
}
b.Write(signatureBlock)
return b.Bytes(), nil
}
func createIntroductionPointsBloc(introductionPoints []IntroductionPoint) []byte {
var introductionPointsRaw []byte
for _, IntroductionPoint := range introductionPoints {
introductionPointsRaw = append(introductionPointsRaw, []byte(IntroductionPoint.Raw)...)
}
return pem.EncodeToMemory(&pem.Block{Type: "MESSAGE", Bytes: introductionPointsRaw})
}
func createPublicKeyBloc(permanentKey *rsa.PublicKey) ([]byte, error) {
der, err := asn1.Marshal(*permanentKey)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: der}), nil
}
func createSignatureBlock(descriptor []byte, privateKey *rsa.PrivateKey) ([]byte, error) {
h := sha1.New()
h.Write(descriptor)
signature, err := privateKey.Sign(rand.Reader, h.Sum(nil), crypto.Hash(0))
if err != nil {
return nil, fmt.Errorf("failed to sign descriptor: %v", err)
}
return pem.EncodeToMemory(&pem.Block{Type: "SIGNATURE", Bytes: signature}), nil
}