Packet.hpp 46 KB

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