Packet.hpp 47 KB

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