Packet.hpp 43 KB

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