Packet.hpp 44 KB

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