This repository has been archived by the owner on May 12, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
node.go
183 lines (167 loc) · 5.31 KB
/
node.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
// Original work Copyright 2015 2016 Lightning Onion
// Modified work Copyright 2016 David Stainton
//
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package sphinxmixcrypto
import (
"bytes"
"errors"
"fmt"
"github.com/david415/go-lioness"
)
var (
// ErrReplayedPacket indicates a replay attack
ErrReplayedPacket = fmt.Errorf("sphinx packet replay error")
)
const (
// ExitNode indicates an exit hop
ExitNode = 0
// MoreHops indicates another mix hop
MoreHops = 255
// ClientHop indicates a client hop
ClientHop = 128
// Failure indicates a prefix-free decoding failure
Failure
)
// PrefixFreeDecode decodes the prefix-free encoding.
// Return the type, value, and the remainder of the input string
func PrefixFreeDecode(s []byte) (int, []byte, []byte) {
if len(s) == 0 {
return Failure, nil, nil
}
if int(s[0]) == 0 {
return ExitNode, nil, s[1:]
}
if int(s[0]) == 255 {
return MoreHops, s[:securityParameter], s[securityParameter:]
}
if int(s[0]) < 128 {
return ClientHop, s[1 : int(s[0])+1], s[int(s[0])+1:]
}
return Failure, nil, nil
}
// UnwrappedMessage is produced by SphinxNode's Unwrap method
type UnwrappedMessage struct {
ProcessAction int
Alpha []byte // ephemeral key
Beta []byte // routing information
Gamma []byte // MAC
Delta []byte // message body
NextHop []byte
ClientID []byte
MessageID []byte
}
// ReplayCache is an interface for detecting packet replays
type ReplayCache interface {
// Get returns true if the hash value is present in the map
Get([32]byte) bool
// Set sets a hash value in the map
Set([32]byte)
// Flush flushes the map
Flush()
}
// PrivateKey interface is used to access the private key so the mix
// can unwrap packets
type PrivateKey interface {
// GetPrivateKey returns the private key
GetPrivateKey() [32]byte
}
// SphinxPacketUnwrap performs the decryption operation that a mix would perform
// An error is returned if the MAC doesn't match or if a packet is replayed.
func SphinxPacketUnwrap(params *SphinxParams, replayCache ReplayCache, privateKey PrivateKey, packet *SphinxPacket) (*UnwrappedMessage, error) {
group := NewGroupCurve25519()
digest := NewBlake2bDigest()
streamCipher := &Chacha20Stream{}
blockCipher := NewLionessBlockCipher()
result := &UnwrappedMessage{}
mixHeader := packet.Header
dhKey := mixHeader.EphemeralKey
routeInfo := mixHeader.RoutingInfo
sharedSecret := group.ExpOn(dhKey, privateKey.GetPrivateKey())
headerMac := mixHeader.HeaderMAC
payload := packet.Payload
// Have we seen it already?
tag := digest.HashReplay(sharedSecret)
if replayCache.Get(tag) {
return nil, ErrReplayedPacket
}
key, err := digest.DeriveHMACKey(sharedSecret)
if err != nil {
return nil, fmt.Errorf("HMAC key derivation fail: %s", err)
}
mac, err := digest.HMAC(key, routeInfo)
if err != nil {
return nil, fmt.Errorf("HMAC fail: %s", err)
}
if !bytes.Equal(headerMac[:], mac[:]) {
// invalid MAC
return nil, errors.New("invalid mac")
}
replayCache.Set(tag)
cipherStreamSize := len(routeInfo) + (2 * securityParameter)
cipherStream, err := streamCipher.GenerateStream(digest.DeriveStreamCipherKey(sharedSecret), uint(cipherStreamSize))
if err != nil {
// stream cipher failure
return nil, fmt.Errorf("stream cipher failure: %s", err)
}
B := make([]byte, cipherStreamSize)
padding := make([]byte, 2*securityParameter)
lioness.XorBytes(B, append(routeInfo, padding...), cipherStream)
deltaKey, err := blockCipher.CreateBlockCipherKey(sharedSecret)
if err != nil {
return nil, fmt.Errorf("createBlockCipherKey failure: %s", err)
}
delta, err := blockCipher.Decrypt(deltaKey, payload)
if err != nil {
return nil, fmt.Errorf("123 wide block cipher decryption failure: %s", err)
}
betaLen := uint((2*params.MaxHops + 1) * securityParameter)
messageType, val, rest := PrefixFreeDecode(B)
if messageType == MoreHops { // next hop
var ray [32]byte
copy(ray[:], dhKey[:])
b := digest.HashBlindingFactor(ray, sharedSecret)
alpha := group.ExpOn(dhKey, b)
gamma := B[securityParameter : securityParameter*2]
beta := B[securityParameter*2:]
// send to next node in the route
result.Alpha = alpha[:]
result.Beta = make([]byte, betaLen)
copy(result.Beta, beta)
result.Gamma = gamma
result.Delta = delta
result.NextHop = val
result.ProcessAction = MoreHops
return result, nil
} else if messageType == ExitNode { // process
zeros := bytes.Repeat([]byte{0}, securityParameter)
if bytes.Equal(delta[:securityParameter], zeros) {
innerType, val, rest := PrefixFreeDecode(delta[securityParameter:])
if innerType == ClientHop {
body, err := RemovePadding(rest)
if err != nil {
return nil, err
}
// deliver body to val
result.Delta = body
result.ClientID = val
result.ProcessAction = ExitNode
return result, nil
}
}
return nil, errors.New("invalid message special destination")
} else if messageType == ClientHop { // client
if len(rest) < securityParameter {
return nil, fmt.Errorf("malformed client hop message")
}
messageID := rest[:securityParameter]
result.ClientID = val
result.MessageID = messageID
result.Delta = delta
result.ProcessAction = ClientHop
return result, nil
}
return nil, fmt.Errorf("Invalid message type %d", messageType)
}