message.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Contains the Whisper protocol Message element.
  17. package whisperv5
  18. import (
  19. "crypto/aes"
  20. "crypto/cipher"
  21. "crypto/ecdsa"
  22. crand "crypto/rand"
  23. "encoding/binary"
  24. "errors"
  25. "strconv"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/crypto/ecies"
  29. "github.com/ethereum/go-ethereum/log"
  30. )
  31. // MessageParams specifies the exact way a message should be wrapped into an Envelope.
  32. type MessageParams struct {
  33. TTL uint32
  34. Src *ecdsa.PrivateKey
  35. Dst *ecdsa.PublicKey
  36. KeySym []byte
  37. Topic TopicType
  38. WorkTime uint32
  39. PoW float64
  40. Payload []byte
  41. Padding []byte
  42. }
  43. // SentMessage represents an end-user data packet to transmit through the
  44. // Whisper protocol. These are wrapped into Envelopes that need not be
  45. // understood by intermediate nodes, just forwarded.
  46. type sentMessage struct {
  47. Raw []byte
  48. }
  49. // ReceivedMessage represents a data packet to be received through the
  50. // Whisper protocol.
  51. type ReceivedMessage struct {
  52. Raw []byte
  53. Payload []byte
  54. Padding []byte
  55. Signature []byte
  56. PoW float64 // Proof of work as described in the Whisper spec
  57. Sent uint32 // Time when the message was posted into the network
  58. TTL uint32 // Maximum time to live allowed for the message
  59. Src *ecdsa.PublicKey // Message recipient (identity used to decode the message)
  60. Dst *ecdsa.PublicKey // Message recipient (identity used to decode the message)
  61. Topic TopicType
  62. SymKeyHash common.Hash // The Keccak256Hash of the key, associated with the Topic
  63. EnvelopeHash common.Hash // Message envelope hash to act as a unique id
  64. EnvelopeVersion uint64
  65. }
  66. func isMessageSigned(flags byte) bool {
  67. return (flags & signatureFlag) != 0
  68. }
  69. func (msg *ReceivedMessage) isSymmetricEncryption() bool {
  70. return msg.SymKeyHash != common.Hash{}
  71. }
  72. func (msg *ReceivedMessage) isAsymmetricEncryption() bool {
  73. return msg.Dst != nil
  74. }
  75. // NewSentMessage creates and initializes a non-signed, non-encrypted Whisper message.
  76. func NewSentMessage(params *MessageParams) (*sentMessage, error) {
  77. msg := sentMessage{}
  78. msg.Raw = make([]byte, 1, len(params.Payload)+len(params.Padding)+signatureLength+padSizeLimit)
  79. msg.Raw[0] = 0 // set all the flags to zero
  80. err := msg.appendPadding(params)
  81. if err != nil {
  82. return nil, err
  83. }
  84. msg.Raw = append(msg.Raw, params.Payload...)
  85. return &msg, nil
  86. }
  87. // getSizeOfLength returns the number of bytes necessary to encode the entire size padding (including these bytes)
  88. func getSizeOfLength(b []byte) (sz int, err error) {
  89. sz = intSize(len(b)) // first iteration
  90. sz = intSize(len(b) + sz) // second iteration
  91. if sz > 3 {
  92. err = errors.New("oversized padding parameter")
  93. }
  94. return sz, err
  95. }
  96. // sizeOfIntSize returns minimal number of bytes necessary to encode an integer value
  97. func intSize(i int) (s int) {
  98. for s = 1; i >= 256; s++ {
  99. i /= 256
  100. }
  101. return s
  102. }
  103. // appendPadding appends the pseudorandom padding bytes and sets the padding flag.
  104. // The last byte contains the size of padding (thus, its size must not exceed 256).
  105. func (msg *sentMessage) appendPadding(params *MessageParams) error {
  106. rawSize := len(params.Payload) + 1
  107. if params.Src != nil {
  108. rawSize += signatureLength
  109. }
  110. odd := rawSize % padSizeLimit
  111. if len(params.Padding) != 0 {
  112. padSize := len(params.Padding)
  113. padLengthSize, err := getSizeOfLength(params.Padding)
  114. if err != nil {
  115. return err
  116. }
  117. totalPadSize := padSize + padLengthSize
  118. buf := make([]byte, 8)
  119. binary.LittleEndian.PutUint32(buf, uint32(totalPadSize))
  120. buf = buf[:padLengthSize]
  121. msg.Raw = append(msg.Raw, buf...)
  122. msg.Raw = append(msg.Raw, params.Padding...)
  123. msg.Raw[0] |= byte(padLengthSize) // number of bytes indicating the padding size
  124. } else if odd != 0 {
  125. totalPadSize := padSizeLimit - odd
  126. if totalPadSize > 255 {
  127. // this algorithm is only valid if padSizeLimit < 256.
  128. // if padSizeLimit will ever change, please fix the algorithm
  129. // (please see also ReceivedMessage.extractPadding() function).
  130. panic("please fix the padding algorithm before releasing new version")
  131. }
  132. buf := make([]byte, totalPadSize)
  133. _, err := crand.Read(buf[1:])
  134. if err != nil {
  135. return err
  136. }
  137. if totalPadSize > 6 && !validateSymmetricKey(buf) {
  138. return errors.New("failed to generate random padding of size " + strconv.Itoa(totalPadSize))
  139. }
  140. buf[0] = byte(totalPadSize)
  141. msg.Raw = append(msg.Raw, buf...)
  142. msg.Raw[0] |= byte(0x1) // number of bytes indicating the padding size
  143. }
  144. return nil
  145. }
  146. // sign calculates and sets the cryptographic signature for the message,
  147. // also setting the sign flag.
  148. func (msg *sentMessage) sign(key *ecdsa.PrivateKey) error {
  149. if isMessageSigned(msg.Raw[0]) {
  150. // this should not happen, but no reason to panic
  151. log.Error("failed to sign the message: already signed")
  152. return nil
  153. }
  154. msg.Raw[0] |= signatureFlag
  155. hash := crypto.Keccak256(msg.Raw)
  156. signature, err := crypto.Sign(hash, key)
  157. if err != nil {
  158. msg.Raw[0] &= ^signatureFlag // clear the flag
  159. return err
  160. }
  161. msg.Raw = append(msg.Raw, signature...)
  162. return nil
  163. }
  164. // encryptAsymmetric encrypts a message with a public key.
  165. func (msg *sentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error {
  166. if !ValidatePublicKey(key) {
  167. return errors.New("invalid public key provided for asymmetric encryption")
  168. }
  169. encrypted, err := ecies.Encrypt(crand.Reader, ecies.ImportECDSAPublic(key), msg.Raw, nil, nil)
  170. if err == nil {
  171. msg.Raw = encrypted
  172. }
  173. return err
  174. }
  175. // encryptSymmetric encrypts a message with a topic key, using AES-GCM-256.
  176. // nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
  177. func (msg *sentMessage) encryptSymmetric(key []byte) (nonce []byte, err error) {
  178. if !validateSymmetricKey(key) {
  179. return nil, errors.New("invalid key provided for symmetric encryption")
  180. }
  181. block, err := aes.NewCipher(key)
  182. if err != nil {
  183. return nil, err
  184. }
  185. aesgcm, err := cipher.NewGCM(block)
  186. if err != nil {
  187. return nil, err
  188. }
  189. // never use more than 2^32 random nonces with a given key
  190. nonce = make([]byte, aesgcm.NonceSize())
  191. _, err = crand.Read(nonce)
  192. if err != nil {
  193. return nil, err
  194. } else if !validateSymmetricKey(nonce) {
  195. return nil, errors.New("crypto/rand failed to generate nonce")
  196. }
  197. msg.Raw = aesgcm.Seal(nil, nonce, msg.Raw, nil)
  198. return nonce, nil
  199. }
  200. // Wrap bundles the message into an Envelope to transmit over the network.
  201. func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err error) {
  202. if options.TTL == 0 {
  203. options.TTL = DefaultTTL
  204. }
  205. if options.Src != nil {
  206. if err = msg.sign(options.Src); err != nil {
  207. return nil, err
  208. }
  209. }
  210. var nonce []byte
  211. if options.Dst != nil {
  212. err = msg.encryptAsymmetric(options.Dst)
  213. } else if options.KeySym != nil {
  214. nonce, err = msg.encryptSymmetric(options.KeySym)
  215. } else {
  216. err = errors.New("unable to encrypt the message: neither symmetric nor assymmetric key provided")
  217. }
  218. if err != nil {
  219. return nil, err
  220. }
  221. envelope = NewEnvelope(options.TTL, options.Topic, nonce, msg)
  222. if err = envelope.Seal(options); err != nil {
  223. return nil, err
  224. }
  225. return envelope, nil
  226. }
  227. // decryptSymmetric decrypts a message with a topic key, using AES-GCM-256.
  228. // nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
  229. func (msg *ReceivedMessage) decryptSymmetric(key []byte, nonce []byte) error {
  230. block, err := aes.NewCipher(key)
  231. if err != nil {
  232. return err
  233. }
  234. aesgcm, err := cipher.NewGCM(block)
  235. if err != nil {
  236. return err
  237. }
  238. if len(nonce) != aesgcm.NonceSize() {
  239. log.Error("decrypting the message", "AES nonce size", len(nonce))
  240. return errors.New("wrong AES nonce size")
  241. }
  242. decrypted, err := aesgcm.Open(nil, nonce, msg.Raw, nil)
  243. if err != nil {
  244. return err
  245. }
  246. msg.Raw = decrypted
  247. return nil
  248. }
  249. // decryptAsymmetric decrypts an encrypted payload with a private key.
  250. func (msg *ReceivedMessage) decryptAsymmetric(key *ecdsa.PrivateKey) error {
  251. decrypted, err := ecies.ImportECDSA(key).Decrypt(msg.Raw, nil, nil)
  252. if err == nil {
  253. msg.Raw = decrypted
  254. }
  255. return err
  256. }
  257. // Validate checks the validity and extracts the fields in case of success
  258. func (msg *ReceivedMessage) Validate() bool {
  259. end := len(msg.Raw)
  260. if end < 1 {
  261. return false
  262. }
  263. if isMessageSigned(msg.Raw[0]) {
  264. end -= signatureLength
  265. if end <= 1 {
  266. return false
  267. }
  268. msg.Signature = msg.Raw[end:]
  269. msg.Src = msg.SigToPubKey()
  270. if msg.Src == nil {
  271. return false
  272. }
  273. }
  274. padSize, ok := msg.extractPadding(end)
  275. if !ok {
  276. return false
  277. }
  278. msg.Payload = msg.Raw[1+padSize : end]
  279. return true
  280. }
  281. // extractPadding extracts the padding from raw message.
  282. // although we don't support sending messages with padding size
  283. // exceeding 255 bytes, such messages are perfectly valid, and
  284. // can be successfully decrypted.
  285. func (msg *ReceivedMessage) extractPadding(end int) (int, bool) {
  286. paddingSize := 0
  287. sz := int(msg.Raw[0] & paddingMask) // number of bytes indicating the entire size of padding (including these bytes)
  288. // could be zero -- it means no padding
  289. if sz != 0 {
  290. paddingSize = int(bytesToUintLittleEndian(msg.Raw[1 : 1+sz]))
  291. if paddingSize < sz || paddingSize+1 > end {
  292. return 0, false
  293. }
  294. msg.Padding = msg.Raw[1+sz : 1+paddingSize]
  295. }
  296. return paddingSize, true
  297. }
  298. // SigToPubKey retrieves the public key of the message signer.
  299. func (msg *ReceivedMessage) SigToPubKey() *ecdsa.PublicKey {
  300. defer func() { recover() }() // in case of invalid signature
  301. pub, err := crypto.SigToPub(msg.hash(), msg.Signature)
  302. if err != nil {
  303. log.Error("failed to recover public key from signature", "err", err)
  304. return nil
  305. }
  306. return pub
  307. }
  308. // hash calculates the SHA3 checksum of the message flags, payload and padding.
  309. func (msg *ReceivedMessage) hash() []byte {
  310. if isMessageSigned(msg.Raw[0]) {
  311. sz := len(msg.Raw) - signatureLength
  312. return crypto.Keccak256(msg.Raw[:sz])
  313. }
  314. return crypto.Keccak256(msg.Raw)
  315. }