Packet.hpp 45 KB

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