Packet.hpp 46 KB

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