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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
|
// This file is part of gnunet-go, a GNUnet-implementation in Golang.
// Copyright (C) 2019-2022 Bernd Fix >Y<
//
// gnunet-go is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// gnunet-go is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later
package main
import (
"context"
"encoding/base64"
"flag"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"gnunet/crypto"
"gnunet/service/revocation"
"gnunet/util"
"github.com/bfix/gospel/data"
)
//----------------------------------------------------------------------
// Data structure used to calculate a valid revocation for a given
// zone key.
//----------------------------------------------------------------------
// State of RevData calculation
const (
StateNew = iota // start new PoW calculation
StateCont // continue PoW calculation
StateDone // PoW calculation done
StateSigned // revocation data signed
)
// RevData is the storage layout for persistent data used by this program.
// Data is read from and written to a file
type RevData struct {
Rd *revocation.RevDataCalc `` // Revocation data
T util.RelativeTime `` // time spend in calculations
Last uint64 `order:"big"` // last value used for PoW test
Numbits uint8 `` // number of leading zero-bits (difficulty)
State uint8 `` // processing state
}
// ReadRevData restores revocation data from perstistent storage. If no
// stored data is found, a new revocation data structure is returned.
func ReadRevData(filename string, bits int, zk *crypto.ZoneKey) (rd *RevData, err error) {
// create new initialized revocation instance with no PoWs.
rd = &RevData{
Rd: revocation.NewRevDataCalc(zk),
Numbits: uint8(bits),
T: util.NewRelativeTime(0),
State: StateNew,
}
// read revocation object from file. If the file does not exist, a new
// calculation is started; otherwise the old calculation will continue.
var file *os.File
if file, err = os.Open(filename); err != nil {
return
}
// read existing file
dataBuf := make([]byte, rd.size())
var n int
if n, err = file.Read(dataBuf); err != nil {
err = fmt.Errorf("error reading file: " + err.Error())
return
}
if n != len(dataBuf) {
err = fmt.Errorf("file size mismatch")
return
}
if err = data.Unmarshal(&rd, dataBuf); err != nil {
err = fmt.Errorf("file corrupted: " + err.Error())
return
}
if !zk.Equal(&rd.Rd.RevData.ZoneKeySig.ZoneKey) {
err = fmt.Errorf("zone key mismatch")
return
}
if err = file.Close(); err != nil {
err = fmt.Errorf("error closing file: " + err.Error())
}
return
}
// Write revocation data to file
func (r *RevData) Write(filename string) (err error) {
var file *os.File
if file, err = os.Create(filename); err != nil {
return fmt.Errorf("can't write to output file: " + err.Error())
}
var buf []byte
if buf, err = data.Marshal(r); err != nil {
return fmt.Errorf("internal error: " + err.Error())
}
if len(buf) != r.size() {
return fmt.Errorf("internal error: Buffer mismatch %d != %d", len(buf), r.size())
}
var n int
if n, err = file.Write(buf); err != nil {
return fmt.Errorf("can't write to output file: " + err.Error())
}
if n != len(buf) {
return fmt.Errorf("can't write data to output file")
}
if err = file.Close(); err != nil {
return fmt.Errorf("error closing file: " + err.Error())
}
return
}
// size of the RevData instance in bytes.
func (r *RevData) size() int {
return 18 + r.Rd.Size()
}
// revoke-zonekey generates a revocation message in a multi-step/multi-state
// process run stand-alone from other GNUnet services:
//
// (1) Generate the desired PoWs for the public zone key:
// This process can be started, stopped and resumed, so the long
// calculation time (usually days or even weeks) can be interrupted if
// desired. For security reasons you should only pass the "-z" argument to
// this step but not the "-k" argument (private key) as it is not required
// to calculate the PoWs.
//
//
// (2) A fully generated PoW set can be signed with the private key to create
// the final revocation data to be send out. This requires to pass the "-k"
// and "-z" argument.
//
// The two steps can be run (sequentially) on separate machines; step one requires
// computing power nd memory and step two requires a trusted environment.
func main() {
log.Println("*** Compute revocation data for a zone key")
log.Println("*** Copyright (c) 2020-2022, Bernd Fix >Y<")
log.Println("*** This is free software distributed under the Affero GPL v3.")
//------------------------------------------------------------------
// handle command line arguments
//------------------------------------------------------------------
var (
verbose bool // be verbose with messages
bits int // number of leading zero-bit requested
zonekey string // zonekey to be revoked
prvkey string // private zonekey (base64-encoded key data)
testing bool // test mode (no minimum difficulty)
filename string // name of file for persistence
)
minDiff := revocation.MinDifficulty
flag.IntVar(&bits, "b", minDiff+1, "Number of leading zero bits")
flag.StringVar(&zonekey, "z", "", "Zone key to be revoked (zone ID)")
flag.StringVar(&prvkey, "k", "", "Private zone key (base54-encoded)")
flag.StringVar(&filename, "f", "", "Name of file to store revocation")
flag.BoolVar(&verbose, "v", false, "verbose output")
flag.BoolVar(&testing, "t", false, "test-mode only")
flag.Parse()
// check arguments (difficulty, zonekey and filename)
if bits < minDiff {
if testing {
log.Printf("WARNING: difficulty is less than %d!", minDiff)
} else {
log.Printf("INFO: difficulty set to %d (required minimum)", minDiff)
bits = minDiff
}
}
if len(filename) == 0 {
log.Fatal("Missing '-f' argument (filename for revocation data)")
}
//------------------------------------------------------------------
// Handle zone keys.
//------------------------------------------------------------------
var (
keyData []byte // binary key data
zk *crypto.ZoneKey // GNUnet zone key
sk *crypto.ZonePrivate // GNUnet private zone key
err error
)
// reconstruct public key
if keyData, err = util.DecodeStringToBinary(zonekey, 32); err != nil {
log.Fatal("Invalid zonekey encoding: " + err.Error())
}
if zk, err = crypto.NewZoneKey(keyData); err != nil {
log.Fatal("Invalid zonekey format: " + err.Error())
}
// reconstruct private key (optional)
if len(prvkey) > 0 {
if keyData, err = base64.StdEncoding.DecodeString(prvkey); err != nil {
log.Fatal("Invalid private zonekey encoding: " + err.Error())
}
if sk, err = crypto.NewZonePrivate(zk.Type, keyData); err != nil {
log.Fatal("Invalid zonekey format: " + err.Error())
}
// verify consistency
if !zk.Equal(sk.Public()) {
log.Fatal("Public and private zone keys don't match.")
}
}
//------------------------------------------------------------------
// Read revocation data from file to continue calculation or to sign
// the revocation. If no file exists, a new (empty) instance is
// returned.
//------------------------------------------------------------------
rd, err := ReadRevData(filename, bits, zk)
// handle revocation data state
switch rd.State {
case StateNew:
log.Println("Starting new revocation calculation...")
rd.State = StateCont
case StateCont:
log.Printf("Revocation calculation started at %s\n", rd.Rd.Timestamp.String())
log.Printf("Time spent on calculation: %s\n", rd.T.String())
log.Printf("Last tested PoW value: %d\n", rd.Last)
log.Println("Continuing...")
case StateDone:
// calculation complete: sign with private key
if sk == nil {
log.Fatal("Need to sign revocation: private key is missing.")
}
log.Println("Signing revocation with private key")
if err = rd.Rd.Sign(sk); err != nil {
log.Fatal("Failed to sign revocation: " + err.Error())
}
// write final revocation
rd.State = StateSigned
if err = rd.Write(filename); err != nil {
log.Fatal("Failed to write revocation: " + err.Error())
}
log.Println("Revocation complete and ready for (later) use.")
return
}
// Continue (or start) calculation
log.Println("Press ^C to abort...")
log.Printf("Difficulty: %d\n", bits)
ctx, cancelFcn := context.WithCancel(context.Background())
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
defer wg.Done()
// show progress messages
cb := func(average float64, last uint64) {
log.Printf("Improved PoW: %.2f average zero bits, %d steps\n", average, last)
}
// calculate revocation data until the required difficulty is met
// or the process is terminated by the user (by pressing ^C).
startTime := util.AbsoluteTimeNow()
average, last := rd.Rd.Compute(ctx, bits, rd.Last, cb)
// check achieved diffiulty (average)
if average < float64(bits) {
// The calculation was interrupted; we still need to compute
// more and better PoWs...
log.Printf("Incomplete revocation: Only %f zero bits on average!\n", average)
rd.State = StateCont
} else {
// we have reached the required PoW difficulty
rd.State = StateDone
// check if we have a valid revocation.
log.Println("Revocation calculation complete:")
diff, rc := rd.Rd.Verify(false)
switch {
case rc == -1:
log.Println(" Missing/invalid signature")
case rc == -2:
log.Println(" Expired revocation")
case rc == -3:
log.Println(" Wrong PoW sequence order")
case diff < float64(revocation.MinAvgDifficulty):
log.Println(" Difficulty to small")
default:
log.Printf(" Difficulty is %.2f\n", diff)
}
}
// update elapsed time
rd.T.Add(startTime.Elapsed())
rd.Last = last
log.Println("Writing revocation data to file...")
if err = rd.Write(filename); err != nil {
log.Fatal("Can't write to file: " + err.Error())
}
}()
go func() {
// handle OS signals
sigCh := make(chan os.Signal, 5)
signal.Notify(sigCh)
loop:
for sig := range sigCh {
// handle OS signals
switch sig {
case syscall.SIGKILL, syscall.SIGINT, syscall.SIGTERM:
log.Printf("Terminating (on signal '%s')\n", sig)
cancelFcn()
break loop
case syscall.SIGHUP:
log.Println("SIGHUP")
case syscall.SIGURG:
// TODO: https://github.com/golang/go/issues/37942
default:
log.Println("Unhandled signal: " + sig.String())
}
}
}()
wg.Wait()
}
|