Packet.hpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_N_PACKET_HPP
  28. #define ZT_N_PACKET_HPP
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <string>
  33. #include <iostream>
  34. #include "Address.hpp"
  35. #include "Poly1305.hpp"
  36. #include "Salsa20.hpp"
  37. #include "Utils.hpp"
  38. #include "Constants.hpp"
  39. #include "Buffer.hpp"
  40. #include "../ext/lz4/lz4.h"
  41. /**
  42. * Protocol version -- incremented only for MAJOR changes
  43. *
  44. * 1 - 0.2.0 ... 0.2.5
  45. * 2 - 0.3.0 ... 0.4.5
  46. * * Added signature and originating peer to multicast frame
  47. * * Double size of multicast frame bloom filter
  48. * 3 - 0.5.0 ... 0.6.0
  49. * * Yet another multicast redesign
  50. * * New crypto completely changes key agreement cipher
  51. * 4 - 0.6.0 ...
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  58. /**
  59. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  60. *
  61. * This is not necessarily the maximum hop counter after which
  62. * relaying is no longer performed.
  63. */
  64. #define ZT_PROTO_MAX_HOPS 7
  65. /**
  66. * Header flag indicating that a packet is encrypted with Salsa20
  67. *
  68. * If this is not set, then the packet's payload is in the clear and the
  69. * MAC is over this (since there is no ciphertext). Otherwise the MAC is
  70. * of the ciphertext after encryption.
  71. */
  72. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  73. /**
  74. * Header flag indicating that a packet is fragmented
  75. *
  76. * If this flag is set, the receiver knows to expect more than one fragment.
  77. * See Packet::Fragment for details.
  78. */
  79. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  80. /**
  81. * Verb flag indicating payload is compressed with LZ4
  82. */
  83. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  84. /**
  85. * Rounds used for Salsa20 encryption in ZT
  86. */
  87. #define ZT_PROTO_SALSA20_ROUNDS 12
  88. // Indices of fields in normal packet header -- do not change as this
  89. // might require both code rework and will break compatibility.
  90. #define ZT_PACKET_IDX_IV 0
  91. #define ZT_PACKET_IDX_DEST 8
  92. #define ZT_PACKET_IDX_SOURCE 13
  93. #define ZT_PACKET_IDX_FLAGS 18
  94. #define ZT_PACKET_IDX_MAC 19
  95. #define ZT_PACKET_IDX_VERB 27
  96. #define ZT_PACKET_IDX_PAYLOAD 28
  97. /**
  98. * Packet buffer size (can be changed)
  99. */
  100. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  101. /**
  102. * Minimum viable packet length (also length of header)
  103. */
  104. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  105. // Indexes of fields in fragment header -- also can't be changed without
  106. // breaking compatibility.
  107. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  108. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  109. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  110. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  111. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  112. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  113. /**
  114. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  115. */
  116. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  117. /**
  118. * Minimum viable fragment length
  119. */
  120. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  121. /**
  122. * Length of LAN beacon packets
  123. */
  124. #define ZT_PROTO_BEACON_LENGTH 13
  125. #define ZT_PROTO_BEACON_IDX_ADDRESS 8
  126. // Size of bloom filter used in multicast propagation graph exploration
  127. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS 512
  128. #define ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES 64
  129. // Field incides for parsing verbs -------------------------------------------
  130. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  131. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  132. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  133. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  134. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  135. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  136. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  137. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  138. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  139. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  140. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  141. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  142. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  143. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  144. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  145. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  146. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  147. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  148. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  149. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  150. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  151. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  152. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  153. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  154. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  155. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  156. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  157. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  158. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  159. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  160. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  161. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH (ZT_PACKET_IDX_PAYLOAD)
  162. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH 2
  163. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_DEPTH)
  164. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO 320
  165. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO)
  166. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM 1024
  167. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM)
  168. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FLAGS 1
  169. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS)
  170. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FLAGS)
  171. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_NETWORK_ID 8
  172. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_NETWORK_ID)
  173. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE 2
  174. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM_NONCE)
  175. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS 1
  176. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX_BITS)
  177. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX 1
  178. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_PREFIX)
  179. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN 5
  180. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN_MCID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN)
  181. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN_MCID 3
  182. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GUID (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN)
  183. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_GUID 8
  184. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN_MCID + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN_MCID)
  185. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC 6
  186. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC)
  187. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC 6
  188. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC)
  189. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_ADI 4
  190. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_ADI)
  191. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ETHERTYPE 2
  192. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ETHERTYPE)
  193. #define ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FRAME_LEN 2
  194. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN + ZT_PROTO_VERB_MULTICAST_FRAME_LEN_FRAME_LEN)
  195. #define ZT_PROTO_VERB_MULTICAST_FRAME_FLAGS_HAS_MEMBERSHIP_CERTIFICATE 0x01
  196. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  197. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  198. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  199. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  200. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  201. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  202. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  203. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  204. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  205. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  206. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  207. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  208. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  209. // ---------------------------------------------------------------------------
  210. namespace ZeroTier {
  211. /**
  212. * ZeroTier packet
  213. *
  214. * Packet format:
  215. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  216. * <[5] destination ZT address>
  217. * <[5] source ZT address>
  218. * <[1] flags (LS 5 bits) and ZT hop count (MS 3 bits)>
  219. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  220. * [... -- begin encryption envelope -- ...]
  221. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  222. * [... verb-specific payload ...]
  223. *
  224. * Packets smaller than 28 bytes are invalid and silently discarded.
  225. *
  226. * MAC is computed on ciphertext *after* encryption. See also:
  227. *
  228. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  229. *
  230. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  231. * sent in the clear, as it's the "here is my public key" message.
  232. *
  233. * Beacon format and beacon packets:
  234. * <[8] 8 random bytes>
  235. * <[5] sender ZT address>
  236. *
  237. * A beacon is a 13-byte packet containing only the address of the sender.
  238. * Receiving peers may or may not respond to beacons with a HELLO or other
  239. * message to initiate direct communication.
  240. *
  241. * Beacons may be used for direct LAN announcement or NAT traversal.
  242. */
  243. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  244. {
  245. public:
  246. /**
  247. * A packet fragment
  248. *
  249. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  250. * is sent with its normal header with the fragmented flag set. Remaining
  251. * fragments are sent this way.
  252. *
  253. * The fragmented bit indicates that there is at least one fragment. Fragments
  254. * themselves contain the total, so the receiver must "learn" this from the
  255. * first fragment it receives.
  256. *
  257. * Fragments are sent with the following format:
  258. * <[8] packet ID of packet whose fragment this belongs to>
  259. * <[5] destination ZT address>
  260. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  261. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  262. * <[1] ZT hop count>
  263. * <[...] fragment data>
  264. *
  265. * The protocol supports a maximum of 16 fragments. If a fragment is received
  266. * before its main packet header, it should be cached for a brief period of
  267. * time to see if its parent arrives. Loss of any fragment constitutes packet
  268. * loss; there is no retransmission mechanism. The receiver must wait for full
  269. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  270. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  271. */
  272. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  273. {
  274. public:
  275. Fragment() :
  276. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  277. {
  278. }
  279. template<unsigned int C2>
  280. Fragment(const Buffer<C2> &b)
  281. throw(std::out_of_range) :
  282. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  283. {
  284. }
  285. /**
  286. * Initialize from a packet
  287. *
  288. * @param p Original assembled packet
  289. * @param fragStart Start of fragment (raw index in packet data)
  290. * @param fragLen Length of fragment in bytes
  291. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  292. * @param fragTotal Total number of fragments (including 0)
  293. * @throws std::out_of_range Packet size would exceed buffer
  294. */
  295. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  296. throw(std::out_of_range)
  297. {
  298. init(p,fragStart,fragLen,fragNo,fragTotal);
  299. }
  300. /**
  301. * Initialize from a packet
  302. *
  303. * @param p Original assembled packet
  304. * @param fragStart Start of fragment (raw index in packet data)
  305. * @param fragLen Length of fragment in bytes
  306. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  307. * @param fragTotal Total number of fragments (including 0)
  308. * @throws std::out_of_range Packet size would exceed buffer
  309. */
  310. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  311. throw(std::out_of_range)
  312. {
  313. if ((fragStart + fragLen) > p.size())
  314. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  315. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  316. // NOTE: this copies both the IV/packet ID and the destination address.
  317. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.data() + ZT_PACKET_IDX_IV,13);
  318. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  319. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  320. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  321. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.data() + fragStart,fragLen);
  322. }
  323. /**
  324. * Get this fragment's destination
  325. *
  326. * @return Destination ZT address
  327. */
  328. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  329. /**
  330. * @return True if fragment is of a valid length
  331. */
  332. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  333. /**
  334. * @return ID of packet this is a fragment of
  335. */
  336. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  337. /**
  338. * @return Total number of fragments in packet
  339. */
  340. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  341. /**
  342. * @return Fragment number of this fragment
  343. */
  344. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  345. /**
  346. * @return Fragment ZT hop count
  347. */
  348. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  349. /**
  350. * Increment this packet's hop count
  351. */
  352. inline void incrementHops()
  353. {
  354. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  355. }
  356. /**
  357. * @return Length of payload in bytes
  358. */
  359. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  360. /**
  361. * @return Raw packet payload
  362. */
  363. inline const unsigned char *payload() const
  364. {
  365. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  366. }
  367. };
  368. /**
  369. * ZeroTier protocol verbs
  370. */
  371. enum Verb /* Max value: 32 (5 bits) */
  372. {
  373. /* No operation, payload ignored, no reply */
  374. VERB_NOP = 0,
  375. /* Announcement of a node's existence:
  376. * <[1] protocol version>
  377. * <[1] software major version>
  378. * <[1] software minor version>
  379. * <[2] software revision>
  380. * <[8] timestamp (ms since epoch)>
  381. * <[...] binary serialized identity (see Identity)>
  382. *
  383. * OK payload:
  384. * <[8] timestamp (echoed from original HELLO)>
  385. * <[1] protocol version (of responder)>
  386. * <[1] software major version (of responder)>
  387. * <[1] software minor version (of responder)>
  388. * <[2] software revision (of responder)>
  389. *
  390. * ERROR has no payload.
  391. */
  392. VERB_HELLO = 1,
  393. /* Error response:
  394. * <[1] in-re verb>
  395. * <[8] in-re packet ID>
  396. * <[1] error code>
  397. * <[...] error-dependent payload>
  398. */
  399. VERB_ERROR = 2,
  400. /* Success response:
  401. * <[1] in-re verb>
  402. * <[8] in-re packet ID>
  403. * <[...] request-specific payload>
  404. */
  405. VERB_OK = 3,
  406. /* Query an identity by address:
  407. * <[5] address to look up>
  408. *
  409. * OK response payload:
  410. * <[...] binary serialized identity>
  411. *
  412. * ERROR response payload:
  413. * <[5] address>
  414. */
  415. VERB_WHOIS = 4,
  416. /* Meet another node at a given protocol address:
  417. * <[1] flags (unused, currently 0)>
  418. * <[5] ZeroTier address of peer that might be found at this address>
  419. * <[2] 16-bit protocol address port>
  420. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  421. * <[...] protocol address (network byte order)>
  422. *
  423. * This is sent by a relaying node to initiate NAT traversal between two
  424. * peers that are communicating by way of indirect relay. The relay will
  425. * send this to both peers at the same time on a periodic basis, telling
  426. * each where it might find the other on the network.
  427. *
  428. * Upon receipt a peer sends HELLO to establish a direct link.
  429. *
  430. * Nodes should implement rate control, limiting the rate at which they
  431. * respond to these packets to prevent their use in DDOS attacks. Nodes
  432. * may also ignore these messages if a peer is not known or is not being
  433. * actively communicated with.
  434. *
  435. * No OK or ERROR is generated.
  436. */
  437. VERB_RENDEZVOUS = 5,
  438. /* A ZT-to-ZT unicast ethernet frame:
  439. * <[8] 64-bit network ID>
  440. * <[2] 16-bit ethertype>
  441. * <[...] ethernet payload>
  442. *
  443. * MAC addresses are derived from the packet's source and destination
  444. * ZeroTier addresses.
  445. *
  446. * ERROR may be generated if a membership certificate is needed for a
  447. * closed network. Payload will be network ID.
  448. */
  449. VERB_FRAME = 6,
  450. /*
  451. * An ethernet frame to or from specified MAC addresses:
  452. * <[8] 64-bit network ID>
  453. * <[6] destination MAC or all zero for destination node>
  454. * <[6] source MAC or all zero for node of origin>
  455. * <[2] 16-bit ethertype>
  456. * <[...] ethernet payload>
  457. *
  458. * Extended frames include full MAC addressing and are used for bridged
  459. * configurations. Theoretically they could carry multicast as well but
  460. * currently they're not used for that.
  461. *
  462. * ERROR may be generated if a membership certificate is needed for a
  463. * closed network. Payload will be network ID.
  464. */
  465. VERB_EXT_FRAME = 7,
  466. /* A multicast frame:
  467. * <[2] 16-bit propagation depth or 0xffff for "do not forward">
  468. * <[320] propagation FIFO>
  469. * <[1024] propagation bloom filter>
  470. * [... begin signed portion ...]
  471. * <[1] 8-bit flags, currently unused and must be 0>
  472. * <[8] 64-bit network ID>
  473. * <[2] 16-bit random propagation bloom filter nonce>
  474. * <[1] number of significant bits in propagation restrict prefix>
  475. * <[1] propagation restriction prefix (sig bits right to left)>
  476. * <[5] ZeroTier address of node of origin>
  477. * <[3] 24-bit multicast ID, together with origin forms GUID>
  478. * <[6] source MAC address>
  479. * <[6] destination multicast group MAC address>
  480. * <[4] destination multicast group ADI field>
  481. * <[2] 16-bit frame ethertype>
  482. * <[2] 16-bit length of payload>
  483. * <[...] ethernet frame payload>
  484. * [... end of signed portion ...]
  485. * <[2] 16-bit length of signature>
  486. * <[...] signature (currently Ed25519/SHA-512, 96 bytes in length)>
  487. * [<[...] network membership certificate (optional)>]
  488. *
  489. * Flags:
  490. * 0x01 - Multicast frame includes network membership certificate
  491. * for original sender for this network.
  492. *
  493. * When a multicast frame is received:
  494. *
  495. * (1) Check the signature of the signed portion of packet, discard on fail
  496. * (2) Check for duplicate multicast, STOP if duplicate
  497. * (3) Check rate limits, STOP if over limit
  498. * (4) Inject into tap if member of network and packet passes other checks
  499. * (5) Increment propagation depth, STOP if over limit
  500. * (6) Pop topmost element off FIFO -- this is next hop
  501. * (7) Push suggested next hops onto FIFO until full -- set corresponding
  502. * bits in bloom filter
  503. * (8) Send to next hop, or to a supernode if none
  504. *
  505. * When choosing next hops, exclude addresses corresponding to bits already
  506. * set in the bloom filter and addresses outside the propagation restrict
  507. * prefix.
  508. *
  509. * Active bridges on a network are always added as next hops for all
  510. * multicast and broadcast traffic, as if they "like" all groups.
  511. *
  512. * Algorithm for setting bits in bloom filter:
  513. *
  514. * (1) Place the address in the least significant 40 bits of a 64-bit int.
  515. * (2) Add the bloom filter nonce to this value.
  516. * (3) XOR the least significant 13 bits of this value with the next most
  517. * significant 13 bits and so on, 4 times.
  518. * (4) This value ANDed with 0x1fff is the bit to set in the bloom filter.
  519. * (5) Set this bit via: byte[bit >> 3] |= (0x80 >> (bit & 7))
  520. *
  521. * To check bits in bloom filter perform the same computation but mask the
  522. * bit instead of ORing it.
  523. *
  524. * Propagation occurs within a restrict prefix. The restrict prefix is
  525. * applied to the least significant 16 bits of an address. The original
  526. * sender of the multicast sets the restrict prefix and sends 2^N copies
  527. * of the multicast frame, one for each address prefix.
  528. *
  529. * ERROR may be generated if a membership certificate is needed for a
  530. * closed network. Payload will be network ID.
  531. */
  532. VERB_MULTICAST_FRAME = 8,
  533. /* Announce interest in multicast group(s):
  534. * <[8] 64-bit network ID>
  535. * <[6] multicast Ethernet address>
  536. * <[4] multicast additional distinguishing information (ADI)>
  537. * [... additional tuples of network/address/adi ...]
  538. *
  539. * LIKEs are sent to peers with whom you have a direct peer to peer
  540. * connection, and always including supernodes.
  541. *
  542. * OK/ERROR are not generated.
  543. */
  544. VERB_MULTICAST_LIKE = 9,
  545. /* Network member certificate replication/push:
  546. * <[...] serialized certificate of membership>
  547. * [ ... additional certificates may follow ...]
  548. *
  549. * Certificate contains network ID, peer it was issued for, etc.
  550. *
  551. * OK/ERROR are not generated.
  552. */
  553. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  554. /* Network configuration request:
  555. * <[8] 64-bit network ID>
  556. * <[2] 16-bit length of request meta-data dictionary>
  557. * <[...] string-serialized request meta-data>
  558. *
  559. * This message requests network configuration from a node capable of
  560. * providing it. Such nodes run the netconf service, which must be
  561. * installed into the ZeroTier home directory.
  562. *
  563. * OK response payload:
  564. * <[8] 64-bit network ID>
  565. * <[2] 16-bit length of network configuration dictionary>
  566. * <[...] network configuration dictionary>
  567. *
  568. * OK returns a Dictionary (string serialized) containing the network's
  569. * configuration and IP address assignment information for the querying
  570. * node. It also contains a membership certificate that the querying
  571. * node can push to other peers to demonstrate its right to speak on
  572. * a given network.
  573. *
  574. * ERROR response payload:
  575. * <[8] 64-bit network ID>
  576. *
  577. * Support is optional. Nodes should return UNSUPPORTED_OPERATION if
  578. * not supported or enabled.
  579. */
  580. VERB_NETWORK_CONFIG_REQUEST = 11,
  581. /* Network configuration refresh request:
  582. * <[...] array of 64-bit network IDs>
  583. *
  584. * This message can be sent by the network configuration master node
  585. * to request that nodes refresh their network configuration. It can
  586. * thus be used to "push" updates so that network config changes will
  587. * take effect quickly.
  588. *
  589. * It does not generate an OK or ERROR message, and is treated only as
  590. * a hint to refresh now.
  591. */
  592. VERB_NETWORK_CONFIG_REFRESH = 12
  593. };
  594. /**
  595. * Error codes for VERB_ERROR
  596. */
  597. enum ErrorCode
  598. {
  599. /* No error, not actually used in transit */
  600. ERROR_NONE = 0,
  601. /* Invalid request */
  602. ERROR_INVALID_REQUEST = 1,
  603. /* Bad/unsupported protocol version */
  604. ERROR_BAD_PROTOCOL_VERSION = 2,
  605. /* Unknown object queried (e.g. with WHOIS) */
  606. ERROR_OBJ_NOT_FOUND = 3,
  607. /* HELLO pushed an identity whose address is already claimed */
  608. ERROR_IDENTITY_COLLISION = 4,
  609. /* Verb or use case not supported/enabled by this node */
  610. ERROR_UNSUPPORTED_OPERATION = 5,
  611. /* Message to private network rejected -- no unexpired certificate on file */
  612. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  613. /* Tried to join network, but you're not a member */
  614. ERROR_NETWORK_ACCESS_DENIED_ = 7 /* extra _ to avoid Windows name conflict */
  615. };
  616. /**
  617. * @param v Verb
  618. * @return String representation (e.g. HELLO, OK)
  619. */
  620. static const char *verbString(Verb v)
  621. throw();
  622. /**
  623. * @param e Error code
  624. * @return String error name
  625. */
  626. static const char *errorString(ErrorCode e)
  627. throw();
  628. template<unsigned int C2>
  629. Packet(const Buffer<C2> &b)
  630. throw(std::out_of_range) :
  631. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  632. {
  633. }
  634. /**
  635. * Construct a new empty packet with a unique random packet ID
  636. *
  637. * Flags and hops will be zero. Other fields and data region are undefined.
  638. * Use the header access methods (setDestination() and friends) to fill out
  639. * the header. Payload should be appended; initial size is header size.
  640. */
  641. Packet() :
  642. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  643. {
  644. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  645. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  646. }
  647. /**
  648. * Construct a new empty packet with a unique random packet ID
  649. *
  650. * @param dest Destination ZT address
  651. * @param source Source ZT address
  652. * @param v Verb
  653. */
  654. Packet(const Address &dest,const Address &source,const Verb v) :
  655. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  656. {
  657. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  658. setDestination(dest);
  659. setSource(source);
  660. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  661. setVerb(v);
  662. }
  663. /**
  664. * Reset this packet structure for reuse in place
  665. *
  666. * @param dest Destination ZT address
  667. * @param source Source ZT address
  668. * @param v Verb
  669. */
  670. inline void reset(const Address &dest,const Address &source,const Verb v)
  671. {
  672. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  673. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  674. setDestination(dest);
  675. setSource(source);
  676. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  677. setVerb(v);
  678. }
  679. /**
  680. * Generate a new IV / packet ID in place
  681. *
  682. * This can be used to re-use a packet buffer multiple times to send
  683. * technically different but otherwise identical copies of the same
  684. * packet.
  685. */
  686. inline void newInitializationVector()
  687. {
  688. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  689. }
  690. /**
  691. * Set this packet's destination
  692. *
  693. * @param dest ZeroTier address of destination
  694. */
  695. inline void setDestination(const Address &dest)
  696. {
  697. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  698. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  699. d[i] = dest[i];
  700. }
  701. /**
  702. * Set this packet's source
  703. *
  704. * @param source ZeroTier address of source
  705. */
  706. inline void setSource(const Address &source)
  707. {
  708. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  709. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  710. s[i] = source[i];
  711. }
  712. /**
  713. * Get this packet's destination
  714. *
  715. * @return Destination ZT address
  716. */
  717. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  718. /**
  719. * Get this packet's source
  720. *
  721. * @return Source ZT address
  722. */
  723. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  724. /**
  725. * @return True if packet is of valid length
  726. */
  727. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  728. /**
  729. * @return True if packet is encrypted
  730. */
  731. inline bool encrypted() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_ENCRYPTED) != 0); }
  732. /**
  733. * @return True if packet is fragmented (expect fragments)
  734. */
  735. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  736. /**
  737. * Set this packet's fragmented flag
  738. *
  739. * @param f Fragmented flag value
  740. */
  741. inline void setFragmented(bool f)
  742. {
  743. if (f)
  744. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  745. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  746. }
  747. /**
  748. * @return True if compressed (result only valid if unencrypted)
  749. */
  750. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  751. /**
  752. * @return ZeroTier forwarding hops (0 to 7)
  753. */
  754. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  755. /**
  756. * Increment this packet's hop count
  757. */
  758. inline void incrementHops()
  759. {
  760. (*this)[ZT_PACKET_IDX_FLAGS] = (char)((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8) | (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] + 1) & 0x07);
  761. }
  762. /**
  763. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  764. *
  765. * @return Packet ID
  766. */
  767. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  768. /**
  769. * Set packet verb
  770. *
  771. * This also has the side-effect of clearing any verb flags, such as
  772. * compressed, and so must only be done during packet composition.
  773. *
  774. * @param v New packet verb
  775. */
  776. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  777. /**
  778. * @return Packet verb (not including flag bits)
  779. */
  780. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  781. /**
  782. * @return Length of packet payload
  783. */
  784. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  785. /**
  786. * @return Raw packet payload
  787. */
  788. inline const unsigned char *payload() const
  789. {
  790. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  791. }
  792. /**
  793. * Armor packet for transport
  794. *
  795. * @param key 32-byte key
  796. * @param encryptPayload If true, encrypt packet payload, else just MAC
  797. */
  798. inline void armor(const void *key,bool encryptPayload)
  799. {
  800. unsigned char mangledKey[32];
  801. unsigned char macKey[32];
  802. unsigned char mac[16];
  803. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  804. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  805. // Set flag now, since it affects key mangle function
  806. if (encryptPayload)
  807. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_ENCRYPTED;
  808. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_ENCRYPTED);
  809. _mangleKey((const unsigned char *)key,mangledKey);
  810. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  811. // MAC key is always the first 32 bytes of the Salsa20 key stream
  812. // This is the same construction DJB's NaCl library uses
  813. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  814. if (encryptPayload)
  815. s20.encrypt(payload,payload,payloadLen);
  816. Poly1305::compute(mac,payload,payloadLen,macKey);
  817. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  818. }
  819. /**
  820. * Verify and (if encrypted) decrypt packet
  821. *
  822. * @param key 32-byte key
  823. * @return False if packet is invalid or failed MAC authenticity check
  824. */
  825. inline bool dearmor(const void *key)
  826. {
  827. unsigned char mangledKey[32];
  828. unsigned char macKey[32];
  829. unsigned char mac[16];
  830. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  831. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  832. _mangleKey((const unsigned char *)key,mangledKey);
  833. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  834. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  835. Poly1305::compute(mac,payload,payloadLen,macKey);
  836. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  837. return false;
  838. if (((*this)[ZT_PACKET_IDX_FLAGS] & (char)ZT_PROTO_FLAG_ENCRYPTED)) {
  839. s20.decrypt(payload,payload,payloadLen);
  840. (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_ENCRYPTED);
  841. }
  842. return true;
  843. }
  844. /**
  845. * Attempt to compress payload if not already (must be unencrypted)
  846. *
  847. * This requires that the payload at least contain the verb byte already
  848. * set. The compressed flag in the verb is set if compression successfully
  849. * results in a size reduction. If no size reduction occurs, compression
  850. * is not done and the flag is left cleared.
  851. *
  852. * @return True if compression occurred
  853. */
  854. inline bool compress()
  855. {
  856. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  857. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  858. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  859. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  860. if ((cl > 0)&&(cl < pl)) {
  861. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  862. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  863. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  864. return true;
  865. }
  866. }
  867. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  868. return false;
  869. }
  870. /**
  871. * Attempt to decompress payload if it is compressed (must be unencrypted)
  872. *
  873. * If payload is compressed, it is decompressed and the compressed verb
  874. * flag is cleared. Otherwise nothing is done and true is returned.
  875. *
  876. * @return True if data is now decompressed and valid, false on error
  877. */
  878. inline bool uncompress()
  879. {
  880. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  881. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  882. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  883. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  884. int ucl = LZ4_uncompress_unknownOutputSize((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  885. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  886. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  887. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  888. } else return false;
  889. }
  890. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  891. }
  892. return true;
  893. }
  894. private:
  895. static const unsigned char ZERO_KEY[32];
  896. /**
  897. * Deterministically mangle a 256-bit crypto key based on packet
  898. *
  899. * @param in Input key (32 bytes)
  900. * @param out Output buffer (32 bytes)
  901. */
  902. inline void _mangleKey(const unsigned char *in,unsigned char *out) const
  903. {
  904. // IV and source/destination addresses. Using the addresses divides the
  905. // key space into two halves-- A->B and B->A (since order will change).
  906. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  907. out[i] = in[i] ^ (unsigned char)(*this)[i];
  908. // Flags, but with hop count masked off. Hop count is altered by forwarding
  909. // nodes. It's one of the only parts of a packet modifiable by people
  910. // without the key.
  911. out[18] = in[18] ^ ((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & 0xf8);
  912. // Raw packet size in bytes -- thus each packet size defines a new
  913. // key space.
  914. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  915. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  916. // Rest of raw key is used unchanged
  917. for(unsigned int i=21;i<32;++i)
  918. out[i] = in[i];
  919. }
  920. };
  921. } // namespace ZeroTier
  922. #endif