Packet.hpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_N_PACKET_HPP
  14. #define ZT_N_PACKET_HPP
  15. #include <cstdint>
  16. #include <cstring>
  17. #include <cstdio>
  18. #include <string>
  19. #include <iostream>
  20. #include "Constants.hpp"
  21. #include "Address.hpp"
  22. #include "Poly1305.hpp"
  23. #include "Salsa20.hpp"
  24. #include "Utils.hpp"
  25. #include "Buffer.hpp"
  26. /**
  27. * Protocol version -- incremented only for major changes
  28. *
  29. * 1 - 0.2.0 ... 0.2.5
  30. * 2 - 0.3.0 ... 0.4.5
  31. * + Added signature and originating peer to multicast frame
  32. * + Double size of multicast frame bloom filter
  33. * 3 - 0.5.0 ... 0.6.0
  34. * + Yet another multicast redesign
  35. * + New crypto completely changes key agreement cipher
  36. * 4 - 0.6.0 ... 1.0.6
  37. * + BREAKING CHANGE: New identity format based on hashcash design
  38. * 5 - 1.1.0 ... 1.1.5
  39. * + Supports echo
  40. * + Supports in-band world (root server definition) updates
  41. * + Clustering! (Though this will work with protocol v4 clients.)
  42. * + Otherwise backward compatible with protocol v4
  43. * 6 - 1.1.5 ... 1.1.10
  44. * + Network configuration format revisions including binary values
  45. * 7 - 1.1.10 ... 1.1.17
  46. * + Introduce trusted paths for local SDN use
  47. * 8 - 1.1.17 ... 1.2.0
  48. * + Multipart network configurations for large network configs
  49. * + Tags and Capabilities
  50. * + inline push of CertificateOfMembership deprecated
  51. * 9 - 1.2.0 ... 1.2.14
  52. * 10 - 1.4.0 ... 1.6.0
  53. * + Multipath capability and load balancing
  54. * 11 - 2.0.0 ... CURRENT
  55. * + Peer-to-peer multicast replication (optional)
  56. * + Old planet/moon stuff is DEAD!
  57. * + AES-256-GMAC-CTR encryption is now the default
  58. * + NIST P-384 (type 1) identities now supported
  59. * + WILL_RELAY allows mesh-like operation
  60. * + Ephemeral keys are now negotiated opportunistically
  61. */
  62. #define ZT_PROTO_VERSION 11
  63. /**
  64. * Minimum supported protocol version
  65. */
  66. #define ZT_PROTO_VERSION_MIN 6
  67. /**
  68. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  69. *
  70. * This is a protocol constant. It's the maximum allowed by the length
  71. * of the hop counter -- three bits. See node/Constants.hpp for the
  72. * pragmatic forwarding limit, which is typically lower.
  73. */
  74. #define ZT_PROTO_MAX_HOPS 7
  75. /**
  76. * NONE/Poly1305 (using Salsa20/12 to generate poly1305 key)
  77. */
  78. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  79. /**
  80. * Salsa2012/Poly1305
  81. */
  82. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  83. /**
  84. * No encryption or authentication at all
  85. *
  86. * For trusted paths the MAC field is the trusted path ID.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__NONE 2
  89. /**
  90. * AES-GMAC_SIV with AES-256
  91. */
  92. #define ZT_PROTO_CIPHER_SUITE__AES256_GMAC_SIV 3
  93. /**
  94. * Header flag indicating that a packet is fragmented
  95. *
  96. * If this flag is set, the receiver knows to expect more than one fragment.
  97. * See Packet::Fragment for details.
  98. */
  99. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  100. /**
  101. * Verb flag indicating payload is compressed with LZ4
  102. */
  103. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  104. // Field indexes in packet header
  105. #define ZT_PACKET_IDX_IV 0
  106. #define ZT_PACKET_IDX_DEST 8
  107. #define ZT_PACKET_IDX_SOURCE 13
  108. #define ZT_PACKET_IDX_FLAGS 18
  109. #define ZT_PACKET_IDX_MAC 19
  110. #define ZT_PACKET_IDX_VERB 27
  111. #define ZT_PACKET_IDX_PAYLOAD 28
  112. /**
  113. * Packet buffer size (can be changed)
  114. */
  115. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_DEFAULT_PHYSMTU)
  116. /**
  117. * Minimum viable packet length (a.k.a. header length)
  118. */
  119. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  120. // Indexes of fields in fragment header
  121. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  122. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  123. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  124. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  125. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  126. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  127. /**
  128. * Magic number found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR
  129. */
  130. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  131. /**
  132. * Minimum viable fragment length
  133. */
  134. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  135. // Field indices for parsing verbs -------------------------------------------
  136. // Some verbs have variable-length fields. Those aren't fully defined here
  137. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  138. // See their respective handler functions.
  139. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  140. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  141. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  142. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  143. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  144. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  145. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  146. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  147. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  148. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  149. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  150. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  151. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  152. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  153. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  154. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  155. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  156. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  157. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  158. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  159. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  160. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  161. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  162. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  163. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  164. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  165. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  166. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  167. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  168. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  169. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  170. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  171. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  172. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  173. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  174. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  175. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  176. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  177. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  178. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  179. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  180. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  181. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT + 4)
  182. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  183. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  184. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  185. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  186. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  187. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  188. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  189. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  190. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  191. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  192. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  193. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  194. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  195. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  196. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  197. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  198. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  199. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  200. // ---------------------------------------------------------------------------
  201. namespace ZeroTier {
  202. /**
  203. * ZeroTier packet
  204. *
  205. * Packet format:
  206. * <[8] 64-bit packet ID / crypto IV>
  207. * <[5] destination ZT address>
  208. * <[5] source ZT address>
  209. * <[1] flags/cipher/hops>
  210. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  211. * [... -- begin encryption envelope -- ...]
  212. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  213. * [... verb-specific payload ...]
  214. *
  215. * Packets smaller than 28 bytes are invalid and silently discarded.
  216. *
  217. * The 64-bit packet ID is a strongly random value used as a crypto IV.
  218. * Its least significant 3 bits are also used as a monotonically increasing
  219. * (and looping) counter for sending packets to a particular recipient. This
  220. * can be used for link quality monitoring and reporting and has no crypto
  221. * impact as it does not increase the likelihood of an IV collision. (The
  222. * crypto we use is not sensitive to the nature of the IV, only that it does
  223. * not repeat.)
  224. *
  225. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  226. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  227. * and H is hop count.
  228. *
  229. * The three-bit hop count is the only part of a packet that is mutable in
  230. * transit without invalidating the MAC. All other bits in the packet are
  231. * immutable. This is because intermediate nodes can increment the hop
  232. * count up to 7 (protocol max).
  233. *
  234. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  235. * sent in the clear, as it's the "here is my public key" message.
  236. */
  237. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  238. {
  239. public:
  240. /**
  241. * A packet fragment
  242. *
  243. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  244. * is sent with its normal header with the fragmented flag set. Remaining
  245. * fragments are sent this way.
  246. *
  247. * The fragmented bit indicates that there is at least one fragment. Fragments
  248. * themselves contain the total, so the receiver must "learn" this from the
  249. * first fragment it receives.
  250. *
  251. * Fragments are sent with the following format:
  252. * <[8] packet ID of packet whose fragment this belongs to>
  253. * <[5] destination ZT address>
  254. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  255. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  256. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  257. * <[...] fragment data>
  258. *
  259. * The protocol supports a maximum of 16 fragments. If a fragment is received
  260. * before its main packet header, it should be cached for a brief period of
  261. * time to see if its parent arrives. Loss of any fragment constitutes packet
  262. * loss; there is no retransmission mechanism. The receiver must wait for full
  263. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  264. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  265. */
  266. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  267. {
  268. public:
  269. inline Fragment() :
  270. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>() {}
  271. template<unsigned int C2>
  272. inline Fragment(const Buffer<C2> &b) :
  273. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b) {}
  274. inline Fragment(const void *data,unsigned int len) :
  275. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len) {}
  276. /**
  277. * Initialize from a packet
  278. *
  279. * @param p Original assembled packet
  280. * @param fragStart Start of fragment (raw index in packet data)
  281. * @param fragLen Length of fragment in bytes
  282. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  283. * @param fragTotal Total number of fragments (including 0)
  284. */
  285. inline Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  286. {
  287. init(p,fragStart,fragLen,fragNo,fragTotal);
  288. }
  289. /**
  290. * Initialize from a packet
  291. *
  292. * @param p Original assembled packet
  293. * @param fragStart Start of fragment (raw index in packet data)
  294. * @param fragLen Length of fragment in bytes
  295. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  296. * @param fragTotal Total number of fragments (including 0)
  297. */
  298. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  299. {
  300. if ((fragStart + fragLen) > p.size())
  301. throw ZT_EXCEPTION_OUT_OF_BOUNDS;
  302. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  303. // NOTE: this copies both the IV/packet ID and the destination address.
  304. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  305. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  306. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  307. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  308. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  309. }
  310. /**
  311. * Get this fragment's destination
  312. *
  313. * @return Destination ZT address
  314. */
  315. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  316. /**
  317. * @return True if fragment is of a valid length
  318. */
  319. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  320. /**
  321. * @return ID of packet this is a fragment of
  322. */
  323. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  324. /**
  325. * @return Total number of fragments in packet
  326. */
  327. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  328. /**
  329. * @return Fragment number of this fragment
  330. */
  331. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  332. /**
  333. * @return Fragment ZT hop count
  334. */
  335. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  336. /**
  337. * Increment this packet's hop count
  338. */
  339. inline unsigned int incrementHops()
  340. {
  341. return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1));
  342. }
  343. /**
  344. * @return Length of payload in bytes
  345. */
  346. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  347. /**
  348. * @return Raw packet payload
  349. */
  350. inline const unsigned char *payload() const { return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  351. };
  352. /**
  353. * ZeroTier protocol verbs
  354. */
  355. enum Verb /* Max value: 32 (5 bits) */
  356. {
  357. /**
  358. * No operation (ignored, no reply)
  359. */
  360. VERB_NOP = 0x00,
  361. /**
  362. * Announcement of a node's existence and vitals:
  363. * <[1] protocol version>
  364. * <[1] software major version>
  365. * <[1] software minor version>
  366. * <[2] software revision>
  367. * <[8] timestamp for determining latency>
  368. * <[...] binary serialized identity>
  369. * <[...] physical destination address of packet>
  370. * [... begin encrypted region ...]
  371. * <[2] 16-bit reserved (legacy) field, always 0>
  372. * <[2] 16-bit length of meta-data dictionary>
  373. * <[...] meta-data dictionary>
  374. * [... end encrypted region ...]
  375. * <[48] HMAC-SHA384 of all fields to this point (as plaintext)>
  376. *
  377. * HELLO is sent with authentication but without the usual encryption so
  378. * that peers can exchange identities.
  379. *
  380. * Destination address is the actual wire address to which the packet
  381. * was sent. See InetAddress::serialize() for format.
  382. *
  383. * Starting at "begin encrypted section" the reset of the packet is
  384. * encrypted with Salsa20/12. This is not the normal packet encryption
  385. * and is technically not necessary as nothing in HELLO is secret. It
  386. * exists merely to shield meta-data info from passive listeners to
  387. * slightly improve privacy, and for backward compatibility with older
  388. * nodes that required it.
  389. *
  390. * HELLO (and its OK response) ends with a large 384-bit HMAC to allow
  391. * identity exchanges to be authenticated with additional strength beyond
  392. * ordinary packet authentication.
  393. *
  394. * OK payload:
  395. * <[8] HELLO timestamp field echo>
  396. * <[1] protocol version>
  397. * <[1] software major version>
  398. * <[1] software minor version>
  399. * <[2] software revision>
  400. * <[...] physical destination address of packet>
  401. * <[2] 16-bit reserved (legacy) field, always 0>
  402. * <[2] 16-bit length of meta-data dictionary>
  403. * <[...] meta-data dictionary>
  404. * <[48] HMAC-SHA384 of all fields to this point (as plaintext)>
  405. *
  406. * With the exception of the timestamp, the other fields pertain to the
  407. * respondent who is sending OK and are not echoes.
  408. *
  409. * ERROR has no payload.
  410. */
  411. VERB_HELLO = 0x01,
  412. /**
  413. * Error response:
  414. * <[1] in-re verb>
  415. * <[8] in-re packet ID>
  416. * <[1] error code>
  417. * <[...] error-dependent payload>
  418. *
  419. * If this is not in response to a single packet then verb can be
  420. * NOP and packet ID can be zero.
  421. */
  422. VERB_ERROR = 0x02,
  423. /**
  424. * Success response:
  425. * <[1] in-re verb>
  426. * <[8] in-re packet ID>
  427. * <[...] request-specific payload>
  428. */
  429. VERB_OK = 0x03,
  430. /**
  431. * Query an identity by address:
  432. * <[5] address to look up>
  433. * [<[...] additional addresses to look up>
  434. *
  435. * OK response payload:
  436. * <[...] identity>
  437. * <[...] locator>
  438. * [... additional identity/locator pairs]
  439. *
  440. * If the address is not found, no response is generated. The semantics
  441. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  442. * be performed.
  443. *
  444. * It is possible for an identity but a null/empty locator to be returned
  445. * if no locator is known for a node. Older versions will also send no
  446. * locator field at all.
  447. */
  448. VERB_WHOIS = 0x04,
  449. /**
  450. * Relay-mediated NAT traversal or firewall punching initiation:
  451. * <[1] flags (unused, currently 0)>
  452. * <[5] ZeroTier address of peer that might be found at this address>
  453. * <[2] 16-bit protocol address port>
  454. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  455. * <[...] protocol address (network byte order)>
  456. *
  457. * An upstream node can send this to inform both sides of a relay of
  458. * information they might use to establish a direct connection.
  459. *
  460. * Upon receipt a peer sends HELLO to establish a direct link.
  461. *
  462. * No OK or ERROR is generated.
  463. */
  464. VERB_RENDEZVOUS = 0x05,
  465. /**
  466. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  467. * <[8] 64-bit network ID>
  468. * <[2] 16-bit ethertype>
  469. * <[...] ethernet payload>
  470. *
  471. * MAC addresses are derived from the packet's source and destination
  472. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  473. * Ethernet framing and other optional flags and features when they
  474. * are not necessary.
  475. *
  476. * ERROR may be generated if a membership certificate is needed for a
  477. * closed network. Payload will be network ID.
  478. */
  479. VERB_FRAME = 0x06,
  480. /**
  481. * Full Ethernet frame with MAC addressing and optional fields:
  482. * <[8] 64-bit network ID>
  483. * <[1] flags>
  484. * <[6] destination MAC or all zero for destination node>
  485. * <[6] source MAC or all zero for node of origin>
  486. * <[2] 16-bit ethertype>
  487. * <[...] ethernet payload>
  488. *
  489. * Flags:
  490. * 0x01 - Certificate of network membership attached (DEPRECATED)
  491. * 0x02 - Most significant bit of subtype (see below)
  492. * 0x04 - Middle bit of subtype (see below)
  493. * 0x08 - Least significant bit of subtype (see below)
  494. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  495. *
  496. * Subtypes (0..7):
  497. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  498. * 0x1 - TEEd outbound frame
  499. * 0x2 - REDIRECTed outbound frame
  500. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  501. * 0x4 - TEEd inbound frame
  502. * 0x5 - REDIRECTed inbound frame
  503. * 0x6 - WATCHed inbound frame
  504. * 0x7 - (reserved for future use)
  505. *
  506. * An extended frame carries full MAC addressing, making it a
  507. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  508. * spoke multicast propagation is requested.
  509. *
  510. * OK payload (if ACK flag is set):
  511. * <[8] 64-bit network ID>
  512. * <[1] flags>
  513. * <[6] destination MAC or all zero for destination node>
  514. * <[6] source MAC or all zero for node of origin>
  515. * <[2] 16-bit ethertype>
  516. */
  517. VERB_EXT_FRAME = 0x07,
  518. /**
  519. * ECHO request (a.k.a. ping):
  520. * <[...] arbitrary payload>
  521. *
  522. * This generates OK with a copy of the transmitted payload. No ERROR
  523. * is generated. Response to ECHO requests is optional and ECHO may be
  524. * ignored if a node detects a possible flood.
  525. */
  526. VERB_ECHO = 0x08,
  527. /**
  528. * Announce interest in multicast group(s):
  529. * <[8] 64-bit network ID>
  530. * <[6] multicast Ethernet address>
  531. * <[4] multicast additional distinguishing information (ADI)>
  532. * [... additional tuples of network/address/adi ...]
  533. *
  534. * LIKEs may be sent to any peer, though a good implementation should
  535. * restrict them to peers on the same network they're for and to network
  536. * controllers and root servers. In the current network, root servers
  537. * will provide the service of final multicast cache.
  538. */
  539. VERB_MULTICAST_LIKE = 0x09,
  540. /**
  541. * Network credentials push:
  542. * [<[...] one or more certificates of membership>]
  543. * <[1] 0x00, null byte marking end of COM array>
  544. * <[2] 16-bit number of capabilities>
  545. * <[...] one or more serialized Capability>
  546. * <[2] 16-bit number of tags>
  547. * <[...] one or more serialized Tags>
  548. * <[2] 16-bit number of revocations>
  549. * <[...] one or more serialized Revocations>
  550. * <[2] 16-bit number of certificates of ownership>
  551. * <[...] one or more serialized CertificateOfOwnership>
  552. *
  553. * This can be sent by anyone at any time to push network credentials.
  554. * These will of course only be accepted if they are properly signed.
  555. * Credentials can be for any number of networks.
  556. *
  557. * The use of a zero byte to terminate the COM section is for legacy
  558. * backward compatibility. Newer fields are prefixed with a length.
  559. *
  560. * OK/ERROR are not generated.
  561. */
  562. VERB_NETWORK_CREDENTIALS = 0x0a,
  563. /**
  564. * Network configuration request:
  565. * <[8] 64-bit network ID>
  566. * <[2] 16-bit length of request meta-data dictionary>
  567. * <[...] string-serialized request meta-data>
  568. * <[8] 64-bit revision of netconf we currently have>
  569. * <[8] 64-bit timestamp of netconf we currently have>
  570. *
  571. * This message requests network configuration from a node capable of
  572. * providing it.
  573. *
  574. * Responses to this are always whole configs intended for the recipient.
  575. * For patches and other updates a NETWORK_CONFIG is sent instead.
  576. *
  577. * It would be valid and correct as of 1.2.0 to use NETWORK_CONFIG always,
  578. * but OK(NETWORK_CONFIG_REQUEST) should be sent for compatibility.
  579. *
  580. * OK response payload:
  581. * <[8] 64-bit network ID>
  582. * <[2] 16-bit length of network configuration dictionary chunk>
  583. * <[...] network configuration dictionary (may be incomplete)>
  584. * [ ... end of legacy single chunk response ... ]
  585. * <[1] 8-bit flags>
  586. * <[8] 64-bit config update ID (should never be 0)>
  587. * <[4] 32-bit total length of assembled dictionary>
  588. * <[4] 32-bit index of chunk>
  589. * [ ... end signed portion ... ]
  590. * <[1] 8-bit chunk signature type>
  591. * <[2] 16-bit length of chunk signature>
  592. * <[...] chunk signature>
  593. *
  594. * The chunk signature signs the entire payload of the OK response.
  595. * Currently only one signature type is supported: ed25519 (1).
  596. *
  597. * Each config chunk is signed to prevent memory exhaustion or
  598. * traffic crowding DOS attacks against config fragment assembly.
  599. *
  600. * If the packet is from the network controller it is permitted to end
  601. * before the config update ID or other chunking related or signature
  602. * fields. This is to support older controllers that don't include
  603. * these fields and may be removed in the future.
  604. *
  605. * ERROR response payload:
  606. * <[8] 64-bit network ID>
  607. */
  608. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  609. /**
  610. * Network configuration data push:
  611. * <[8] 64-bit network ID>
  612. * <[2] 16-bit length of network configuration dictionary chunk>
  613. * <[...] network configuration dictionary (may be incomplete)>
  614. * <[1] 8-bit flags>
  615. * <[8] 64-bit config update ID (should never be 0)>
  616. * <[4] 32-bit total length of assembled dictionary>
  617. * <[4] 32-bit index of chunk>
  618. * [ ... end signed portion ... ]
  619. * <[1] 8-bit chunk signature type>
  620. * <[2] 16-bit length of chunk signature>
  621. * <[...] chunk signature>
  622. *
  623. * This is a direct push variant for network config updates. It otherwise
  624. * carries the same payload as OK(NETWORK_CONFIG_REQUEST) and has the same
  625. * semantics.
  626. *
  627. * The legacy mode missing the additional chunking fields is not supported
  628. * here.
  629. *
  630. * Flags:
  631. * 0x01 - Use fast propagation
  632. *
  633. * An OK should be sent if the config is successfully received and
  634. * accepted.
  635. *
  636. * OK payload:
  637. * <[8] 64-bit network ID>
  638. * <[8] 64-bit config update ID>
  639. */
  640. VERB_NETWORK_CONFIG = 0x0c,
  641. /**
  642. * Request endpoints for multicast distribution:
  643. * <[8] 64-bit network ID>
  644. * <[1] flags>
  645. * <[6] MAC address of multicast group being queried>
  646. * <[4] 32-bit ADI for multicast group being queried>
  647. * <[4] 32-bit requested max number of multicast peers>
  648. *
  649. * This message asks a peer for additional known endpoints that have
  650. * LIKEd a given multicast group. It's sent when the sender wishes
  651. * to send multicast but does not have the desired number of recipient
  652. * peers.
  653. *
  654. * OK response payload: (multiple OKs can be generated)
  655. * <[8] 64-bit network ID>
  656. * <[6] MAC address of multicast group being queried>
  657. * <[4] 32-bit ADI for multicast group being queried>
  658. * <[4] 32-bit total number of known members in this multicast group>
  659. * <[2] 16-bit number of members enumerated in this packet>
  660. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  661. *
  662. * ERROR is not generated; queries that return no response are dropped.
  663. */
  664. VERB_MULTICAST_GATHER = 0x0d,
  665. /** *** DEPRECATED ***
  666. * Multicast frame:
  667. * <[8] 64-bit network ID>
  668. * <[1] flags>
  669. * [<[4] 32-bit implicit gather limit>]
  670. * [<[6] source MAC>]
  671. * <[6] destination MAC (multicast address)>
  672. * <[4] 32-bit multicast ADI (multicast address extension)>
  673. * <[2] 16-bit ethertype>
  674. * <[...] ethernet payload>
  675. *
  676. * Flags:
  677. * 0x01 - Network certificate of membership attached (DEPRECATED)
  678. * 0x02 - Implicit gather limit field is present
  679. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  680. * 0x08 - Please replicate (sent to multicast replicators)
  681. *
  682. * OK and ERROR responses are optional. OK may be generated if there are
  683. * implicit gather results or if the recipient wants to send its own
  684. * updated certificate of network membership to the sender. ERROR may be
  685. * generated if a certificate is needed or if multicasts to this group
  686. * are no longer wanted (multicast unsubscribe).
  687. *
  688. * OK response payload:
  689. * <[8] 64-bit network ID>
  690. * <[6] MAC address of multicast group>
  691. * <[4] 32-bit ADI for multicast group>
  692. * <[1] flags>
  693. * [<[...] network certificate of membership (DEPRECATED)>]
  694. * [<[...] implicit gather results if flag 0x01 is set>]
  695. *
  696. * OK flags (same bits as request flags):
  697. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  698. * 0x02 - OK includes implicit gather results
  699. *
  700. * ERROR response payload:
  701. * <[8] 64-bit network ID>
  702. * <[6] multicast group MAC>
  703. * <[4] 32-bit multicast group ADI>
  704. */
  705. VERB_MULTICAST_FRAME = 0x0e,
  706. /**
  707. * Push of potential endpoints for direct communication:
  708. * <[2] 16-bit number of paths>
  709. * <[...] paths>
  710. *
  711. * Path record format:
  712. * <[1] 8-bit path flags (always 0, currently unused)>
  713. * <[2] length of extended path characteristics or 0 for none>
  714. * <[...] extended path characteristics>
  715. * <[1] address type>
  716. * <[1] address length in bytes>
  717. * <[...] address>
  718. *
  719. * The receiver may, upon receiving a push, attempt to establish a
  720. * direct link to one or more of the indicated addresses. It is the
  721. * responsibility of the sender to limit which peers it pushes direct
  722. * paths to to those with whom it has a trust relationship. The receiver
  723. * must obey any restrictions provided such as exclusivity or blacklists.
  724. * OK responses to this message are optional.
  725. *
  726. * Note that a direct path push does not imply that learned paths can't
  727. * be used unless they are blacklisted explicitly or unless flag 0x01
  728. * is set.
  729. *
  730. * OK and ERROR are not generated.
  731. */
  732. VERB_PUSH_DIRECT_PATHS = 0x10,
  733. VERB_ACK = 0x12,
  734. VERB_QOS_MEASUREMENT = 0x13,
  735. /**
  736. * A message with arbitrary user-definable content:
  737. * <[8] 64-bit arbitrary message type ID>
  738. * [<[...] message payload>]
  739. *
  740. * This can be used to send arbitrary messages over VL1. It generates no
  741. * OK or ERROR and has no special semantics outside of whatever the user
  742. * (via the ZeroTier core API) chooses to give it.
  743. *
  744. * Message type IDs less than or equal to 65535 are reserved for use by
  745. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  746. * implementations.
  747. */
  748. VERB_USER_MESSAGE = 0x14,
  749. /**
  750. * Encapsulate a ZeroTier packet for multicast distribution:
  751. * [... begin signed portion ...]
  752. * <[1] 8-bit flags>
  753. * <[5] 40-bit ZeroTier address of sender>
  754. * <[2] 16-bit length of inner payload>
  755. * <[1] inner payload verb>
  756. * <[...] inner payload data>
  757. * [... end signed portion ...]
  758. * <[2] 16-bit length of signature or 0 if un-signed>
  759. * [<[...] optional signature of multicast>]
  760. * <[...] address (min prefix) list>
  761. */
  762. VERB_MULTICAST = 0x16,
  763. /**
  764. * Encapsulate a full ZeroTier packet in another:
  765. * <[...] raw encapsulated packet>
  766. *
  767. * Encapsulation exists to enable secure relaying as opposed to the usual
  768. * "dumb" relaying. The latter is faster but secure relaying has roles
  769. * where endpoint privacy is desired. Multiply nested ENCAP packets
  770. * could allow ZeroTier to act as an onion router.
  771. *
  772. * When encapsulated packets are forwarded they do have their hop count
  773. * field incremented.
  774. */
  775. VERB_ENCAP = 0x17
  776. // protocol max: 0x1f
  777. };
  778. /**
  779. * Error codes for VERB_ERROR
  780. */
  781. enum ErrorCode
  782. {
  783. /* No error, not actually used in transit */
  784. ERROR_NONE = 0x00,
  785. /* Invalid request */
  786. ERROR_INVALID_REQUEST = 0x01,
  787. /* Bad/unsupported protocol version */
  788. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  789. /* Unknown object queried */
  790. ERROR_OBJ_NOT_FOUND = 0x03,
  791. /* HELLO pushed an identity whose address is already claimed */
  792. ERROR_IDENTITY_COLLISION = 0x04,
  793. /* Verb or use case not supported/enabled by this node */
  794. ERROR_UNSUPPORTED_OPERATION = 0x05,
  795. /* Network membership certificate update needed */
  796. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  797. /* Tried to join network, but you're not a member */
  798. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  799. /* Cannot deliver a forwarded ZeroTier packet (e.g. hops exceeded, no routes) */
  800. /* Payload: <packet ID>, <destination>, <... additional packet ID / destinations> */
  801. ERROR_CANNOT_DELIVER = 0x09
  802. };
  803. template<unsigned int C2>
  804. inline Packet(const Buffer<C2> &b) :
  805. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  806. {
  807. }
  808. inline Packet(const void *data,unsigned int len) :
  809. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  810. {
  811. }
  812. /**
  813. * Construct a new empty packet with a unique random packet ID
  814. *
  815. * Flags and hops will be zero. Other fields and data region are undefined.
  816. * Use the header access methods (setDestination() and friends) to fill out
  817. * the header. Payload should be appended; initial size is header size.
  818. */
  819. inline Packet() :
  820. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  821. {
  822. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  823. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  824. }
  825. /**
  826. * Make a copy of a packet with a new initialization vector and destination address
  827. *
  828. * This can be used to take one draft prototype packet and quickly make copies to
  829. * encrypt for different destinations.
  830. *
  831. * @param prototype Prototype packet
  832. * @param dest Destination ZeroTier address for new packet
  833. */
  834. inline Packet(const Packet &prototype,const Address &dest) :
  835. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  836. {
  837. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  838. setDestination(dest);
  839. }
  840. /**
  841. * Construct a new empty packet with a unique random packet ID
  842. *
  843. * @param dest Destination ZT address
  844. * @param source Source ZT address
  845. * @param v Verb
  846. */
  847. inline Packet(const Address &dest,const Address &source,const Verb v) :
  848. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  849. {
  850. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  851. setDestination(dest);
  852. setSource(source);
  853. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  854. setVerb(v);
  855. }
  856. /**
  857. * Reset this packet structure for reuse in place
  858. *
  859. * @param dest Destination ZT address
  860. * @param source Source ZT address
  861. * @param v Verb
  862. */
  863. inline void reset(const Address &dest,const Address &source,const Verb v)
  864. {
  865. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  866. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  867. setDestination(dest);
  868. setSource(source);
  869. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  870. setVerb(v);
  871. }
  872. /**
  873. * Generate a new IV / packet ID in place
  874. *
  875. * This can be used to re-use a packet buffer multiple times to send
  876. * technically different but otherwise identical copies of the same
  877. * packet.
  878. */
  879. inline void newInitializationVector() { setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId()); }
  880. /**
  881. * Set this packet's destination
  882. *
  883. * @param dest ZeroTier address of destination
  884. */
  885. inline void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  886. /**
  887. * Set this packet's source
  888. *
  889. * @param source ZeroTier address of source
  890. */
  891. inline void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  892. /**
  893. * Get this packet's destination
  894. *
  895. * @return Destination ZT address
  896. */
  897. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  898. /**
  899. * Get this packet's source
  900. *
  901. * @return Source ZT address
  902. */
  903. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  904. /**
  905. * @return True if packet is of valid length
  906. */
  907. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  908. /**
  909. * @return True if packet is fragmented (expect fragments)
  910. */
  911. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  912. /**
  913. * Set this packet's fragmented flag
  914. *
  915. * @param f Fragmented flag value
  916. */
  917. inline void setFragmented(bool f)
  918. {
  919. if (f)
  920. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  921. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  922. }
  923. /**
  924. * @return True if compressed (result only valid if unencrypted)
  925. */
  926. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  927. /**
  928. * @return ZeroTier forwarding hops (0 to 7)
  929. */
  930. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  931. /**
  932. * Increment this packet's hop count
  933. */
  934. inline unsigned char incrementHops()
  935. {
  936. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  937. const unsigned char h = (b + 1) & 0x07;
  938. b = (b & 0xf8) | h;
  939. return (unsigned int)h;
  940. }
  941. /**
  942. * @return Cipher suite selector: 0 - 7 (see #defines)
  943. */
  944. inline unsigned int cipher() const
  945. {
  946. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  947. }
  948. /**
  949. * Set this packet's cipher suite
  950. */
  951. inline void setCipher(unsigned int c)
  952. {
  953. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  954. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  955. }
  956. /**
  957. * Get the trusted path ID for this packet (only meaningful if cipher is trusted path)
  958. *
  959. * @return Trusted path ID (from MAC field)
  960. */
  961. inline uint64_t trustedPathId() const { return at<uint64_t>(ZT_PACKET_IDX_MAC); }
  962. /**
  963. * Set this packet's trusted path ID and set the cipher spec to trusted path
  964. *
  965. * @param tpid Trusted path ID
  966. */
  967. inline void setTrusted(const uint64_t tpid)
  968. {
  969. setCipher(ZT_PROTO_CIPHER_SUITE__NONE);
  970. setAt(ZT_PACKET_IDX_MAC,tpid);
  971. }
  972. /**
  973. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  974. *
  975. * Note that the least significant 3 bits of this ID will change when armor()
  976. * is called to armor the packet for transport. This is because armor() will
  977. * mask the last 3 bits against the send counter for QoS monitoring use prior
  978. * to actually using the IV to encrypt and MAC the packet. Be aware of this
  979. * when grabbing the packetId of a new packet prior to armor/send.
  980. *
  981. * @return Packet ID
  982. */
  983. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  984. /**
  985. * Set packet verb
  986. *
  987. * This also has the side-effect of clearing any verb flags, such as
  988. * compressed, and so must only be done during packet composition.
  989. *
  990. * @param v New packet verb
  991. */
  992. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  993. /**
  994. * @return Packet verb (not including flag bits)
  995. */
  996. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  997. /**
  998. * @return Length of packet payload
  999. */
  1000. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1001. /**
  1002. * @return Raw packet payload
  1003. */
  1004. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1005. /**
  1006. * Armor packet for transport
  1007. *
  1008. * @param key 32-byte key
  1009. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1010. */
  1011. void armor(const void *key,bool encryptPayload);
  1012. /**
  1013. * Verify and (if encrypted) decrypt packet
  1014. *
  1015. * This does not handle trusted path mode packets and will return false
  1016. * for these. These are handled in IncomingPacket if the sending physical
  1017. * address and MAC field match a trusted path.
  1018. *
  1019. * @param key 32-byte key
  1020. * @return False if packet is invalid or failed MAC authenticity check
  1021. */
  1022. bool dearmor(const void *key);
  1023. /**
  1024. * Attempt to compress payload if not already (must be unencrypted)
  1025. *
  1026. * This requires that the payload at least contain the verb byte already
  1027. * set. The compressed flag in the verb is set if compression successfully
  1028. * results in a size reduction. If no size reduction occurs, compression
  1029. * is not done and the flag is left cleared.
  1030. *
  1031. * @return True if compression occurred
  1032. */
  1033. bool compress();
  1034. /**
  1035. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1036. *
  1037. * If payload is compressed, it is decompressed and the compressed verb
  1038. * flag is cleared. Otherwise nothing is done and true is returned.
  1039. *
  1040. * @return True if data is now decompressed and valid, false on error
  1041. */
  1042. bool uncompress();
  1043. private:
  1044. static const uint8_t ZERO_KEY[32];
  1045. static uint64_t nextPacketId();
  1046. /**
  1047. * Deterministically mangle a 256-bit crypto key based on packet
  1048. *
  1049. * This uses extra data from the packet to mangle the secret, giving us an
  1050. * effective IV that is somewhat more than 64 bits. This is "free" for
  1051. * Salsa20 since it has negligible key setup time so using a different
  1052. * key each time is fine.
  1053. *
  1054. * @param in Input key (32 bytes)
  1055. * @param out Output buffer (32 bytes)
  1056. */
  1057. ZT_ALWAYS_INLINE void _salsa20MangleKey(const uint8_t *in,uint8_t *out) const
  1058. {
  1059. const uint8_t *const d = (const unsigned char *)data();
  1060. // IV and source/destination addresses. Using the addresses divides the
  1061. // key space into two halves-- A->B and B->A (since order will change).
  1062. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1063. out[i] = in[i] ^ d[i];
  1064. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1065. // nodes. It's one of the only parts of a packet modifiable by people
  1066. // without the key.
  1067. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8U);
  1068. // Raw packet size in bytes -- thus each packet size defines a new
  1069. // key space.
  1070. out[19] = in[19] ^ (uint8_t)size();
  1071. out[20] = in[20] ^ (uint8_t)(size() >> 8U); // little endian
  1072. // Rest of raw key is used unchanged
  1073. for(unsigned int i=21;i<32;++i)
  1074. out[i] = in[i];
  1075. }
  1076. };
  1077. } // namespace ZeroTier
  1078. #endif