-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvalidator_pow.go
More file actions
171 lines (134 loc) · 4.33 KB
/
validator_pow.go
File metadata and controls
171 lines (134 loc) · 4.33 KB
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
package berghain
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"net/http"
"sync"
"github.com/dropmorepackets/haproxy-go/pkg/buffer"
)
var sha256Pool = sync.Pool{
New: func() any {
return NewZeroHasher(hashAlgo())
},
}
func acquireSHA256() hash.Hash {
return sha256Pool.Get().(hash.Hash)
}
func releaseSHA256(h hash.Hash) {
h.Reset()
sha256Pool.Put(h)
}
type powValidator struct {
}
const (
validatorPOWRandom = "0000000000000000"
validatorPOWHash = "0000000000000000000000000000000000000000000000000000000000000000"
validatorPOWMinSolutionLength = len(validatorPOWRandom + "-" + validatorPOWHash + "-0")
)
var validatorPOWChallengeTemplate = mustJSONEncodeString(struct {
Countdown int `json:"c"`
Type int `json:"t"`
Random string `json:"r"`
Hash string `json:"s"`
}{
// Only strings have to be set, as the default is zero for ints.
// We do set the Type here because it is static anyway...
Type: 1,
Random: "0000000000000000",
Hash: "0000000000000000000000000000000000000000000000000000000000000000",
})
// This prevents invalid template strings by validatoring them on start
var _ = func() bool {
h := hashAlgo()
if len(validatorPOWHash) != hex.EncodedLen(h.Size()) {
panic("invalid pow hash length")
}
return true
}()
func (powValidator) onNew(b *Berghain, req *ValidatorRequest, resp *ValidatorResponse) error {
h := b.acquireHMAC()
defer b.releaseHMAC(h)
lc := b.LevelConfig(req.Identifier.Level)
copy(resp.Body.WriteBytes(), validatorPOWChallengeTemplate)
resp.Body.AdvanceW(len(`{"c":`))
// the following conversion is faster than sprintf but also way uglier, I am sorry.
// 48 is the ASCII code for '0', adding lc.Countdown will give us the single correct digit.
copy(resp.Body.WriteNBytes(1), []byte{byte(48 + lc.Countdown)})
resp.Body.AdvanceW(len(`,"t":1,"r":"`))
timestampArea := resp.Body.WriteNBytes(len(validatorPOWRandom))
resp.Body.AdvanceW(len(`","s":"`))
hexArea := resp.Body.WriteNBytes(hex.EncodedLen(h.Size()))
resp.Body.AdvanceW(len(`"}`))
// we use the response body temporarily as a buffer
expireAt := tc.Now().Add(lc.Duration)
timestampBuf := resp.Body.WriteNBytes(8)
resp.Body.AdvanceW(-8) // this should be illegal
binary.LittleEndian.PutUint64(timestampBuf, uint64(expireAt.Unix()))
hex.Encode(timestampArea, timestampBuf)
// Write identifier to hash to ensure uniqueness
req.Identifier.WriteTo(h)
h.Write(timestampArea)
hex.Encode(hexArea, h.Sum(nil))
return nil
}
func (powValidator) isValid(b *Berghain, req *ValidatorRequest, resp *ValidatorResponse) error {
// req.Body should be at least validatorPOWMinSolutionLength
if len(req.Body) <= validatorPOWMinSolutionLength {
// invalid solution data
return ErrInvalidLength
}
body := buffer.NewSliceBufferWithSlice(req.Body)
timestampArea := body.ReadNBytes(len(validatorPOWRandom))
body.AdvanceR(1) // Skip padding character
sumArea := body.ReadNBytes(len(validatorPOWHash))
body.AdvanceR(1) // Skip padding character
solArea := body.ReadBytes()
h := b.acquireHMAC()
defer b.releaseHMAC(h)
// Write identifier to hash to ensure uniqueness
req.Identifier.WriteTo(h)
h.Write(timestampArea)
// we use the response body temporarily as a buffer
defer resp.Body.Reset()
ourSum := resp.Body.WriteNBytes(hex.EncodedLen(h.Size()))
hex.Encode(ourSum, h.Sum(nil))
if !bytes.Equal(ourSum, sumArea) {
// invalid hash in solution
return ErrInvalidHMAC
}
resp.Body.Reset()
expirArea := resp.Body.WriteNBytes(hex.DecodedLen(len(validatorPOWRandom)))
if _, err := hex.Decode(expirArea, timestampArea); err != nil {
return err
}
// Untrusted input is decoded and compared!
if uint64(tc.Now().Unix()) > binary.LittleEndian.Uint64(expirArea) {
return ErrExpired
}
sha := acquireSHA256()
defer releaseSHA256(sha)
sha.Write(timestampArea)
sha.Write(solArea)
sum := sha.Sum(nil)
if !bytes.HasPrefix(sum, []byte{0x00, 0x00}) {
return errInvalidSolution
}
return nil
}
var errInvalidSolution = fmt.Errorf("invalid solution")
func validatorPOW(b *Berghain, req *ValidatorRequest, resp *ValidatorResponse) error {
var p powValidator
switch req.Method {
case http.MethodPost:
if err := p.isValid(b, req, resp); err != nil {
return err
}
return req.Identifier.ToCookie(b, resp.Token)
case http.MethodGet:
return p.onNew(b, req, resp)
}
return errInvalidMethod
}