aboutsummaryrefslogtreecommitdiff
path: root/src/gnunet/crypto/gns.go
blob: 39eb8c5c981331eea811a69e1c043631099d859f (plain) (blame)
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// 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 crypto

import (
	"bytes"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/binary"
	"errors"
	"gnunet/enums"
	"gnunet/util"

	"github.com/bfix/gospel/data"
	"github.com/bfix/gospel/logger"
	"github.com/bfix/gospel/math"
	"golang.org/x/crypto/hkdf"
)

//======================================================================
// All zone-related cryptography in GNS is encapsulated in three
// distinct types: ZonePrivate, ZoneKey (public) and ZoneSignature.
// To enable crypto-agility, these types are implemented in a generic
// way - mostly as byte arrays holding the specific representation of a
// crypto implementation.
//
// Currently two key systems are implemented:
//   * PKEY: Ed25519 keys with private scalar and ECDSA signatures
//   * EDKEY: Ed25519 keys for EdDSA signatures (Ed25519 standard)
//
// It is easy to implement new crypto schemes as long as the following
// criteria are met:
//   * It is an asymmetric crypto scheme (with private and public key)
//   * It can encrypt data with a public key and decrypt it with the
//     corresponding private key. How that is done is completely up to
//     the specific implementation.
//   * It can sign data with the private key and verify it with the
//     corresponding public key.
//   * It can do key blinding (public and private) based on a 64 byte
//     byte array. How that is done is up to the specific implementation.
//
// The way to add new zone crypto implementation is as follows; as an
// example the RSA crypto scheme is outlined:
//
//   (1) Register/define a new GNS_TYPE_RSAKEY
//   (2) Add ZONE_RSAKEY and GNS_TYPE_RSAKEY to the "Zone types"
//       declarations in this file.
//   (3) Code the implementation in a file named `gns_rsakey.go`:
//       You have to implement three interfaces (ZonePrivateImpl,
//       ZoneKeyImpl and ZoneSigImpl) in three separate custom types.
//       Additionally an instantiation function (zero value) must be
//       defined for all three custom types (like 'NewRSAPrivate()'
//       taking no arguments and returning an empty new instance.
//   (4) In the 'init()' method of your source file, register the
//       implementation in the "Zone implementations" below with:
//           zoneImpl[ZONE_RSAKEY] = &ZoneImplementation{
//               NewPrivate: NewRSAPrivate,
//               PrivateSize: 256,
//               NewPublic: NewRSAPublic,
//               PublicSize: 270.
//               NewSignature: newRSASignature,
//               SignatureSize: 512,
//           }
//   Review a provided implementation (like `gns_edkey.go`) as an
//   example on how to create a custom GNS zone crypto.
//   (5) Add the zone type to the GNS block handler in file
//       `service/gns/block_handler.go`:
//           ;
//           enums.GNS_TYPE_RSAKEY:     NewZoneHandler,
//           ;
//
//======================================================================

//----------------------------------------------------------------------
// Implementation interfaces
//----------------------------------------------------------------------

// ZoneAbstractImpl is an abstract interface used in derived interfaces
type ZoneAbstractImpl interface {
	// Init the instance from given binary representation
	Init(data []byte) error

	// Bytes returns the binary representation (can be used with 'init()')
	Bytes() []byte
}

// ZoneKeyImpl defines the methods for a public zone key.
type ZoneKeyImpl interface {
	ZoneAbstractImpl

	// Derive a zone key from this zone key based on a big integer
	// (key blinding). Returns the derived key and the blinding value.
	Derive(h *math.Int) (ZoneKeyImpl, *math.Int, error)

	// BlockKey returns the key for block en-/decryption
	BlockKey(label string, expires util.AbsoluteTime) (skey []byte)

	// Encrypt binary data (of any size). Output can be larger than input
	Encrypt(data []byte, label string, expires util.AbsoluteTime) ([]byte, error)

	// Decrypt data (of any size). Output can be smaller than input
	Decrypt(data []byte, label string, expires util.AbsoluteTime) ([]byte, error)

	// Verify a signature for binary data
	Verify(data []byte, sig *ZoneSignature) (bool, error)
}

// ZonePrivateImpl defines the methods for a private zone key.
type ZonePrivateImpl interface {
	ZoneAbstractImpl

	// Derive a private key from this zone key based on a big integer
	// (key blinding). Returns the derived key and the blinding value.
	Derive(h *math.Int) (ZonePrivateImpl, *math.Int, error)

	// Sign binary data and return the signature
	Sign(data []byte) (*ZoneSignature, error)

	// Public returns the associated public key
	Public() ZoneKeyImpl
}

// ZoneSigImpl defines the methods for a signature object.
type ZoneSigImpl interface {
	ZoneAbstractImpl
}

//----------------------------------------------------------------------
// Zone types
//----------------------------------------------------------------------

//nolint:stylecheck // allow non-camel-case in constants
var (
	ZONE_PKEY  = uint32(enums.GNS_TYPE_PKEY)
	ZONE_EDKEY = uint32(enums.GNS_TYPE_EDKEY)
)

var (
	// register available zone types for BlockHandler
	ZoneTypes = []enums.GNSType{
		enums.GNS_TYPE_PKEY,
		enums.GNS_TYPE_EDKEY,
	}
)

//----------------------------------------------------------------------
// Zone implementations
//----------------------------------------------------------------------

// ZoneImplementation holds factory methods and size values for a
// specific crypto implementation (based on the associated zone type)
type ZoneImplementation struct {
	NewPrivate    func() ZonePrivateImpl
	PrivateSize   uint
	NewPublic     func() ZoneKeyImpl
	PublicSize    uint
	NewSignature  func() ZoneSigImpl
	SignatureSize uint
}

// keep a mapping of available implementations
var (
	zoneImpl = make(map[uint32]*ZoneImplementation)
)

// Error codes
var (
	ErrNoImplementation = errors.New("unknown zone implementation")
	ErrUnknownZoneType  = errors.New("unknown zone type")
)

// GetImplementation return the factory for a given zone type.
// If zje zone type is unregistered, nil is returned.
func GetImplementation(ztype uint32) *ZoneImplementation {
	if impl, ok := zoneImpl[ztype]; ok {
		return impl
	}
	return nil
}

//======================================================================
// Generic implementations:
//======================================================================

//----------------------------------------------------------------------
// Zone key (private)
//----------------------------------------------------------------------

// ZonePrivate represents the possible types of private zone keys (PKEY, EDKEY,...)
type ZonePrivate struct {
	ZoneKey

	impl ZonePrivateImpl // reference to implementation
}

// NewZonePrivate returns a new initialized ZonePrivate instance
func NewZonePrivate(ztype uint32, d []byte) (zp *ZonePrivate, err error) {
	// get factory for given zone type
	impl, ok := zoneImpl[ztype]
	if !ok {
		return nil, ErrNoImplementation
	}
	// assemble private zone key
	zp = &ZonePrivate{
		ZoneKey{
			ztype,
			nil,
			nil,
		},
		nil,
	}
	zp.impl = impl.NewPrivate()
	if err = zp.impl.Init(d); err != nil {
		return
	}
	zp.ZoneKey.KeyData = zp.impl.Public().Bytes()
	zp.ZoneKey.impl = impl.NewPublic()
	err = zp.ZoneKey.impl.Init(zp.ZoneKey.KeyData)
	return
}

// KeySize returns the number of bytes of a key representation.
// This method is used during serialization (Unmarshal).
func (zp *ZonePrivate) KeySize() uint {
	if impl, ok := zoneImpl[zp.Type]; ok {
		return impl.PrivateSize
	}
	return 0
}

// Derive key (key blinding)
func (zp *ZonePrivate) Derive(label, context string) (dzp *ZonePrivate, h *math.Int, err error) {
	// get factory for given zone type
	impl := zoneImpl[zp.Type]

	// calculate derived key
	h = deriveH(zp.impl.Bytes(), label, context)
	var derived ZonePrivateImpl
	if derived, h, err = zp.impl.Derive(h); err != nil {
		return
	}
	// assemble derived pivate key
	dzp = &ZonePrivate{
		ZoneKey{
			zp.Type,
			nil,
			nil,
		},
		derived,
	}
	zp.ZoneKey.KeyData = derived.Public().Bytes()
	zp.ZoneKey.impl = impl.NewPublic()
	err = zp.ZoneKey.impl.Init(zp.ZoneKey.KeyData)
	return
}

// ZoneSign data with a private key
func (zp *ZonePrivate) Sign(data []byte) (sig *ZoneSignature, err error) {
	return zp.impl.Sign(data)
}

// Public returns the associated public key
func (zp *ZonePrivate) Public() *ZoneKey {
	return &zp.ZoneKey
}

//----------------------------------------------------------------------
// Zone key (public)
//----------------------------------------------------------------------

// ZoneKey represents the possible types of zone keys (PKEY, EDKEY,...)
type ZoneKey struct {
	Type    uint32 `json:"type" order:"big"`
	KeyData []byte `json:"key" size:"(KeySize)"`

	impl ZoneKeyImpl // reference to implementation
}

// NewZoneKey returns a new initialized ZoneKey instance
func NewZoneKey(d []byte) (zk *ZoneKey, err error) {
	// read zone key from data
	zk = new(ZoneKey)
	if err = data.Unmarshal(zk, d); err != nil {
		return
	}
	// initialize implementation
	impl, ok := zoneImpl[zk.Type]
	if !ok {
		err = ErrUnknownZoneType
		return
	}
	zk.impl = impl.NewPublic()
	err = zk.impl.Init(zk.KeyData)
	return
}

// KeySize returns the number of bytes of a key representation.
// This method is used during serialization (Unmarshal).
func (zk *ZoneKey) KeySize() uint {
	if impl, ok := zoneImpl[zk.Type]; ok {
		return impl.PublicSize
	}
	return 0
}

// Derive key (key blinding)
func (zk *ZoneKey) Derive(label, context string) (dzk *ZoneKey, h *math.Int, err error) {
	h = deriveH(zk.KeyData, label, context)
	var derived ZoneKeyImpl
	if derived, h, err = zk.impl.Derive(h); err != nil {
		return
	}
	dzk = &ZoneKey{
		Type:    zk.Type,
		KeyData: derived.Bytes(),
		impl:    derived,
	}
	return
}

// BlockKey returns the key for block en-/decryption
func (zk *ZoneKey) BlockKey(label string, expires util.AbsoluteTime) (skey []byte) {
	return zk.impl.BlockKey(label, expires)
}

// Encrypt data
func (zk *ZoneKey) Encrypt(data []byte, label string, expire util.AbsoluteTime) ([]byte, error) {
	return zk.impl.Encrypt(data, label, expire)
}

// Decrypt data
func (zk *ZoneKey) Decrypt(data []byte, label string, expire util.AbsoluteTime) ([]byte, error) {
	return zk.impl.Decrypt(data, label, expire)
}

// Verify a zone signature
func (zk *ZoneKey) Verify(data []byte, zs *ZoneSignature) (ok bool, err error) {
	if err = zk.withImpl(); err != nil {
		return
	}
	return zk.impl.Verify(data, zs)
}

// ID returns the human-readable zone identifier.
func (zk *ZoneKey) ID() string {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, zk.Type)
	if err == nil {
		_, err = buf.Write(zk.KeyData)
	}
	if err != nil {
		logger.Printf(logger.ERROR, "[ZoneKey.ID] failed: %s", err.Error())
	}
	return util.EncodeBinaryToString(buf.Bytes())
}

// Bytes returns all bytes of a zone key
func (zk *ZoneKey) Bytes() []byte {
	data, _ := data.Marshal(zk)
	return data
}

// Equal checks if two zone keys are equal
func (zk *ZoneKey) Equal(k *ZoneKey) bool {
	return bytes.Equal(zk.KeyData, k.KeyData)
}

// withImpl ensure that an implementation reference is available
func (zk *ZoneKey) withImpl() (err error) {
	if zk.impl == nil {
		factory := zoneImpl[zk.Type]
		zk.impl = factory.NewPublic()
		err = zk.impl.Init(zk.KeyData)
	}
	return
}

//----------------------------------------------------------------------
// Zone signature
//----------------------------------------------------------------------

type ZoneSignature struct {
	ZoneKey
	Signature []byte `size:"(SigSize)"` // signature data

	impl ZoneSigImpl // reference to implementation
}

// NewZoneSignature returns a new initialized ZoneSignature instance
func NewZoneSignature(d []byte) (sig *ZoneSignature, err error) {
	// read signature
	sig = new(ZoneSignature)
	if err = data.Unmarshal(sig, d); err != nil {
		return
	}
	// initialize implementations
	impl, ok := zoneImpl[sig.Type]
	if !ok {
		err = ErrUnknownZoneType
		return
	}
	// set signature implementation
	zs := impl.NewSignature()
	if err = zs.Init(sig.Signature); err != nil {
		return
	}
	sig.impl = zs
	// set public key implementation
	zk := impl.NewPublic()
	if err = zk.Init(sig.KeyData); err != nil {
		return
	}
	sig.ZoneKey.impl = zk
	return
}

// SigSize returns the number of bytes of a signature that can be
// verified with a given zone key. This method is used during
// serialization (Unmarshal).
func (zs *ZoneSignature) SigSize() uint {
	if impl, ok := zoneImpl[zs.Type]; ok {
		return impl.SignatureSize
	}
	return 0
}

// Key returns the associated zone key object
func (zs *ZoneSignature) Key() *ZoneKey {
	return &zs.ZoneKey
}

// Verify a signature
func (zs *ZoneSignature) Verify(data []byte) (bool, error) {
	return zs.ZoneKey.Verify(data, zs)
}

//----------------------------------------------------------------------
// Helper functions
//----------------------------------------------------------------------

// deriveH derives an integer 'h' from the arguments.
func deriveH(key []byte, label, context string) *math.Int {
	prk := hkdf.Extract(sha512.New, key, []byte("key-derivation"))
	data := append([]byte(label), []byte(context)...)
	rdr := hkdf.Expand(sha256.New, prk, data)
	b := make([]byte, 64)
	if _, err := rdr.Read(b); err != nil {
		logger.Printf(logger.ERROR, "[deriveH] failed: %s", err.Error())
	}
	return math.NewIntFromBytes(b)
}