Packet.hpp 50 KB

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