Packet.hpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. /*
  2. * Copyright (c)2019 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: 2023-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 <stdint.h>
  16. #include <string.h>
  17. #include <stdio.h>
  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. * + ZT_ALWAYS_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. * + Minimum proto version is now 8 (1.1.17 and newer)
  60. * + WILL_RELAY allows mesh-like operation
  61. * + Ephemeral keys are now negotiated opportunistically
  62. */
  63. #define ZT_PROTO_VERSION 11
  64. /**
  65. * Minimum supported protocol version
  66. */
  67. #define ZT_PROTO_VERSION_MIN 8
  68. /**
  69. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  70. *
  71. * This is a protocol constant. It's the maximum allowed by the length
  72. * of the hop counter -- three bits. See node/Constants.hpp for the
  73. * pragmatic forwarding limit, which is typically lower.
  74. */
  75. #define ZT_PROTO_MAX_HOPS 7
  76. /**
  77. * NONE/Poly1305 (using Salsa20/12 to generate poly1305 key)
  78. */
  79. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  80. /**
  81. * Salsa2012/Poly1305
  82. */
  83. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  84. /**
  85. * Cipher suite: NONE
  86. *
  87. * This differs from POLY1305/NONE in that *no* crypto is done, not even
  88. * authentication. This is for trusted local LAN interconnects for internal
  89. * SDN use within a data center.
  90. *
  91. * For this mode the MAC field becomes a trusted path ID and must match the
  92. * configured ID of a trusted path or the packet is discarded.
  93. */
  94. #define ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH 2
  95. /**
  96. * AES-256-GMAC-CTR
  97. */
  98. #define ZT_PROTO_CIPHER_SUITE__AES256_GMAC_CTR 3
  99. /**
  100. * Header flag indicating that a packet is fragmented
  101. *
  102. * If this flag is set, the receiver knows to expect more than one fragment.
  103. * See Packet::Fragment for details.
  104. */
  105. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  106. /**
  107. * Verb flag indicating payload is compressed with LZ4
  108. */
  109. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  110. // Field indexes in packet header
  111. #define ZT_PACKET_IDX_IV 0
  112. #define ZT_PACKET_IDX_DEST 8
  113. #define ZT_PACKET_IDX_SOURCE 13
  114. #define ZT_PACKET_IDX_FLAGS 18
  115. #define ZT_PACKET_IDX_MAC 19
  116. #define ZT_PACKET_IDX_VERB 27
  117. #define ZT_PACKET_IDX_PAYLOAD 28
  118. /**
  119. * Packet buffer size (can be changed)
  120. */
  121. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_DEFAULT_PHYSMTU)
  122. /**
  123. * Minimum viable packet length (a.k.a. header length)
  124. */
  125. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  126. // Indexes of fields in fragment header
  127. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  128. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  129. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  130. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  131. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  132. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  133. /**
  134. * Magic number found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR
  135. */
  136. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  137. /**
  138. * Minimum viable fragment length
  139. */
  140. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  141. // Field indices for parsing verbs -------------------------------------------
  142. // Some verbs have variable-length fields. Those aren't fully defined here
  143. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  144. // See their respective handler functions.
  145. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  146. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  147. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  148. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  149. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  150. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  151. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  152. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  153. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  154. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  155. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  156. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  157. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  158. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  159. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  160. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  161. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  162. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  163. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  164. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  165. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  166. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  167. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  168. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  169. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  170. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  171. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  172. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  173. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  174. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  175. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  176. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  177. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  178. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  179. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  180. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  181. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  182. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  183. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  184. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  185. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  186. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  187. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT + 4)
  188. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  189. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  190. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  191. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  192. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  193. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  194. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  195. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  196. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  197. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  198. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  199. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  200. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  201. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  202. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  203. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  204. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  205. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  206. // ---------------------------------------------------------------------------
  207. namespace ZeroTier {
  208. /**
  209. * ZeroTier packet
  210. *
  211. * Packet format:
  212. * <[8] 64-bit packet ID / crypto IV / packet counter>
  213. * <[5] destination ZT address>
  214. * <[5] source ZT address>
  215. * <[1] flags/cipher/hops>
  216. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  217. * [... -- begin encryption envelope -- ...]
  218. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  219. * [... verb-specific payload ...]
  220. *
  221. * Packets smaller than 28 bytes are invalid and silently discarded.
  222. *
  223. * The 64-bit packet ID is a strongly random value used as a crypto IV.
  224. * Its least significant 3 bits are also used as a monotonically increasing
  225. * (and looping) counter for sending packets to a particular recipient. This
  226. * can be used for link quality monitoring and reporting and has no crypto
  227. * impact as it does not increase the likelihood of an IV collision. (The
  228. * crypto we use is not sensitive to the nature of the IV, only that it does
  229. * not repeat.)
  230. *
  231. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  232. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  233. * and H is hop count.
  234. *
  235. * The three-bit hop count is the only part of a packet that is mutable in
  236. * transit without invalidating the MAC. All other bits in the packet are
  237. * immutable. This is because intermediate nodes can increment the hop
  238. * count up to 7 (protocol max).
  239. *
  240. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  241. * sent in the clear, as it's the "here is my public key" message.
  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 (top 5 bits unused and must be zero)>
  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. ZT_ALWAYS_INLINE Fragment() :
  276. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>() {}
  277. template<unsigned int C2>
  278. ZT_ALWAYS_INLINE Fragment(const Buffer<C2> &b) :
  279. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b) {}
  280. ZT_ALWAYS_INLINE Fragment(const void *data,unsigned int len) :
  281. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len) {}
  282. /**
  283. * Initialize from a packet
  284. *
  285. * @param p Original assembled packet
  286. * @param fragStart Start of fragment (raw index in packet data)
  287. * @param fragLen Length of fragment in bytes
  288. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  289. * @param fragTotal Total number of fragments (including 0)
  290. */
  291. ZT_ALWAYS_INLINE Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  292. {
  293. init(p,fragStart,fragLen,fragNo,fragTotal);
  294. }
  295. /**
  296. * Initialize from a packet
  297. *
  298. * @param p Original assembled packet
  299. * @param fragStart Start of fragment (raw index in packet data)
  300. * @param fragLen Length of fragment in bytes
  301. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  302. * @param fragTotal Total number of fragments (including 0)
  303. */
  304. ZT_ALWAYS_INLINE void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  305. {
  306. if ((fragStart + fragLen) > p.size())
  307. throw ZT_EXCEPTION_OUT_OF_BOUNDS;
  308. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  309. // NOTE: this copies both the IV/packet ID and the destination address.
  310. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  311. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  312. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  313. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  314. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  315. }
  316. /**
  317. * Get this fragment's destination
  318. *
  319. * @return Destination ZT address
  320. */
  321. ZT_ALWAYS_INLINE Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  322. /**
  323. * @return True if fragment is of a valid length
  324. */
  325. ZT_ALWAYS_INLINE bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  326. /**
  327. * @return ID of packet this is a fragment of
  328. */
  329. ZT_ALWAYS_INLINE uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  330. /**
  331. * @return Total number of fragments in packet
  332. */
  333. ZT_ALWAYS_INLINE unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  334. /**
  335. * @return Fragment number of this fragment
  336. */
  337. ZT_ALWAYS_INLINE unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  338. /**
  339. * @return Fragment ZT hop count
  340. */
  341. ZT_ALWAYS_INLINE unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  342. /**
  343. * Increment this packet's hop count
  344. */
  345. ZT_ALWAYS_INLINE unsigned int incrementHops()
  346. {
  347. return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1));
  348. }
  349. /**
  350. * @return Length of payload in bytes
  351. */
  352. ZT_ALWAYS_INLINE unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  353. /**
  354. * @return Raw packet payload
  355. */
  356. ZT_ALWAYS_INLINE const unsigned char *payload() const { return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  357. };
  358. /**
  359. * ZeroTier protocol verbs
  360. */
  361. enum Verb /* Max value: 32 (5 bits) */
  362. {
  363. /**
  364. * No operation (ignored, no reply)
  365. */
  366. VERB_NOP = 0x00,
  367. /**
  368. * Announcement of a node's existence and vitals:
  369. * <[1] protocol version>
  370. * <[1] software major version>
  371. * <[1] software minor version>
  372. * <[2] software revision>
  373. * <[8] timestamp for determining latency>
  374. * <[...] binary serialized identity (see Identity)>
  375. * <[...] physical destination address of packet>
  376. *
  377. * HELLO is sent in the clear as it is how peers share their identity
  378. * public keys.
  379. *
  380. * Destination address is the actual wire address to which the packet
  381. * was sent. See InetAddress::serialize() for format.
  382. *
  383. * OK payload:
  384. * <[8] HELLO timestamp field echo>
  385. * <[1] protocol version>
  386. * <[1] software major version>
  387. * <[1] software minor version>
  388. * <[2] software revision>
  389. * <[...] physical destination address of packet>
  390. *
  391. * With the exception of the timestamp, the other fields pertain to the
  392. * respondent who is sending OK and are not echoes.
  393. *
  394. * ERROR has no payload.
  395. */
  396. VERB_HELLO = 0x01,
  397. /**
  398. * Error response:
  399. * <[1] in-re verb>
  400. * <[8] in-re packet ID>
  401. * <[1] error code>
  402. * <[...] error-dependent payload>
  403. *
  404. * If this is not in response to a single packet then verb can be
  405. * NOP and packet ID can be zero.
  406. */
  407. VERB_ERROR = 0x02,
  408. /**
  409. * Success response:
  410. * <[1] in-re verb>
  411. * <[8] in-re packet ID>
  412. * <[...] request-specific payload>
  413. */
  414. VERB_OK = 0x03,
  415. /**
  416. * Query an identity by address:
  417. * <[5] address to look up>
  418. * [<[...] additional addresses to look up>
  419. *
  420. * OK response payload:
  421. * <[...] binary serialized identity>
  422. * [<[...] additional binary serialized identities>]
  423. *
  424. * If querying a cluster, duplicate OK responses may occasionally occur.
  425. * These must be tolerated, which is easy since they'll have info you
  426. * already have.
  427. *
  428. * If the address is not found, no response is generated. The semantics
  429. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  430. * be performed.
  431. */
  432. VERB_WHOIS = 0x04,
  433. /**
  434. * Relay-mediated NAT traversal or firewall punching initiation:
  435. * <[1] flags (unused, currently 0)>
  436. * <[5] ZeroTier address of peer that might be found at this address>
  437. * <[2] 16-bit protocol address port>
  438. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  439. * <[...] protocol address (network byte order)>
  440. *
  441. * An upstream node can send this to inform both sides of a relay of
  442. * information they might use to establish a direct connection.
  443. *
  444. * Upon receipt a peer sends HELLO to establish a direct link.
  445. *
  446. * No OK or ERROR is generated.
  447. */
  448. VERB_RENDEZVOUS = 0x05,
  449. /**
  450. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  451. * <[8] 64-bit network ID>
  452. * <[2] 16-bit ethertype>
  453. * <[...] ethernet payload>
  454. *
  455. * MAC addresses are derived from the packet's source and destination
  456. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  457. * Ethernet framing and other optional flags and features when they
  458. * are not necessary.
  459. *
  460. * ERROR may be generated if a membership certificate is needed for a
  461. * closed network. Payload will be network ID.
  462. */
  463. VERB_FRAME = 0x06,
  464. /**
  465. * Full Ethernet frame with MAC addressing and optional fields:
  466. * <[8] 64-bit network ID>
  467. * <[1] flags>
  468. * <[6] destination MAC or all zero for destination node>
  469. * <[6] source MAC or all zero for node of origin>
  470. * <[2] 16-bit ethertype>
  471. * <[...] ethernet payload>
  472. *
  473. * Flags:
  474. * 0x01 - Certificate of network membership attached (DEPRECATED)
  475. * 0x02 - Most significant bit of subtype (see below)
  476. * 0x04 - Middle bit of subtype (see below)
  477. * 0x08 - Least significant bit of subtype (see below)
  478. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  479. *
  480. * Subtypes (0..7):
  481. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  482. * 0x1 - TEEd outbound frame
  483. * 0x2 - REDIRECTed outbound frame
  484. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  485. * 0x4 - TEEd inbound frame
  486. * 0x5 - REDIRECTed inbound frame
  487. * 0x6 - WATCHed inbound frame
  488. * 0x7 - (reserved for future use)
  489. *
  490. * An extended frame carries full MAC addressing, making it a
  491. * superset of VERB_FRAME. It is used for bridged traffic,
  492. * redirected or observed traffic via rules, and can in theory
  493. * be used for multicast though MULTICAST_FRAME exists for that
  494. * purpose and has additional options and capabilities.
  495. *
  496. * OK payload (if ACK flag is set):
  497. * <[8] 64-bit network ID>
  498. */
  499. VERB_EXT_FRAME = 0x07,
  500. /**
  501. * ECHO request (a.k.a. ping):
  502. * <[...] arbitrary payload>
  503. *
  504. * This generates OK with a copy of the transmitted payload. No ERROR
  505. * is generated. Response to ECHO requests is optional and ECHO may be
  506. * ignored if a node detects a possible flood.
  507. */
  508. VERB_ECHO = 0x08,
  509. /**
  510. * Announce interest in multicast group(s):
  511. * <[8] 64-bit network ID>
  512. * <[6] multicast Ethernet address>
  513. * <[4] multicast additional distinguishing information (ADI)>
  514. * [... additional tuples of network/address/adi ...]
  515. *
  516. * OK/ERROR are not generated.
  517. */
  518. VERB_MULTICAST_LIKE = 0x09,
  519. /**
  520. * Network credentials push:
  521. * [<[...] one or more certificates of membership>]
  522. * <[1] 0x00, null byte marking end of COM array>
  523. * <[2] 16-bit number of capabilities>
  524. * <[...] one or more serialized Capability>
  525. * <[2] 16-bit number of tags>
  526. * <[...] one or more serialized Tags>
  527. * <[2] 16-bit number of revocations>
  528. * <[...] one or more serialized Revocations>
  529. * <[2] 16-bit number of certificates of ownership>
  530. * <[...] one or more serialized CertificateOfOwnership>
  531. *
  532. * This can be sent by anyone at any time to push network credentials.
  533. * These will of course only be accepted if they are properly signed.
  534. * Credentials can be for any number of networks.
  535. *
  536. * The use of a zero byte to terminate the COM section is for legacy
  537. * backward compatibility. Newer fields are prefixed with a length.
  538. *
  539. * OK/ERROR are not generated.
  540. */
  541. VERB_NETWORK_CREDENTIALS = 0x0a,
  542. /**
  543. * Network configuration request:
  544. * <[8] 64-bit network ID>
  545. * <[2] 16-bit length of request meta-data dictionary>
  546. * <[...] string-serialized request meta-data>
  547. * <[8] 64-bit revision of netconf we currently have>
  548. * <[8] 64-bit timestamp of netconf we currently have>
  549. *
  550. * This message requests network configuration from a node capable of
  551. * providing it.
  552. *
  553. * Responses to this are always whole configs intended for the recipient.
  554. * For patches and other updates a NETWORK_CONFIG is sent instead.
  555. *
  556. * It would be valid and correct as of 1.2.0 to use NETWORK_CONFIG always,
  557. * but OK(NETWORK_CONFIG_REQUEST) should be sent for compatibility.
  558. *
  559. * OK response payload:
  560. * <[8] 64-bit network ID>
  561. * <[2] 16-bit length of network configuration dictionary chunk>
  562. * <[...] network configuration dictionary (may be incomplete)>
  563. * [ ... end of legacy single chunk response ... ]
  564. * <[1] 8-bit flags>
  565. * <[8] 64-bit config update ID (should never be 0)>
  566. * <[4] 32-bit total length of assembled dictionary>
  567. * <[4] 32-bit index of chunk>
  568. * [ ... end signed portion ... ]
  569. * <[1] 8-bit chunk signature type>
  570. * <[2] 16-bit length of chunk signature>
  571. * <[...] chunk signature>
  572. *
  573. * The chunk signature signs the entire payload of the OK response.
  574. * Currently only one signature type is supported: ed25519 (1).
  575. *
  576. * Each config chunk is signed to prevent memory exhaustion or
  577. * traffic crowding DOS attacks against config fragment assembly.
  578. *
  579. * If the packet is from the network controller it is permitted to end
  580. * before the config update ID or other chunking related or signature
  581. * fields. This is to support older controllers that don't include
  582. * these fields and may be removed in the future.
  583. *
  584. * ERROR response payload:
  585. * <[8] 64-bit network ID>
  586. */
  587. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  588. /**
  589. * Network configuration data push:
  590. * <[8] 64-bit network ID>
  591. * <[2] 16-bit length of network configuration dictionary chunk>
  592. * <[...] network configuration dictionary (may be incomplete)>
  593. * <[1] 8-bit flags>
  594. * <[8] 64-bit config update ID (should never be 0)>
  595. * <[4] 32-bit total length of assembled dictionary>
  596. * <[4] 32-bit index of chunk>
  597. * [ ... end signed portion ... ]
  598. * <[1] 8-bit chunk signature type>
  599. * <[2] 16-bit length of chunk signature>
  600. * <[...] chunk signature>
  601. *
  602. * This is a direct push variant for network config updates. It otherwise
  603. * carries the same payload as OK(NETWORK_CONFIG_REQUEST) and has the same
  604. * semantics.
  605. *
  606. * The legacy mode missing the additional chunking fields is not supported
  607. * here.
  608. *
  609. * Flags:
  610. * 0x01 - Use fast propagation
  611. *
  612. * An OK should be sent if the config is successfully received and
  613. * accepted.
  614. *
  615. * OK payload:
  616. * <[8] 64-bit network ID>
  617. * <[8] 64-bit config update ID>
  618. */
  619. VERB_NETWORK_CONFIG = 0x0c,
  620. /**
  621. * Request endpoints for multicast distribution:
  622. * <[8] 64-bit network ID>
  623. * <[1] flags>
  624. * <[6] MAC address of multicast group being queried>
  625. * <[4] 32-bit ADI for multicast group being queried>
  626. * <[4] 32-bit requested max number of multicast peers>
  627. * [<[...] network certificate of membership>]
  628. *
  629. * Flags:
  630. * 0x01 - COM is attached (DEPRECATED)
  631. *
  632. * More than one OK response can occur if the response is broken up across
  633. * multiple packets or if querying a clustered node.
  634. *
  635. * OK response payload:
  636. * <[8] 64-bit network ID>
  637. * <[6] MAC address of multicast group being queried>
  638. * <[4] 32-bit ADI for multicast group being queried>
  639. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  640. * <[4] 32-bit total number of known members in this multicast group>
  641. * <[2] 16-bit number of members enumerated in this packet>
  642. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  643. *
  644. * ERROR is not generated; queries that return no response are dropped.
  645. */
  646. VERB_MULTICAST_GATHER = 0x0d,
  647. /**
  648. * Multicast frame:
  649. * <[8] 64-bit network ID>
  650. * <[1] flags>
  651. * [<[4] 32-bit implicit gather limit>]
  652. * [<[6] source MAC>]
  653. * [<[2] number of explicitly specified recipients>]
  654. * [<[...] series of 5-byte explicitly specified recipients>]
  655. * <[6] destination MAC (multicast address)>
  656. * <[4] 32-bit multicast ADI (multicast address extension)>
  657. * <[2] 16-bit ethertype>
  658. * <[...] ethernet payload>
  659. *
  660. * Flags:
  661. * 0x01 - Network certificate of membership attached (DEPRECATED)
  662. * 0x02 - Implicit gather limit field is present (DEPRECATED)
  663. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  664. * 0x08 - Explicit recipient list included for P2P/HS replication
  665. *
  666. * Explicit recipient lists are used for peer to peer or hub and spoke
  667. * replication.
  668. *
  669. * OK response payload:
  670. * <[8] 64-bit network ID>
  671. * <[6] MAC address of multicast group>
  672. * <[4] 32-bit ADI for multicast group>
  673. * <[1] flags>
  674. * [<[...] network certificate of membership (DEPRECATED)>]
  675. * [<[...] implicit gather results if flag 0x01 is set>]
  676. *
  677. * OK flags (same bits as request flags):
  678. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  679. * 0x02 - OK includes implicit gather results
  680. *
  681. * ERROR response payload:
  682. * <[8] 64-bit network ID>
  683. * <[6] multicast group MAC>
  684. * <[4] 32-bit multicast group ADI>
  685. */
  686. VERB_MULTICAST_FRAME = 0x0e,
  687. /**
  688. * Push of potential endpoints for direct communication:
  689. * <[2] 16-bit number of paths>
  690. * <[...] paths>
  691. *
  692. * Path record format:
  693. * <[1] 8-bit path flags>
  694. * <[2] length of extended path characteristics or 0 for none>
  695. * <[...] extended path characteristics>
  696. * <[1] address type>
  697. * <[1] address length in bytes>
  698. * <[...] address>
  699. *
  700. * Path record flags:
  701. * 0x01 - Forget this path if currently known (not implemented yet)
  702. *
  703. * The receiver may, upon receiving a push, attempt to establish a
  704. * direct link to one or more of the indicated addresses. It is the
  705. * responsibility of the sender to limit which peers it pushes direct
  706. * paths to to those with whom it has a trust relationship. The receiver
  707. * must obey any restrictions provided such as exclusivity or blacklists.
  708. * OK responses to this message are optional.
  709. *
  710. * Note that a direct path push does not imply that learned paths can't
  711. * be used unless they are blacklisted explicitly or unless flag 0x01
  712. * is set.
  713. *
  714. * OK and ERROR are not generated.
  715. */
  716. VERB_PUSH_DIRECT_PATHS = 0x10,
  717. // 0x11 -- deprecated
  718. /**
  719. * An acknowledgment of receipt of a series of recent packets from another
  720. * peer. This is used to calculate relative throughput values and to detect
  721. * packet loss. Only VERB_FRAME and VERB_EXT_FRAME packets are counted.
  722. *
  723. * ACK response format:
  724. * <[4] 32-bit number of bytes received since last ACK>
  725. *
  726. * Upon receipt of this packet, the local peer will verify that the correct
  727. * number of bytes were received by the remote peer. If these values do
  728. * not agree that could be an indicator of packet loss.
  729. *
  730. * Additionally, the local peer knows the interval of time that has
  731. * elapsed since the last received ACK. With this information it can compute
  732. * a rough estimate of the current throughput.
  733. *
  734. * This is sent at a maximum rate of once per every ZT_PATH_ACK_INTERVAL
  735. */
  736. VERB_ACK = 0x12,
  737. /**
  738. * A packet containing timing measurements useful for estimating path quality.
  739. * Composed of a list of <packet ID:internal sojourn time> pairs for an
  740. * arbitrary set of recent packets. This is used to sample for latency and
  741. * packet delay variance (PDV, "jitter").
  742. *
  743. * QoS record format:
  744. *
  745. * <[8] 64-bit packet ID of previously-received packet>
  746. * <[1] 8-bit packet sojourn time>
  747. * <...repeat until end of max 1400 byte packet...>
  748. *
  749. * The number of possible records per QoS packet is: (1400 * 8) / 72 = 155
  750. * This packet should be sent very rarely (every few seconds) as it can be
  751. * somewhat large if the connection is saturated. Future versions might use
  752. * a bloom table to probabilistically determine these values in a vastly
  753. * more space-efficient manner.
  754. *
  755. * Note: The 'internal packet sojourn time' is a slight misnomer as it is a
  756. * measure of the amount of time between when a packet was received and the
  757. * egress time of its tracking QoS packet.
  758. *
  759. * This is sent at a maximum rate of once per every ZT_PATH_QOS_INTERVAL
  760. */
  761. VERB_QOS_MEASUREMENT = 0x13,
  762. /**
  763. * A message with arbitrary user-definable content:
  764. * <[8] 64-bit arbitrary message type ID>
  765. * [<[...] message payload>]
  766. *
  767. * This can be used to send arbitrary messages over VL1. It generates no
  768. * OK or ERROR and has no special semantics outside of whatever the user
  769. * (via the ZeroTier core API) chooses to give it.
  770. *
  771. * Message type IDs less than or equal to 65535 are reserved for use by
  772. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  773. * implementations.
  774. */
  775. VERB_USER_MESSAGE = 0x14,
  776. /**
  777. * A trace for remote debugging or diagnostics:
  778. * <[...] null-terminated dictionary containing trace information>
  779. * [<[...] additional null-terminated dictionaries>]
  780. *
  781. * This message contains a remote trace event. Remote trace events can
  782. * be sent to observers configured at the network level for those that
  783. * pertain directly to activity on a network, or to global observers if
  784. * locally configured.
  785. */
  786. VERB_REMOTE_TRACE = 0x15,
  787. /**
  788. * A signed locator for this node:
  789. * <[8] 64-bit flags>
  790. * <[2] 16-bit length of locator>
  791. * <[...] serialized locator>
  792. *
  793. * This message is sent in response to OK(HELLO) and can be pushed
  794. * opportunitistically. Its payload is a signed Locator object that
  795. * attests to where and how this Node may be reached. A locator can
  796. * contain static IPs/ports or other ZeroTier nodes that can be used
  797. * to reach this one.
  798. *
  799. * These Locator objects can be stored e.g. by roots in LF to publish
  800. * node reachability. Since they're signed any node can verify that
  801. * the originating node approves of their content.
  802. */
  803. VERB_SET_LOCATOR = 0x16,
  804. /**
  805. * A list of peers this node will relay traffic to/from:
  806. * <[2] 16-bit number of peers>
  807. * <[16] 128-bit hash of node public key>
  808. * <[2] 16-bit latency to node or 0 if unspecified>
  809. * <[4] 32-bit max bandwidth in megabits or 0 if unspecified>
  810. * [<[...] additional hash,latency,bandwidth tuples>]
  811. *
  812. * This messages can be pushed to indicate that this peer is willing
  813. * to relay traffic to other peers. It contains a list of 128-bit
  814. * hashes (the first 128 bits of a SHA512) of identity public keys
  815. * of currently reachable and willing-to-relay-for nodes.
  816. *
  817. * This can be used to initiate mesh-like behavior in ZeroTier. The
  818. * peers for which this node is willing to relay are reported as
  819. * hashes of their identity public keys. This prevents this message
  820. * from revealing explicit information about linked peers. The
  821. * receiving peer can only "see" a will-relay entry if it knows the
  822. * identity of the peer it is trying to reach.
  823. */
  824. VERB_WILL_RELAY = 0x17,
  825. /**
  826. * A push of one or more ephemeral key pairs:
  827. * <[2] 8-bit length of random padding>
  828. * <[...] random padding>
  829. * <[1] 8-bit number of keys in message>
  830. * <[1] 8-bit key type>
  831. * <[4] 32-bit max key ttl in seconds or 0 for unspecified>
  832. * <[4] 32-bit reserved field (currently always 0)>
  833. * <[...] public key (length determined by type)>
  834. * [<[...] additional keys as type, ttl, flags, key>]
  835. *
  836. * This verb is used to push ephemeral keys. A node replies to each
  837. * ephemeral key push with an OK message containing its own current
  838. * ephemeral keys that it wants to use for p2p communication.
  839. *
  840. * These are ephemeral public keys. Currently keys of type C25519
  841. * and P-384 are supported and both will be pushed.
  842. *
  843. * If more than one key is pushed, key agreement is performed using
  844. * all keys for which both peers pushed the same key type. The raw
  845. * results of these keys are then hashed together in order of key
  846. * type ID with SHA384 to yield a session key. If the desired session
  847. * key is shorter than 384 bits the first N bits are used.
  848. *
  849. * The random padding component can be used to ranomize the length
  850. * of these packets so adversaries can't easily selectively block
  851. * ephemeral key exchange by exploiting a fixed packet length.
  852. *
  853. * OK response payload:
  854. * <[...] responder's keys, same format as verb payload>
  855. */
  856. VERB_EPHEMERAL_KEY = 0x18
  857. };
  858. /**
  859. * Error codes for VERB_ERROR
  860. */
  861. enum ErrorCode
  862. {
  863. /* No error, not actually used in transit */
  864. ERROR_NONE = 0x00,
  865. /* Invalid request */
  866. ERROR_INVALID_REQUEST = 0x01,
  867. /* Bad/unsupported protocol version */
  868. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  869. /* Unknown object queried */
  870. ERROR_OBJ_NOT_FOUND = 0x03,
  871. /* HELLO pushed an identity whose address is already claimed */
  872. ERROR_IDENTITY_COLLISION = 0x04,
  873. /* Verb or use case not supported/enabled by this node */
  874. ERROR_UNSUPPORTED_OPERATION = 0x05,
  875. /* Network membership certificate update needed */
  876. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  877. /* Tried to join network, but you're not a member */
  878. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  879. /* Multicasts to this group are not wanted */
  880. ERROR_UNWANTED_MULTICAST = 0x08,
  881. /* Cannot deliver a forwarded ZeroTier packet (e.g. hops exceeded, no routes) */
  882. /* Payload: <packet ID>, <destination>, <... additional packet ID / destinations> */
  883. ERROR_CANNOT_DELIVER = 0x09
  884. };
  885. template<unsigned int C2>
  886. ZT_ALWAYS_INLINE Packet(const Buffer<C2> &b) :
  887. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  888. {
  889. }
  890. ZT_ALWAYS_INLINE Packet(const void *data,unsigned int len) :
  891. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  892. {
  893. }
  894. /**
  895. * Construct a new empty packet with a unique random packet ID
  896. *
  897. * Flags and hops will be zero. Other fields and data region are undefined.
  898. * Use the header access methods (setDestination() and friends) to fill out
  899. * the header. Payload should be appended; initial size is header size.
  900. */
  901. ZT_ALWAYS_INLINE Packet() :
  902. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  903. {
  904. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  905. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  906. }
  907. /**
  908. * Make a copy of a packet with a new initialization vector and destination address
  909. *
  910. * This can be used to take one draft prototype packet and quickly make copies to
  911. * encrypt for different destinations.
  912. *
  913. * @param prototype Prototype packet
  914. * @param dest Destination ZeroTier address for new packet
  915. */
  916. ZT_ALWAYS_INLINE Packet(const Packet &prototype,const Address &dest) :
  917. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  918. {
  919. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  920. setDestination(dest);
  921. }
  922. /**
  923. * Construct a new empty packet with a unique random packet ID
  924. *
  925. * @param dest Destination ZT address
  926. * @param source Source ZT address
  927. * @param v Verb
  928. */
  929. ZT_ALWAYS_INLINE Packet(const Address &dest,const Address &source,const Verb v) :
  930. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  931. {
  932. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  933. setDestination(dest);
  934. setSource(source);
  935. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  936. setVerb(v);
  937. }
  938. /**
  939. * Reset this packet structure for reuse in place
  940. *
  941. * @param dest Destination ZT address
  942. * @param source Source ZT address
  943. * @param v Verb
  944. */
  945. ZT_ALWAYS_INLINE void reset(const Address &dest,const Address &source,const Verb v)
  946. {
  947. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  948. setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId());
  949. setDestination(dest);
  950. setSource(source);
  951. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  952. setVerb(v);
  953. }
  954. /**
  955. * Generate a new IV / packet ID in place
  956. *
  957. * This can be used to re-use a packet buffer multiple times to send
  958. * technically different but otherwise identical copies of the same
  959. * packet.
  960. */
  961. ZT_ALWAYS_INLINE void newInitializationVector() { setAt<uint64_t>(ZT_PACKET_IDX_IV,Packet::nextPacketId()); }
  962. /**
  963. * Set this packet's destination
  964. *
  965. * @param dest ZeroTier address of destination
  966. */
  967. ZT_ALWAYS_INLINE void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  968. /**
  969. * Set this packet's source
  970. *
  971. * @param source ZeroTier address of source
  972. */
  973. ZT_ALWAYS_INLINE void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  974. /**
  975. * Get this packet's destination
  976. *
  977. * @return Destination ZT address
  978. */
  979. ZT_ALWAYS_INLINE Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  980. /**
  981. * Get this packet's source
  982. *
  983. * @return Source ZT address
  984. */
  985. ZT_ALWAYS_INLINE Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  986. /**
  987. * @return True if packet is of valid length
  988. */
  989. ZT_ALWAYS_INLINE bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  990. /**
  991. * @return True if packet is fragmented (expect fragments)
  992. */
  993. ZT_ALWAYS_INLINE bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  994. /**
  995. * Set this packet's fragmented flag
  996. *
  997. * @param f Fragmented flag value
  998. */
  999. ZT_ALWAYS_INLINE void setFragmented(bool f)
  1000. {
  1001. if (f)
  1002. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  1003. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  1004. }
  1005. /**
  1006. * @return True if compressed (result only valid if unencrypted)
  1007. */
  1008. ZT_ALWAYS_INLINE bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  1009. /**
  1010. * @return ZeroTier forwarding hops (0 to 7)
  1011. */
  1012. ZT_ALWAYS_INLINE unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  1013. /**
  1014. * Increment this packet's hop count
  1015. */
  1016. ZT_ALWAYS_INLINE unsigned char incrementHops()
  1017. {
  1018. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1019. const unsigned char h = (b + 1) & 0x07;
  1020. b = (b & 0xf8) | h;
  1021. return (unsigned int)h;
  1022. }
  1023. /**
  1024. * @return Cipher suite selector: 0 - 7 (see #defines)
  1025. */
  1026. ZT_ALWAYS_INLINE unsigned int cipher() const
  1027. {
  1028. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  1029. }
  1030. /**
  1031. * Set this packet's cipher suite
  1032. */
  1033. ZT_ALWAYS_INLINE void setCipher(unsigned int c)
  1034. {
  1035. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1036. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  1037. }
  1038. /**
  1039. * Get the trusted path ID for this packet (only meaningful if cipher is trusted path)
  1040. *
  1041. * @return Trusted path ID (from MAC field)
  1042. */
  1043. ZT_ALWAYS_INLINE uint64_t trustedPathId() const { return at<uint64_t>(ZT_PACKET_IDX_MAC); }
  1044. /**
  1045. * Set this packet's trusted path ID and set the cipher spec to trusted path
  1046. *
  1047. * @param tpid Trusted path ID
  1048. */
  1049. ZT_ALWAYS_INLINE void setTrusted(const uint64_t tpid)
  1050. {
  1051. setCipher(ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH);
  1052. setAt(ZT_PACKET_IDX_MAC,tpid);
  1053. }
  1054. /**
  1055. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  1056. *
  1057. * Note that the least significant 3 bits of this ID will change when armor()
  1058. * is called to armor the packet for transport. This is because armor() will
  1059. * mask the last 3 bits against the send counter for QoS monitoring use prior
  1060. * to actually using the IV to encrypt and MAC the packet. Be aware of this
  1061. * when grabbing the packetId of a new packet prior to armor/send.
  1062. *
  1063. * @return Packet ID
  1064. */
  1065. ZT_ALWAYS_INLINE uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  1066. /**
  1067. * Set packet verb
  1068. *
  1069. * This also has the side-effect of clearing any verb flags, such as
  1070. * compressed, and so must only be done during packet composition.
  1071. *
  1072. * @param v New packet verb
  1073. */
  1074. ZT_ALWAYS_INLINE void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  1075. /**
  1076. * @return Packet verb (not including flag bits)
  1077. */
  1078. ZT_ALWAYS_INLINE Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  1079. /**
  1080. * @return Length of packet payload
  1081. */
  1082. ZT_ALWAYS_INLINE unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1083. /**
  1084. * @return Raw packet payload
  1085. */
  1086. ZT_ALWAYS_INLINE const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1087. /**
  1088. * Armor packet for transport
  1089. *
  1090. * @param key 32-byte key
  1091. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1092. */
  1093. void armor(const void *key,bool encryptPayload);
  1094. /**
  1095. * Verify and (if encrypted) decrypt packet
  1096. *
  1097. * This does not handle trusted path mode packets and will return false
  1098. * for these. These are handled in IncomingPacket if the sending physical
  1099. * address and MAC field match a trusted path.
  1100. *
  1101. * @param key 32-byte key
  1102. * @return False if packet is invalid or failed MAC authenticity check
  1103. */
  1104. bool dearmor(const void *key);
  1105. /**
  1106. * Attempt to compress payload if not already (must be unencrypted)
  1107. *
  1108. * This requires that the payload at least contain the verb byte already
  1109. * set. The compressed flag in the verb is set if compression successfully
  1110. * results in a size reduction. If no size reduction occurs, compression
  1111. * is not done and the flag is left cleared.
  1112. *
  1113. * @return True if compression occurred
  1114. */
  1115. bool compress();
  1116. /**
  1117. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1118. *
  1119. * If payload is compressed, it is decompressed and the compressed verb
  1120. * flag is cleared. Otherwise nothing is done and true is returned.
  1121. *
  1122. * @return True if data is now decompressed and valid, false on error
  1123. */
  1124. bool uncompress();
  1125. private:
  1126. static const unsigned char ZERO_KEY[32];
  1127. static uint64_t nextPacketId();
  1128. /**
  1129. * Deterministically mangle a 256-bit crypto key based on packet
  1130. *
  1131. * This uses extra data from the packet to mangle the secret, giving us an
  1132. * effective IV that is somewhat more than 64 bits. This is "free" for
  1133. * Salsa20 since it has negligible key setup time so using a different
  1134. * key each time is fine.
  1135. *
  1136. * @param in Input key (32 bytes)
  1137. * @param out Output buffer (32 bytes)
  1138. */
  1139. ZT_ALWAYS_INLINE void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1140. {
  1141. const unsigned char *d = (const unsigned char *)data();
  1142. // IV and source/destination addresses. Using the addresses divides the
  1143. // key space into two halves-- A->B and B->A (since order will change).
  1144. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1145. out[i] = in[i] ^ d[i];
  1146. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1147. // nodes. It's one of the only parts of a packet modifiable by people
  1148. // without the key.
  1149. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1150. // Raw packet size in bytes -- thus each packet size defines a new
  1151. // key space.
  1152. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1153. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1154. // Rest of raw key is used unchanged
  1155. for(unsigned int i=21;i<32;++i)
  1156. out[i] = in[i];
  1157. }
  1158. };
  1159. } // namespace ZeroTier
  1160. #endif