Packet.hpp 43 KB

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