Packet.hpp 51 KB

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