2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
|
|
|
# Copyright (c) 2022 Status Research & Development GmbH
|
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
# at your option.
|
|
|
|
# This file may not be copied, modified, or distributed except according to
|
|
|
|
# those terms.
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2022-08-03 11:33:19 +00:00
|
|
|
when (NimMajor, NimMinor) < (1, 4):
|
|
|
|
{.push raises: [Defect].}
|
|
|
|
else:
|
|
|
|
{.push raises: [].}
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2020-09-06 08:31:47 +00:00
|
|
|
import std/[oids, strformat]
|
2022-06-16 08:08:52 +00:00
|
|
|
import bearssl/rand
|
|
|
|
import chronos, chronicles, stew/endians2
|
2020-07-07 11:14:11 +00:00
|
|
|
import nimcrypto/[hmac, sha2, sha, hash, rijndael, twofish, bcmode]
|
2019-10-29 18:51:48 +00:00
|
|
|
import secure,
|
2020-06-19 17:29:43 +00:00
|
|
|
../../stream/connection,
|
2019-12-07 16:36:39 +00:00
|
|
|
../../peerinfo,
|
2019-10-29 18:51:48 +00:00
|
|
|
../../crypto/crypto,
|
2019-09-13 17:20:37 +00:00
|
|
|
../../crypto/ecnist,
|
2020-07-01 06:25:09 +00:00
|
|
|
../../peerid,
|
2021-05-21 16:27:01 +00:00
|
|
|
../../utility,
|
|
|
|
../../errors
|
2020-06-19 17:29:43 +00:00
|
|
|
|
2019-09-13 17:20:37 +00:00
|
|
|
export hmac, sha2, sha, hash, rijndael, bcmode
|
2019-09-06 06:51:46 +00:00
|
|
|
|
2019-09-10 02:13:15 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p secio"
|
2019-09-10 02:13:15 +00:00
|
|
|
|
|
|
|
const
|
|
|
|
SecioCodec* = "/secio/1.0.0"
|
|
|
|
SecioMaxMessageSize = 8 * 1024 * 1024 ## 8mb
|
2019-09-13 17:20:37 +00:00
|
|
|
SecioMaxMacSize = sha512.sizeDigest
|
2019-09-10 02:13:15 +00:00
|
|
|
SecioNonceSize = 16
|
|
|
|
SecioExchanges = "P-256,P-384,P-521"
|
2019-09-13 17:20:37 +00:00
|
|
|
SecioCiphers = "TwofishCTR,AES-256,AES-128"
|
|
|
|
SecioHashes = "SHA256,SHA512"
|
2019-09-06 06:51:46 +00:00
|
|
|
|
|
|
|
type
|
2021-06-07 07:32:08 +00:00
|
|
|
Secio* = ref object of Secure
|
2022-06-16 08:08:52 +00:00
|
|
|
rng: ref HmacDrbgContext
|
2019-09-13 17:20:37 +00:00
|
|
|
localPrivateKey: PrivateKey
|
2019-09-10 02:13:15 +00:00
|
|
|
localPublicKey: PublicKey
|
2019-09-13 17:20:37 +00:00
|
|
|
remotePublicKey: PublicKey
|
|
|
|
|
|
|
|
SecureCipherType {.pure.} = enum
|
|
|
|
Aes128, Aes256, Twofish
|
|
|
|
|
|
|
|
SecureMacType {.pure.} = enum
|
|
|
|
Sha1, Sha256, Sha512
|
|
|
|
|
|
|
|
SecureCipher = object
|
|
|
|
case kind: SecureCipherType
|
|
|
|
of SecureCipherType.Aes128:
|
|
|
|
ctxaes128: CTR[aes128]
|
|
|
|
of SecureCipherType.Aes256:
|
|
|
|
ctxaes256: CTR[aes256]
|
|
|
|
of SecureCipherType.Twofish:
|
|
|
|
ctxtwofish256: CTR[twofish256]
|
|
|
|
|
|
|
|
SecureMac = object
|
|
|
|
case kind: SecureMacType
|
|
|
|
of SecureMacType.Sha256:
|
|
|
|
ctxsha256: HMAC[sha256]
|
|
|
|
of SecureMacType.Sha512:
|
|
|
|
ctxsha512: HMAC[sha512]
|
|
|
|
of SecureMacType.Sha1:
|
|
|
|
ctxsha1: HMAC[sha1]
|
|
|
|
|
2020-02-25 05:06:57 +00:00
|
|
|
SecioConn = ref object of SecureConn
|
2019-09-13 17:20:37 +00:00
|
|
|
writerMac: SecureMac
|
|
|
|
readerMac: SecureMac
|
|
|
|
writerCoder: SecureCipher
|
|
|
|
readerCoder: SecureCipher
|
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
SecioError* = object of LPError
|
2019-12-13 15:25:07 +00:00
|
|
|
|
2020-09-06 08:31:47 +00:00
|
|
|
func shortLog*(conn: SecioConn): auto =
|
2021-05-21 16:27:01 +00:00
|
|
|
try:
|
|
|
|
if conn.isNil: "SecioConn(nil)"
|
2021-09-08 09:07:46 +00:00
|
|
|
else: &"{shortLog(conn.peerId)}:{conn.oid}"
|
2021-05-21 16:27:01 +00:00
|
|
|
except ValueError as exc:
|
|
|
|
raise newException(Defect, exc.msg)
|
|
|
|
|
2020-09-06 08:31:47 +00:00
|
|
|
chronicles.formatIt(SecioConn): shortLog(it)
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc init(mac: var SecureMac, hash: string, key: openArray[byte]) =
|
2019-09-13 17:20:37 +00:00
|
|
|
if hash == "SHA256":
|
|
|
|
mac = SecureMac(kind: SecureMacType.Sha256)
|
|
|
|
mac.ctxsha256.init(key)
|
|
|
|
elif hash == "SHA512":
|
|
|
|
mac = SecureMac(kind: SecureMacType.Sha512)
|
|
|
|
mac.ctxsha512.init(key)
|
|
|
|
elif hash == "SHA1":
|
|
|
|
mac = SecureMac(kind: SecureMacType.Sha1)
|
|
|
|
mac.ctxsha1.init(key)
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc update(mac: var SecureMac, data: openArray[byte]) =
|
2019-09-13 17:20:37 +00:00
|
|
|
case mac.kind
|
|
|
|
of SecureMacType.Sha256:
|
|
|
|
update(mac.ctxsha256, data)
|
|
|
|
of SecureMacType.Sha512:
|
|
|
|
update(mac.ctxsha512, data)
|
|
|
|
of SecureMacType.Sha1:
|
|
|
|
update(mac.ctxsha1, data)
|
|
|
|
|
|
|
|
proc sizeDigest(mac: SecureMac): int {.inline.} =
|
|
|
|
case mac.kind
|
|
|
|
of SecureMacType.Sha256:
|
|
|
|
result = int(mac.ctxsha256.sizeDigest())
|
|
|
|
of SecureMacType.Sha512:
|
|
|
|
result = int(mac.ctxsha512.sizeDigest())
|
|
|
|
of SecureMacType.Sha1:
|
|
|
|
result = int(mac.ctxsha1.sizeDigest())
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc finish(mac: var SecureMac, data: var openArray[byte]) =
|
2019-09-13 17:20:37 +00:00
|
|
|
case mac.kind
|
|
|
|
of SecureMacType.Sha256:
|
|
|
|
discard finish(mac.ctxsha256, data)
|
|
|
|
of SecureMacType.Sha512:
|
|
|
|
discard finish(mac.ctxsha512, data)
|
|
|
|
of SecureMacType.Sha1:
|
|
|
|
discard finish(mac.ctxsha1, data)
|
|
|
|
|
|
|
|
proc reset(mac: var SecureMac) =
|
|
|
|
case mac.kind
|
|
|
|
of SecureMacType.Sha256:
|
|
|
|
reset(mac.ctxsha256)
|
|
|
|
of SecureMacType.Sha512:
|
|
|
|
reset(mac.ctxsha512)
|
|
|
|
of SecureMacType.Sha1:
|
|
|
|
reset(mac.ctxsha1)
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc init(sc: var SecureCipher, cipher: string, key: openArray[byte],
|
|
|
|
iv: openArray[byte]) {.inline.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
if cipher == "AES-128":
|
|
|
|
sc = SecureCipher(kind: SecureCipherType.Aes128)
|
|
|
|
sc.ctxaes128.init(key, iv)
|
|
|
|
elif cipher == "AES-256":
|
|
|
|
sc = SecureCipher(kind: SecureCipherType.Aes256)
|
|
|
|
sc.ctxaes256.init(key, iv)
|
|
|
|
elif cipher == "TwofishCTR":
|
|
|
|
sc = SecureCipher(kind: SecureCipherType.Twofish)
|
|
|
|
sc.ctxtwofish256.init(key, iv)
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc encrypt(cipher: var SecureCipher, input: openArray[byte],
|
|
|
|
output: var openArray[byte]) {.inline.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
case cipher.kind
|
|
|
|
of SecureCipherType.Aes128:
|
|
|
|
cipher.ctxaes128.encrypt(input, output)
|
|
|
|
of SecureCipherType.Aes256:
|
|
|
|
cipher.ctxaes256.encrypt(input, output)
|
|
|
|
of SecureCipherType.Twofish:
|
|
|
|
cipher.ctxtwofish256.encrypt(input, output)
|
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc decrypt(cipher: var SecureCipher, input: openArray[byte],
|
|
|
|
output: var openArray[byte]) {.inline.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
case cipher.kind
|
|
|
|
of SecureCipherType.Aes128:
|
|
|
|
cipher.ctxaes128.decrypt(input, output)
|
|
|
|
of SecureCipherType.Aes256:
|
|
|
|
cipher.ctxaes256.decrypt(input, output)
|
|
|
|
of SecureCipherType.Twofish:
|
|
|
|
cipher.ctxtwofish256.decrypt(input, output)
|
|
|
|
|
2020-02-25 05:06:57 +00:00
|
|
|
proc macCheckAndDecode(sconn: SecioConn, data: var seq[byte]): bool =
|
2019-09-13 17:20:37 +00:00
|
|
|
## This procedure checks MAC of recieved message ``data`` and if message is
|
|
|
|
## authenticated, then decrypt message.
|
|
|
|
##
|
|
|
|
## Procedure returns ``false`` if message is too short or MAC verification
|
|
|
|
## failed.
|
|
|
|
var macData: array[SecioMaxMacSize, byte]
|
|
|
|
let macsize = sconn.readerMac.sizeDigest()
|
|
|
|
if len(data) < macsize:
|
|
|
|
trace "Message is shorter then MAC size", message_length = len(data),
|
|
|
|
mac_size = macsize
|
|
|
|
return false
|
|
|
|
let mark = len(data) - macsize
|
|
|
|
sconn.readerMac.update(data.toOpenArray(0, mark - 1))
|
|
|
|
sconn.readerMac.finish(macData)
|
|
|
|
sconn.readerMac.reset()
|
|
|
|
if not equalMem(addr data[mark], addr macData[0], macsize):
|
|
|
|
trace "Invalid MAC",
|
|
|
|
calculated = toHex(macData.toOpenArray(0, macsize - 1)),
|
2020-05-18 05:25:55 +00:00
|
|
|
stored = toHex(data.toOpenArray(mark, data.high))
|
2019-09-13 17:20:37 +00:00
|
|
|
return false
|
|
|
|
|
|
|
|
sconn.readerCoder.decrypt(data.toOpenArray(0, mark - 1),
|
|
|
|
data.toOpenArray(0, mark - 1))
|
|
|
|
data.setLen(mark)
|
|
|
|
result = true
|
|
|
|
|
2020-05-07 20:37:46 +00:00
|
|
|
proc readRawMessage(conn: Connection): Future[seq[byte]] {.async.} =
|
|
|
|
while true: # Discard 0-length payloads
|
|
|
|
var lengthBuf: array[4, byte]
|
2020-06-19 17:29:43 +00:00
|
|
|
await conn.readExactly(addr lengthBuf[0], lengthBuf.len)
|
2020-05-07 20:37:46 +00:00
|
|
|
let length = uint32.fromBytesBE(lengthBuf)
|
|
|
|
|
|
|
|
trace "Recieved message header", header = lengthBuf.shortLog, length = length
|
|
|
|
|
|
|
|
if length > SecioMaxMessageSize: # Verify length before casting!
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Received size of message exceed limits", conn, length = length
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Message exceeds maximum length")
|
|
|
|
|
|
|
|
if length > 0:
|
|
|
|
var buf = newSeq[byte](int(length))
|
2020-06-19 17:29:43 +00:00
|
|
|
await conn.readExactly(addr buf[0], buf.len)
|
2020-05-07 20:37:46 +00:00
|
|
|
trace "Received message body",
|
2020-09-06 08:31:47 +00:00
|
|
|
conn, length = buf.len, buff = buf.shortLog
|
2020-05-07 20:37:46 +00:00
|
|
|
return buf
|
|
|
|
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Discarding 0-length payload", conn
|
2020-05-07 20:37:46 +00:00
|
|
|
|
|
|
|
method readMessage*(sconn: SecioConn): Future[seq[byte]] {.async.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
## Read message from channel secure connection ``sconn``.
|
2020-04-14 13:21:16 +00:00
|
|
|
when chronicles.enabledLogLevel == LogLevel.TRACE:
|
|
|
|
logScope:
|
|
|
|
stream_oid = $sconn.stream.oid
|
2020-06-19 17:29:43 +00:00
|
|
|
var buf = await sconn.stream.readRawMessage()
|
2020-05-07 20:37:46 +00:00
|
|
|
if sconn.macCheckAndDecode(buf):
|
|
|
|
result = buf
|
|
|
|
else:
|
|
|
|
trace "Message MAC verification failed", buf = buf.shortLog
|
|
|
|
raise (ref SecioError)(msg: "message failed MAC verification")
|
|
|
|
|
|
|
|
method write*(sconn: SecioConn, message: seq[byte]) {.async.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
## Write message ``message`` to secure connection ``sconn``.
|
2020-05-07 20:37:46 +00:00
|
|
|
if message.len == 0:
|
|
|
|
return
|
|
|
|
|
2020-05-21 15:01:36 +00:00
|
|
|
var
|
|
|
|
left = message.len
|
|
|
|
offset = 0
|
|
|
|
while left > 0:
|
|
|
|
let
|
|
|
|
chunkSize = if left > SecioMaxMessageSize - 64: SecioMaxMessageSize - 64 else: left
|
|
|
|
macsize = sconn.writerMac.sizeDigest()
|
|
|
|
length = chunkSize + macsize
|
|
|
|
|
|
|
|
var msg = newSeq[byte](chunkSize + 4 + macsize)
|
|
|
|
msg[0..<4] = uint32(length).toBytesBE()
|
|
|
|
|
|
|
|
sconn.writerCoder.encrypt(message.toOpenArray(offset, offset + chunkSize - 1),
|
|
|
|
msg.toOpenArray(4, 4 + chunkSize - 1))
|
|
|
|
left = left - chunkSize
|
|
|
|
offset = offset + chunkSize
|
|
|
|
let mo = 4 + chunkSize
|
|
|
|
sconn.writerMac.update(msg.toOpenArray(4, 4 + chunkSize - 1))
|
|
|
|
sconn.writerMac.finish(msg.toOpenArray(mo, mo + macsize - 1))
|
|
|
|
sconn.writerMac.reset()
|
|
|
|
|
|
|
|
trace "Writing message", message = msg.shortLog, left, offset
|
|
|
|
await sconn.stream.write(msg)
|
2020-08-15 05:36:15 +00:00
|
|
|
sconn.activity = true
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2020-02-25 05:06:57 +00:00
|
|
|
proc newSecioConn(conn: Connection,
|
|
|
|
hash: string,
|
|
|
|
cipher: string,
|
|
|
|
secrets: Secret,
|
|
|
|
order: int,
|
2021-05-21 16:27:01 +00:00
|
|
|
remotePubKey: PublicKey): SecioConn
|
2021-05-22 18:27:30 +00:00
|
|
|
{.raises: [Defect, LPError].} =
|
2020-06-19 17:29:43 +00:00
|
|
|
## Create new secure stream/lpstream, using specified hash algorithm ``hash``,
|
2019-09-13 17:20:37 +00:00
|
|
|
## cipher algorithm ``cipher``, stretched keys ``secrets`` and order
|
|
|
|
## ``order``.
|
2020-08-06 07:29:27 +00:00
|
|
|
|
2021-10-25 08:26:32 +00:00
|
|
|
result = SecioConn.new(conn, conn.peerId, conn.observedAddr)
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-09-13 17:20:37 +00:00
|
|
|
let i0 = if order < 0: 1 else: 0
|
|
|
|
let i1 = if order < 0: 0 else: 1
|
|
|
|
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "Writer credentials", mackey = secrets.macOpenArray(i0).shortLog,
|
|
|
|
enckey = secrets.keyOpenArray(i0).shortLog,
|
|
|
|
iv = secrets.ivOpenArray(i0).shortLog
|
|
|
|
trace "Reader credentials", mackey = secrets.macOpenArray(i1).shortLog,
|
|
|
|
enckey = secrets.keyOpenArray(i1).shortLog,
|
|
|
|
iv = secrets.ivOpenArray(i1).shortLog
|
2019-09-13 17:20:37 +00:00
|
|
|
result.writerMac.init(hash, secrets.macOpenArray(i0))
|
|
|
|
result.readerMac.init(hash, secrets.macOpenArray(i1))
|
|
|
|
result.writerCoder.init(cipher, secrets.keyOpenArray(i0),
|
|
|
|
secrets.ivOpenArray(i0))
|
|
|
|
result.readerCoder.init(cipher, secrets.keyOpenArray(i1),
|
|
|
|
secrets.ivOpenArray(i1))
|
2019-09-10 02:13:15 +00:00
|
|
|
|
|
|
|
proc transactMessage(conn: Connection,
|
|
|
|
msg: seq[byte]): Future[seq[byte]] {.async.} =
|
2020-05-07 20:37:46 +00:00
|
|
|
trace "Sending message", message = msg.shortLog, length = len(msg)
|
|
|
|
await conn.write(msg)
|
|
|
|
return await conn.readRawMessage()
|
2019-09-10 02:13:15 +00:00
|
|
|
|
2022-09-05 12:31:14 +00:00
|
|
|
method handshake*(s: Secio, conn: Connection, initiator: bool, peerId: Opt[PeerId]): Future[SecureConn] {.async.} =
|
2019-09-13 17:20:37 +00:00
|
|
|
var
|
|
|
|
localNonce: array[SecioNonceSize, byte]
|
|
|
|
remoteNonce: seq[byte]
|
|
|
|
remoteBytesPubkey: seq[byte]
|
|
|
|
remoteEBytesPubkey: seq[byte]
|
|
|
|
remoteEBytesSig: seq[byte]
|
|
|
|
remotePubkey: PublicKey
|
2020-07-21 20:10:21 +00:00
|
|
|
remoteEPubkey: ecnist.EcPublicKey
|
2019-09-13 17:20:37 +00:00
|
|
|
remoteESignature: Signature
|
|
|
|
remoteExchanges: string
|
|
|
|
remoteCiphers: string
|
|
|
|
remoteHashes: string
|
2021-12-16 10:05:20 +00:00
|
|
|
remotePeerId: PeerId
|
|
|
|
localPeerId: PeerId
|
2020-05-18 05:25:55 +00:00
|
|
|
localBytesPubkey = s.localPublicKey.getBytes().tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2022-06-16 08:08:52 +00:00
|
|
|
hmacDrbgGenerate(s.rng[], localNonce)
|
2019-09-06 06:51:46 +00:00
|
|
|
|
2019-12-10 20:50:35 +00:00
|
|
|
var request = createProposal(localNonce,
|
|
|
|
localBytesPubkey,
|
|
|
|
SecioExchanges,
|
|
|
|
SecioCiphers,
|
|
|
|
SecioHashes)
|
2019-09-10 02:13:15 +00:00
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
localPeerId = PeerId.init(s.localPublicKey).tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2020-02-04 14:17:24 +00:00
|
|
|
trace "Local proposal", schemes = SecioExchanges,
|
|
|
|
ciphers = SecioCiphers,
|
2019-09-13 17:20:37 +00:00
|
|
|
hashes = SecioHashes,
|
2020-03-23 06:03:36 +00:00
|
|
|
pubkey = localBytesPubkey.shortLog,
|
2019-09-13 17:20:37 +00:00
|
|
|
peer = localPeerId
|
|
|
|
|
|
|
|
var answer = await transactMessage(conn, request)
|
2019-09-10 02:13:15 +00:00
|
|
|
|
|
|
|
if len(answer) == 0:
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Proposal exchange failed", conn
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Proposal exchange failed")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
if not decodeProposal(answer, remoteNonce, remoteBytesPubkey, remoteExchanges,
|
|
|
|
remoteCiphers, remoteHashes):
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Remote proposal decoding failed", conn
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Remote proposal decoding failed")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
if not remotePubkey.init(remoteBytesPubkey):
|
2020-07-21 20:10:21 +00:00
|
|
|
trace "Remote public key incorrect or corrupted",
|
|
|
|
pubkey = remoteBytesPubkey.shortLog
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Remote public key incorrect or corrupted")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
remotePeerId = PeerId.init(remotePubkey).tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2022-09-05 12:31:14 +00:00
|
|
|
if peerId.isSome():
|
|
|
|
let targetPid = peerId.get()
|
|
|
|
if not targetPid.validate():
|
|
|
|
raise newException(SecioError, "Failed to validate expected peerId.")
|
|
|
|
|
|
|
|
if remotePeerId != targetPid:
|
|
|
|
raise newException(SecioError, "Peer ids don't match!")
|
|
|
|
conn.peerId = remotePeerId
|
2019-09-13 17:20:37 +00:00
|
|
|
let order = getOrder(remoteBytesPubkey, localNonce, localBytesPubkey,
|
2020-05-18 05:25:55 +00:00
|
|
|
remoteNonce).tryGet()
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "Remote proposal", schemes = remoteExchanges, ciphers = remoteCiphers,
|
2019-09-13 17:20:37 +00:00
|
|
|
hashes = remoteHashes,
|
2020-03-23 06:03:36 +00:00
|
|
|
pubkey = remoteBytesPubkey.shortLog, order = order,
|
2019-09-13 17:20:37 +00:00
|
|
|
peer = remotePeerId
|
|
|
|
|
|
|
|
let scheme = selectBest(order, SecioExchanges, remoteExchanges)
|
|
|
|
let cipher = selectBest(order, SecioCiphers, remoteCiphers)
|
|
|
|
let hash = selectBest(order, SecioHashes, remoteHashes)
|
|
|
|
if len(scheme) == 0 or len(cipher) == 0 or len(hash) == 0:
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "No algorithms in common", peer = remotePeerId
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "No algorithms in common")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "Encryption scheme selected", scheme = scheme, cipher = cipher,
|
2019-09-13 17:20:37 +00:00
|
|
|
hash = hash
|
|
|
|
|
2020-07-07 11:14:11 +00:00
|
|
|
var ekeypair = ephemeral(scheme, s.rng[]).tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
# We need EC public key in raw binary form
|
2020-07-21 20:10:21 +00:00
|
|
|
var epubkey = ekeypair.pubkey.getRawBytes().tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
var localCorpus = request[4..^1] & answer & epubkey
|
2020-05-18 05:25:55 +00:00
|
|
|
var signature = s.localPrivateKey.sign(localCorpus).tryGet()
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
var localExchange = createExchange(epubkey, signature.getBytes())
|
|
|
|
var remoteExchange = await transactMessage(conn, localExchange)
|
|
|
|
if len(remoteExchange) == 0:
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Corpus exchange failed", conn
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Corpus exchange failed")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
if not decodeExchange(remoteExchange, remoteEBytesPubkey, remoteEBytesSig):
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Remote exchange decoding failed", conn
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Remote exchange decoding failed")
|
2019-09-06 06:51:46 +00:00
|
|
|
|
2019-09-13 17:20:37 +00:00
|
|
|
if not remoteESignature.init(remoteEBytesSig):
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "Remote signature incorrect or corrupted", signature = remoteEBytesSig.shortLog
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Remote signature incorrect or corrupted")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
var remoteCorpus = answer & request[4..^1] & remoteEBytesPubkey
|
|
|
|
if not remoteESignature.verify(remoteCorpus, remotePubkey):
|
2020-02-04 14:17:24 +00:00
|
|
|
trace "Signature verification failed", scheme = $remotePubkey.scheme,
|
|
|
|
signature = $remoteESignature,
|
|
|
|
pubkey = $remotePubkey,
|
|
|
|
corpus = $remoteCorpus
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Signature verification failed")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "Signature verified", scheme = remotePubkey.scheme
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2020-07-21 20:10:21 +00:00
|
|
|
if not remoteEPubkey.initRaw(remoteEBytesPubkey):
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "Remote ephemeral public key incorrect or corrupted",
|
2019-09-13 17:20:37 +00:00
|
|
|
pubkey = toHex(remoteEBytesPubkey)
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Remote ephemeral public key incorrect or corrupted")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
var secret = getSecret(remoteEPubkey, ekeypair.seckey)
|
|
|
|
if len(secret) == 0:
|
2020-07-21 20:10:21 +00:00
|
|
|
trace "Shared secret could not be created"
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Shared secret could not be created")
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "Shared secret calculated", secret = secret.shortLog
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
var keys = stretchKeys(cipher, hash, secret)
|
|
|
|
|
|
|
|
trace "Authenticated encryption parameters",
|
2020-03-23 06:03:36 +00:00
|
|
|
iv0 = toHex(keys.ivOpenArray(0)), key0 = keys.keyOpenArray(0).shortLog,
|
|
|
|
mac0 = keys.macOpenArray(0).shortLog,
|
|
|
|
iv1 = keys.ivOpenArray(1).shortLog, key1 = keys.keyOpenArray(1).shortLog,
|
|
|
|
mac1 = keys.macOpenArray(1).shortLog
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
# Perform Nonce exchange over encrypted channel.
|
|
|
|
|
2020-02-25 05:06:57 +00:00
|
|
|
var secioConn = newSecioConn(conn, hash, cipher, keys, order, remotePubkey)
|
|
|
|
result = secioConn
|
2020-05-07 20:37:46 +00:00
|
|
|
await secioConn.write(remoteNonce)
|
2020-02-25 05:06:57 +00:00
|
|
|
var res = await secioConn.readMessage()
|
2019-09-13 17:20:37 +00:00
|
|
|
|
|
|
|
if res != @localNonce:
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "Nonce verification failed", receivedNonce = res.shortLog,
|
|
|
|
localNonce = localNonce.shortLog
|
2020-05-07 20:37:46 +00:00
|
|
|
raise (ref SecioError)(msg: "Nonce verification failed")
|
2019-09-13 17:20:37 +00:00
|
|
|
else:
|
2019-11-06 18:25:33 +00:00
|
|
|
trace "Secure handshake succeeded"
|
2019-09-13 17:20:37 +00:00
|
|
|
|
2019-09-13 18:01:14 +00:00
|
|
|
method init(s: Secio) {.gcsafe.} =
|
2020-02-25 05:06:57 +00:00
|
|
|
procCall Secure(s).init()
|
2019-09-13 18:01:14 +00:00
|
|
|
s.codec = SecioCodec
|
2019-09-06 06:51:46 +00:00
|
|
|
|
2021-06-07 07:32:08 +00:00
|
|
|
proc new*(
|
|
|
|
T: typedesc[Secio],
|
2022-06-16 08:08:52 +00:00
|
|
|
rng: ref HmacDrbgContext,
|
2021-06-07 07:32:08 +00:00
|
|
|
localPrivateKey: PrivateKey): T =
|
2021-09-02 10:03:40 +00:00
|
|
|
let pkRes = localPrivateKey.getPublicKey()
|
2021-05-21 16:27:01 +00:00
|
|
|
if pkRes.isErr:
|
2021-09-02 10:03:40 +00:00
|
|
|
raise newException(Defect, "Invalid private key")
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2021-06-07 07:32:08 +00:00
|
|
|
let secio = Secio(
|
2020-07-07 11:14:11 +00:00
|
|
|
rng: rng,
|
|
|
|
localPrivateKey: localPrivateKey,
|
2021-09-02 10:03:40 +00:00
|
|
|
localPublicKey: pkRes.get(),
|
2020-07-07 11:14:11 +00:00
|
|
|
)
|
2021-06-07 07:32:08 +00:00
|
|
|
secio.init()
|
|
|
|
secio
|