Protocol.hpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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_PROTOCOL_HPP
  14. #define ZT_PROTOCOL_HPP
  15. #include "Constants.hpp"
  16. #include "AES.hpp"
  17. #include "Salsa20.hpp"
  18. #include "Poly1305.hpp"
  19. #include "LZ4.hpp"
  20. #include "Buf.hpp"
  21. #include "Address.hpp"
  22. #include "Identity.hpp"
  23. // TODO: mlock
  24. /*
  25. * Core ZeroTier protocol packet formats ------------------------------------------------------------------------------
  26. *
  27. * Packet format:
  28. * <[8] 64-bit packet ID / crypto IV>
  29. * <[5] destination ZT address>
  30. * <[5] source ZT address>
  31. * <[1] outer visible flags, cipher, and hop count (bits: FFCCHHH)>
  32. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  33. * [... -- begin encryption envelope -- ...]
  34. * <[1] inner envelope flags (MS 3 bits) and verb (LS 5 bits)>
  35. * [... verb-specific payload ...]
  36. *
  37. * Packets smaller than 28 bytes are invalid and silently discarded.
  38. *
  39. * The hop count field is masked during message authentication computation
  40. * and is thus the only field that is mutable in transit. It's incremented
  41. * when roots or other nodes forward packets and exists to prevent infinite
  42. * forwarding loops and to detect direct paths.
  43. *
  44. * HELLO is normally sent in the clear with the POLY1305_NONE cipher suite
  45. * and with Poly1305 computed on plain text (Salsa20/12 is still used to
  46. * generate a one time use Poly1305 key). As of protocol version 11 HELLO
  47. * also includes a terminating HMAC (last 48 bytes) that significantly
  48. * hardens HELLO authentication beyond what a 64-bit MAC can guarantee.
  49. *
  50. * Fragmented packets begin with a packet header whose fragment bit (bit
  51. * 0x40 in the flags field) is set. This constitutes fragment zero. The
  52. * total number of expected fragments is contained in each subsequent
  53. * fragment packet. Unfragmented packets must not have the fragment bit
  54. * set or the receiver will expect at least one additional fragment.
  55. *
  56. * --
  57. *
  58. * Packet fragment format (fragments beyond 0):
  59. * <[8] packet ID of packet to which this fragment belongs>
  60. * <[5] destination ZT address>
  61. * <[1] 0xff here signals that this is a fragment>
  62. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  63. * <[1] ZT hop count (least significant 3 bits; others are reserved)>
  64. * <[...] fragment data>
  65. *
  66. * The protocol supports a maximum of 16 fragments including fragment 0
  67. * which contains the full packet header (with fragment bit set). Fragments
  68. * thus always carry fragment numbers between 1 and 15. All fragments
  69. * belonging to the same packet must carry the same total fragment count in
  70. * the most significant 4 bits of the fragment numbering field.
  71. *
  72. * All fragments have the same packet ID and destination. The packet ID
  73. * doubles as the grouping identifier for fragment reassembly.
  74. *
  75. * Fragments do not carry their own packet MAC. The entire packet is
  76. * authenticated once it is assembled by the receiver. Incomplete packets
  77. * are discarded after a receiver configured period of time.
  78. *
  79. * --------------------------------------------------------------------------------------------------------------------
  80. */
  81. /*
  82. * Protocol versions
  83. *
  84. * 1 - 0.2.0 ... 0.2.5
  85. * 2 - 0.3.0 ... 0.4.5
  86. * + Added signature and originating peer to multicast frame
  87. * + Double size of multicast frame bloom filter
  88. * 3 - 0.5.0 ... 0.6.0
  89. * + Yet another multicast redesign
  90. * + New crypto completely changes key agreement cipher
  91. * 4 - 0.6.0 ... 1.0.6
  92. * + BREAKING CHANGE: New identity format based on hashcash design
  93. * 5 - 1.1.0 ... 1.1.5
  94. * + Supports echo
  95. * + Supports in-band world (root server definition) updates
  96. * + Clustering! (Though this will work with protocol v4 clients.)
  97. * + Otherwise backward compatible with protocol v4
  98. * 6 - 1.1.5 ... 1.1.10
  99. * + Network configuration format revisions including binary values
  100. * 7 - 1.1.10 ... 1.1.17
  101. * + Introduce trusted paths for local SDN use
  102. * 8 - 1.1.17 ... 1.2.0
  103. * + Multipart network configurations for large network configs
  104. * + Tags and Capabilities
  105. * + inline push of CertificateOfMembership deprecated
  106. * 9 - 1.2.0 ... 1.2.14
  107. * 10 - 1.4.0 ... 1.4.6
  108. * + Contained early pre-alpha versions of multipath, which are deprecated
  109. * 11 - 2.0.0 ... CURRENT
  110. * + New more WAN-efficient P2P-assisted multicast algorithm
  111. * + HELLO and OK(HELLO) include an extra HMAC to harden authentication
  112. * + HELLO and OK(HELLO) can carry structured meta-data
  113. * + Ephemeral keys for forward secrecy and limited key lifetime
  114. * + Old planet/moon stuff is DEAD! Independent roots are easier.
  115. * + AES encryption is now the default
  116. * + New combined Curve25519/NIST P-384 identity type (type 1)
  117. * + Short probe packets to reduce probe bandwidth
  118. * + Aggressive NAT traversal techniques for IPv4 symmetric NATs
  119. * + Remote diagnostics including rewrite of remote tracing
  120. */
  121. #define ZT_PROTO_VERSION 11
  122. /**
  123. * Minimum supported protocol version
  124. */
  125. #define ZT_PROTO_VERSION_MIN 8
  126. /**
  127. * Maximum allowed packet size (can technically be increased up to 16384)
  128. */
  129. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_MIN_UDP_MTU)
  130. /**
  131. * Minimum viable packet length (outer header + verb)
  132. */
  133. #define ZT_PROTO_MIN_PACKET_LENGTH 28
  134. /**
  135. * Index at which the encrypted section of a packet begins
  136. */
  137. #define ZT_PROTO_PACKET_ENCRYPTED_SECTION_START 27
  138. /**
  139. * Index at which packet payload begins (after verb)
  140. */
  141. #define ZT_PROTO_PACKET_PAYLOAD_START 28
  142. /**
  143. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  144. *
  145. * This is a protocol constant. It's the maximum allowed by the length
  146. * of the hop counter -- three bits. A lower limit is specified as
  147. * the actual maximum hop count.
  148. */
  149. #define ZT_PROTO_MAX_HOPS 7
  150. /**
  151. * NONE/Poly1305 (using Salsa20/12 to generate poly1305 key)
  152. */
  153. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  154. /**
  155. * Salsa2012/Poly1305
  156. */
  157. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  158. /**
  159. * No encryption or authentication at all
  160. *
  161. * For trusted paths the MAC field is the trusted path ID.
  162. */
  163. #define ZT_PROTO_CIPHER_SUITE__NONE 2
  164. /**
  165. * AES-GCM-NRH (AES-GCM with nonce reuse hardening) w/AES-256
  166. */
  167. #define ZT_PROTO_CIPHER_SUITE__AES_GCM_NRH 3
  168. /**
  169. * Minimum viable length for a fragment
  170. */
  171. #define ZT_PROTO_MIN_FRAGMENT_LENGTH 16
  172. /**
  173. * Magic number indicating a fragment if present at index 13
  174. */
  175. #define ZT_PROTO_PACKET_FRAGMENT_INDICATOR 0xff
  176. /**
  177. * Index at which fragment indicator is found in fragments
  178. */
  179. #define ZT_PROTO_PACKET_FRAGMENT_INDICATOR_INDEX 13
  180. /**
  181. * Index of flags field in regular packet headers
  182. */
  183. #define ZT_PROTO_PACKET_FLAGS_INDEX 18
  184. /**
  185. * Length of a probe packet
  186. */
  187. #define ZT_PROTO_PROBE_LENGTH 8
  188. /**
  189. * Index at which packet fragment payload starts
  190. */
  191. #define ZT_PROTO_PACKET_FRAGMENT_PAYLOAD_START_AT ZT_PROTO_MIN_FRAGMENT_LENGTH
  192. /**
  193. * Header flag indicating that a packet is fragmented and more fragments should be expected
  194. */
  195. #define ZT_PROTO_FLAG_FRAGMENTED 0x40U
  196. /**
  197. * Mask for obtaining hops from the combined flags, cipher, and hops field
  198. */
  199. #define ZT_PROTO_FLAG_FIELD_HOPS_MASK 0x07U
  200. /**
  201. * Verb flag indicating payload is compressed with LZ4
  202. */
  203. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80U
  204. /**
  205. * Mask to extract just the verb from the verb field, which also includes flags
  206. */
  207. #define ZT_PROTO_VERB_MASK 0x1fU
  208. /**
  209. * Key derivation function label for the keys used with HMAC-384 in HELLO
  210. *
  211. * With the KDF the 'iter' parameter is 0 for the key used for
  212. * HMAC in HELLO and 1 for the one used in OK(HELLO).
  213. */
  214. #define ZT_PROTO_KDF_KEY_LABEL_HELLO_HMAC 'H'
  215. /**
  216. * HELLO exchange meta-data: random 128-bit identifier for each running instance
  217. */
  218. #define ZT_PROTO_HELLO_NODE_META_INSTANCE_ID "i"
  219. /**
  220. * HELLO exchange meta-data: signed locator for this node
  221. */
  222. #define ZT_PROTO_HELLO_NODE_META_LOCATOR "l"
  223. /**
  224. * HELLO exchange meta-data: ephemeral C25519 public key
  225. */
  226. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_C25519 "e0"
  227. /**
  228. * HELLO exchange meta-data: ephemeral NIST P-384 public key
  229. */
  230. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_P384 "e1"
  231. /**
  232. * HELLO exchange meta-data: address(es) of nodes to whom this node will relay
  233. */
  234. #define ZT_PROTO_HELLO_NODE_META_NEIGHBORS "wr"
  235. /**
  236. * HELLO exchange meta-data: X coordinate of your node (sent in OK(HELLO))
  237. */
  238. #define ZT_PROTO_HELLO_NODE_META_LOCATION_X "gX"
  239. /**
  240. * HELLO exchange meta-data: Y coordinate of your node (sent in OK(HELLO))
  241. */
  242. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Y "gY"
  243. /**
  244. * HELLO exchange meta-data: Z coordinate of your node (sent in OK(HELLO))
  245. */
  246. #define ZT_PROTO_HELLO_NODE_META_LOCATION_Z "gZ"
  247. /**
  248. * HELLO exchange meta-data: preferred cipher suite (may be ignored)
  249. */
  250. #define ZT_PROTO_HELLO_NODE_META_PREFERRED_CIPHER_SUITE "c"
  251. namespace ZeroTier {
  252. namespace Protocol {
  253. /**
  254. * Packet verb (message type)
  255. */
  256. enum Verb
  257. {
  258. /**
  259. * No operation
  260. *
  261. * This packet does nothing, but it is sometimes sent as a probe to
  262. * trigger a HELLO exchange as the code will attempt HELLO when it
  263. * receives a packet from an unidentified source.
  264. */
  265. VERB_NOP = 0x00,
  266. /**
  267. * Announcement of a node's existence and vitals:
  268. * <[1] protocol version>
  269. * <[1] software major version (LEGACY)>
  270. * <[1] software minor version (LEGACY)>
  271. * <[2] software revision (LEGACY)>
  272. * <[8] timestamp for determining latency (LEGACY)>
  273. * <[...] binary serialized identity>
  274. * <[...] physical destination address of packet (LEGACY)>
  275. * <[2] 16-bit reserved "encrypted zero" field (LEGACY)>
  276. * <[...] encrypted dictionary>
  277. * <[2] 16-bit length of preceding encrypted dictionary>
  278. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  279. *
  280. * HELLO is sent to initiate a new pairing between two nodes.
  281. *
  282. * HELLO is the only packet ever sent without normal payload encryption,
  283. * though an inner encrypted envelope exists to obscure all fields that
  284. * do not need to be sent in the clear. HELLO's MAC field contains a
  285. * Poly1305 MAC for backward compatibility, and v2.x adds an additional
  286. * HMAC-SHA384 at the end for stronger authentication of sessions. HELLO
  287. * authentication is performed using the long-lived identity key only,
  288. * and the encryption of the inner dictionary field is done using a key
  289. * derived from this identity key explicitly for this purpose.
  290. *
  291. * The main payload of HELLO is the protocol version and the full identity
  292. * of the sender, which includes the sender's public key(s). An encrypted
  293. * dictionary (key/value store) is also included for additional information.
  294. * This is encrypted using AES-CTR with a derived key and using the final
  295. * 96 bits of the packet's HMAC-SHA384 as the CTR IV. (The HMAC authenticates
  296. * the packet prior to this field being encrypted, making this a SIV
  297. * construction much like AES-GMAC-SIV.)
  298. *
  299. * The length of the dictionary field is included immediately after it so
  300. * that it can be decrypted and the HMAC validated without performing any
  301. * parsing of anything else, since it's a good idea to authenticate any
  302. * message as early as possible in any secure protocol.
  303. *
  304. * V1.x will ignore the HMAC and dictionary fields as it doesn't understand
  305. * them, but the packet is constructed so that 1.x nodes will parse what
  306. * they need to communicate with 2.x nodes (without forward secrecy) as long
  307. * as we wish to support this.
  308. *
  309. * Several legacy fields are present as well for the benefit of 1.x nodes.
  310. * These will go away and become simple reserved space once 1.x is no longer
  311. * supported. Some are self-explanatory. The "encrypted zero" is rather
  312. * strange. It's a 16-bit zero value encrypted using Salsa20/12 and the
  313. * long-lived identity key shared by the two peers. It tells 1.x that an
  314. * old encrypted field is no longer there and that it should stop parsing
  315. * the packet at that point.
  316. *
  317. * The following fields are nearly always present and must exist to support
  318. * forward secrecy (in the case of the instance ID, keys, and key revision)
  319. * or federated root membership (in the case of the locator).
  320. *
  321. * TIMESTAMP - node's timestamp in milliseconds (supersedes legacy field)
  322. * INSTANCE_ID - a 64-bit unique value generated on each node start
  323. * EPHEMERAL_C25519 - an ephemeral Curve25519 public key
  324. * EPHEMERAL_P384 - an ephemeral NIST P-384 public key
  325. * EPHEMERAL_REVISION - 64-bit monotonically increasing per-instance counter
  326. * LOCATOR - signed record enumerating this node's trusted contact points
  327. *
  328. * The following optional fields may also be present:
  329. *
  330. * NAME - arbitrary short user-defined name for this node
  331. * CONTACT - arbitrary short contact information string for this node
  332. * NEIGHBORS - addresses of node(s) to whom we'll relay (mesh-like routing)
  333. * LOC_X, LOC_Y, LOC_Z - location relative to the nearest large center of mass
  334. * PEER_LOC_X, PEER_LOC_Y, PEER_LOC_Z - where sender thinks peer is located
  335. * SOFTWARE_VENDOR - short name or description of vendor, such as a URL
  336. * SOFTWARE_VERSION - major, minor, revision, and build, and 16-bit integers
  337. * PHYSICAL_DEST - serialized Endpoint to which this message was sent
  338. * VIRTUAL_DEST - ZeroTier address of first hop (if first hop wasn't destination)
  339. * COMPLIANCE - bit mask containing bits for e.g. a FIPS-compliant node
  340. *
  341. * A valid and successfully authenticated HELLO will generate the following
  342. * OK response. It contains an echo of the timestamp supplied by the
  343. * initiating peer, the protocol version, and a dictionary containing
  344. * the same information about the responding peer as the originating peer
  345. * sent.
  346. *
  347. * Note that OK(HELLO) as well as HELLO itself is always sent using the long
  348. * lived identity key, not ephemeral keys. This allows ephemeral re-keying to
  349. * always succeed if one side's ephemeral keys are out of date.
  350. *
  351. * OK payload:
  352. * <[8] timestamp echoed from original HELLO>
  353. * <[1] protocol version>
  354. * <[1] software major version (LEGACY)>
  355. * <[1] software minor version (LEGACY)>
  356. * <[2] software revision (LEGACY)>
  357. * <[...] physical destination address of packet (LEGACY)>
  358. * <[2] 16-bit reserved zero field (LEGACY)>
  359. * <[...] dictionary>
  360. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  361. */
  362. VERB_HELLO = 0x01,
  363. /**
  364. * Error response:
  365. * <[1] in-re verb>
  366. * <[8] in-re packet ID>
  367. * <[1] error code>
  368. * <[...] error-dependent payload, may be empty>
  369. *
  370. * An ERROR that does not pertain to a specific packet will have its verb
  371. * set to VERB_NOP and its packet ID set to zero.
  372. */
  373. VERB_ERROR = 0x02,
  374. /**
  375. * Success response:
  376. * <[1] in-re verb>
  377. * <[8] in-re packet ID>
  378. * <[...] request-specific payload>
  379. */
  380. VERB_OK = 0x03,
  381. /**
  382. * Query an identity by address:
  383. * <[5] address to look up>
  384. * [<[...] additional addresses to look up>
  385. *
  386. * OK response payload:
  387. * <[...] identity>
  388. * <[...] locator>
  389. * [... additional identity/locator pairs]
  390. *
  391. * If the address is not found, no response is generated. The semantics
  392. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  393. * be performed.
  394. *
  395. * It is possible for an identity but a null/empty locator to be returned
  396. * if no locator is known for a node. Older versions may omit the locator.
  397. */
  398. VERB_WHOIS = 0x04,
  399. /**
  400. * Relay-mediated NAT traversal or firewall punching initiation:
  401. * <[1] flags (unused, currently 0)>
  402. * <[5] ZeroTier address of peer that might be found at this address>
  403. * <[2] 16-bit protocol address port>
  404. * <[1] protocol address length / type>
  405. * <[...] protocol address (network byte order)>
  406. *
  407. * This is sent by a third party node to inform a node of where another
  408. * may be located. These are currently only allowed from roots.
  409. *
  410. * The protocol address format differs from the standard InetAddress
  411. * encoding for legacy reasons, but it's not hard to decode. The following
  412. * values are valid for the protocol address length (type) field:
  413. *
  414. * 4 - IPv4 IP address
  415. * 16 - IPv6 IP address
  416. * 255 - Endpoint object, unmarshaled in place (port ignored)
  417. *
  418. * No OK or ERROR is generated.
  419. */
  420. VERB_RENDEZVOUS = 0x05,
  421. /**
  422. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  423. * <[8] 64-bit network ID>
  424. * <[2] 16-bit ethertype>
  425. * <[...] ethernet payload>
  426. *
  427. * MAC addresses are derived from the packet's source and destination
  428. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  429. * Ethernet framing and other optional flags and features when they
  430. * are not necessary.
  431. *
  432. * ERROR may be generated if a membership certificate is needed for a
  433. * closed network. Payload will be network ID.
  434. */
  435. VERB_FRAME = 0x06,
  436. /**
  437. * Full Ethernet frame with MAC addressing and optional fields:
  438. * <[8] 64-bit network ID>
  439. * <[1] flags>
  440. * <[6] destination MAC or all zero for destination node>
  441. * <[6] source MAC or all zero for node of origin>
  442. * <[2] 16-bit ethertype>
  443. * <[...] ethernet payload>
  444. *
  445. * Flags:
  446. * 0x01 - Certificate of network membership attached (DEPRECATED)
  447. * 0x02 - Most significant bit of subtype (see below)
  448. * 0x04 - Middle bit of subtype (see below)
  449. * 0x08 - Least significant bit of subtype (see below)
  450. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  451. *
  452. * Subtypes (0..7):
  453. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  454. * 0x1 - TEEd outbound frame
  455. * 0x2 - REDIRECTed outbound frame
  456. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  457. * 0x4 - TEEd inbound frame
  458. * 0x5 - REDIRECTed inbound frame
  459. * 0x6 - WATCHed inbound frame
  460. * 0x7 - (reserved for future use)
  461. *
  462. * An extended frame carries full MAC addressing, making it a
  463. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  464. * spoke multicast propagation is requested.
  465. *
  466. * OK payload (if ACK flag is set):
  467. * <[8] 64-bit network ID>
  468. * <[1] flags>
  469. * <[6] destination MAC or all zero for destination node>
  470. * <[6] source MAC or all zero for node of origin>
  471. * <[2] 16-bit ethertype>
  472. */
  473. VERB_EXT_FRAME = 0x07,
  474. /**
  475. * ECHO request (a.k.a. ping):
  476. * <[...] arbitrary payload>
  477. *
  478. * This generates OK with a copy of the transmitted payload. No ERROR
  479. * is generated. Response to ECHO requests is optional and ECHO may be
  480. * ignored if a node detects a possible flood.
  481. */
  482. VERB_ECHO = 0x08,
  483. /**
  484. * Announce interest in multicast group(s):
  485. * <[8] 64-bit network ID>
  486. * <[6] multicast Ethernet address>
  487. * <[4] multicast additional distinguishing information (ADI)>
  488. * [... additional tuples of network/address/adi ...]
  489. *
  490. * LIKEs may be sent to any peer, though a good implementation should
  491. * restrict them to peers on the same network they're for and to network
  492. * controllers and root servers. In the current network, root servers
  493. * will provide the service of final multicast cache.
  494. */
  495. VERB_MULTICAST_LIKE = 0x09,
  496. /**
  497. * Network credentials push:
  498. * [<[...] one or more certificates of membership>]
  499. * <[1] 0x00, null byte marking end of COM array>
  500. * <[2] 16-bit number of capabilities>
  501. * <[...] one or more serialized Capability>
  502. * <[2] 16-bit number of tags>
  503. * <[...] one or more serialized Tags>
  504. * <[2] 16-bit number of revocations>
  505. * <[...] one or more serialized Revocations>
  506. * <[2] 16-bit number of certificates of ownership>
  507. * <[...] one or more serialized CertificateOfOwnership>
  508. *
  509. * This can be sent by anyone at any time to push network credentials.
  510. * These will of course only be accepted if they are properly signed.
  511. * Credentials can be for any number of networks.
  512. *
  513. * The use of a zero byte to terminate the COM section is for legacy
  514. * backward compatibility. Newer fields are prefixed with a length.
  515. *
  516. * OK/ERROR are not generated.
  517. */
  518. VERB_NETWORK_CREDENTIALS = 0x0a,
  519. /**
  520. * Network configuration request:
  521. * <[8] 64-bit network ID>
  522. * <[2] 16-bit length of request meta-data dictionary>
  523. * <[...] string-serialized request meta-data>
  524. * <[8] 64-bit revision of netconf we currently have>
  525. * <[8] 64-bit timestamp of netconf we currently have>
  526. *
  527. * This message requests network configuration from a node capable of
  528. * providing it. Responses can be sent as OK(NETWORK_CONFIG_REQUEST)
  529. * or NETWORK_CONFIG messages. NETWORK_CONFIG can also be sent by
  530. * network controllers or other nodes unsolicited.
  531. *
  532. * OK response payload:
  533. * (same as VERB_NETWORK_CONFIG payload)
  534. *
  535. * ERROR response payload:
  536. * <[8] 64-bit network ID>
  537. */
  538. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  539. /**
  540. * Network configuration data push:
  541. * <[8] 64-bit network ID>
  542. * <[2] 16-bit length of network configuration dictionary chunk>
  543. * <[...] network configuration dictionary (may be incomplete)>
  544. * <[1] 8-bit flags>
  545. * <[8] 64-bit config update ID (should never be 0)>
  546. * <[4] 32-bit total length of assembled dictionary>
  547. * <[4] 32-bit index of chunk>
  548. * [ ... end signed portion ... ]
  549. * <[1] 8-bit reserved field (legacy)>
  550. * <[2] 16-bit length of chunk signature>
  551. * <[...] chunk signature>
  552. *
  553. * Network configurations can come from network controllers or theoretically
  554. * any other node, but each chunk must be signed by the network controller
  555. * that generated it originally. The config update ID is arbitrary and is merely
  556. * used by the receiver to group chunks. Chunk indexes must be sequential and
  557. * the total delivered chunks must yield a total network config equal to the
  558. * specified total length.
  559. *
  560. * Flags:
  561. * 0x01 - Use fast propagation -- rumor mill flood this chunk to other members
  562. *
  563. * An OK should be sent if the config is successfully received and
  564. * accepted.
  565. *
  566. * OK payload:
  567. * <[8] 64-bit network ID>
  568. * <[8] 64-bit config update ID>
  569. */
  570. VERB_NETWORK_CONFIG = 0x0c,
  571. /**
  572. * Request endpoints for multicast distribution:
  573. * <[8] 64-bit network ID>
  574. * <[1] flags>
  575. * <[6] MAC address of multicast group being queried>
  576. * <[4] 32-bit ADI for multicast group being queried>
  577. * <[4] 32-bit requested max number of multicast peers>
  578. *
  579. * This message asks a peer for additional known endpoints that have
  580. * LIKEd a given multicast group. It's sent when the sender wishes
  581. * to send multicast but does not have the desired number of recipient
  582. * peers.
  583. *
  584. * OK response payload: (multiple OKs can be generated)
  585. * <[8] 64-bit network ID>
  586. * <[6] MAC address of multicast group being queried>
  587. * <[4] 32-bit ADI for multicast group being queried>
  588. * <[4] 32-bit total number of known members in this multicast group>
  589. * <[2] 16-bit number of members enumerated in this packet>
  590. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  591. *
  592. * ERROR is not generated; queries that return no response are dropped.
  593. */
  594. VERB_MULTICAST_GATHER = 0x0d,
  595. /** *** DEPRECATED ***
  596. * Multicast frame:
  597. * <[8] 64-bit network ID>
  598. * <[1] flags>
  599. * [<[4] 32-bit implicit gather limit>]
  600. * [<[6] source MAC>]
  601. * <[6] destination MAC (multicast address)>
  602. * <[4] 32-bit multicast ADI (multicast address extension)>
  603. * <[2] 16-bit ethertype>
  604. * <[...] ethernet payload>
  605. *
  606. * Flags:
  607. * 0x01 - Network certificate of membership attached (DEPRECATED)
  608. * 0x02 - Implicit gather limit field is present
  609. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  610. * 0x08 - Please replicate (sent to multicast replicators)
  611. *
  612. * OK and ERROR responses are optional. OK may be generated if there are
  613. * implicit gather results or if the recipient wants to send its own
  614. * updated certificate of network membership to the sender. ERROR may be
  615. * generated if a certificate is needed or if multicasts to this group
  616. * are no longer wanted (multicast unsubscribe).
  617. *
  618. * OK response payload:
  619. * <[8] 64-bit network ID>
  620. * <[6] MAC address of multicast group>
  621. * <[4] 32-bit ADI for multicast group>
  622. * <[1] flags>
  623. * [<[...] network certificate of membership (DEPRECATED)>]
  624. * [<[...] implicit gather results if flag 0x01 is set>]
  625. *
  626. * OK flags (same bits as request flags):
  627. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  628. * 0x02 - OK includes implicit gather results
  629. *
  630. * ERROR response payload:
  631. * <[8] 64-bit network ID>
  632. * <[6] multicast group MAC>
  633. * <[4] 32-bit multicast group ADI>
  634. */
  635. VERB_MULTICAST_FRAME_deprecated = 0x0e,
  636. /**
  637. * Push of potential endpoints for direct communication:
  638. * <[2] 16-bit number of paths>
  639. * <[...] paths>
  640. *
  641. * Path record format:
  642. * <[1] 8-bit path flags>
  643. * <[2] length of extended path characteristics or 0 for none>
  644. * <[...] extended path characteristics>
  645. * <[1] address type>
  646. * <[1] address record length in bytes>
  647. * <[...] address>
  648. *
  649. * Path flags:
  650. * 0x01 - Sender is likely behind a symmetric NAT
  651. * 0x02 - Use BFG1024 algorithm for symmetric NAT-t if conditions met
  652. *
  653. * The receiver may, upon receiving a push, attempt to establish a
  654. * direct link to one or more of the indicated addresses. It is the
  655. * responsibility of the sender to limit which peers it pushes direct
  656. * paths to to those with whom it has a trust relationship. The receiver
  657. * must obey any restrictions provided such as exclusivity or blacklists.
  658. * OK responses to this message are optional.
  659. *
  660. * Note that a direct path push does not imply that learned paths can't
  661. * be used unless they are blacklisted explicitly or unless flag 0x01
  662. * is set.
  663. *
  664. * OK and ERROR are not generated.
  665. */
  666. VERB_PUSH_DIRECT_PATHS = 0x10,
  667. /**
  668. * A message with arbitrary user-definable content:
  669. * <[8] 64-bit arbitrary message type ID>
  670. * [<[...] message payload>]
  671. *
  672. * This can be used to send arbitrary messages over VL1. It generates no
  673. * OK or ERROR and has no special semantics outside of whatever the user
  674. * (via the ZeroTier core API) chooses to give it.
  675. *
  676. * Message type IDs less than or equal to 65535 are reserved for use by
  677. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  678. * implementations.
  679. */
  680. VERB_USER_MESSAGE = 0x14,
  681. /**
  682. * Encapsulate a ZeroTier packet for multicast distribution:
  683. * [... begin signed portion ...]
  684. * <[1] 8-bit flags>
  685. * <[5] 40-bit ZeroTier address of sender>
  686. * <[2] 16-bit length of inner payload>
  687. * <[1] inner payload verb>
  688. * <[...] inner payload data>
  689. * [... end signed portion ...]
  690. * <[2] 16-bit length of signature or 0 if un-signed>
  691. * [<[...] optional signature of multicast>]
  692. * <[...] address (min prefix) list>
  693. */
  694. VERB_MULTICAST = 0x16,
  695. /**
  696. * Encapsulate a full ZeroTier packet in another:
  697. * <[...] raw encapsulated packet>
  698. *
  699. * Encapsulation exists to enable secure relaying as opposed to the usual
  700. * "dumb" relaying. The latter is faster but secure relaying has roles
  701. * where endpoint privacy is desired. Multiply nested ENCAP packets
  702. * could allow ZeroTier to act as an onion router.
  703. *
  704. * When encapsulated packets are forwarded they do have their hop count
  705. * field incremented.
  706. */
  707. VERB_ENCAP = 0x17
  708. // protocol max: 0x1f
  709. };
  710. /**
  711. * Error codes used in ERROR packets.
  712. */
  713. enum ErrorCode
  714. {
  715. /* Invalid request */
  716. ERROR_INVALID_REQUEST = 0x01,
  717. /* Bad/unsupported protocol version */
  718. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  719. /* Unknown object queried */
  720. ERROR_OBJ_NOT_FOUND = 0x03,
  721. /* Verb or use case not supported/enabled by this node */
  722. ERROR_UNSUPPORTED_OPERATION = 0x05,
  723. /* Network access denied; updated credentials needed */
  724. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  725. /* Tried to join network, but you're not a member */
  726. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  727. /* Cannot deliver a forwarded ZeroTier packet (for any reason) */
  728. ERROR_CANNOT_DELIVER = 0x09
  729. };
  730. /**
  731. * EXT_FRAME subtypes, which are packed into three bits in the flags field.
  732. *
  733. * This allows the node to know whether this is a normal frame or one generated
  734. * by a special tee or redirect type flow rule.
  735. */
  736. enum ExtFrameSubtype
  737. {
  738. EXT_FRAME_SUBTYPE_NORMAL = 0x0,
  739. EXT_FRAME_SUBTYPE_TEE_OUTBOUND = 0x1,
  740. EXT_FRAME_SUBTYPE_REDIRECT_OUTBOUND = 0x2,
  741. EXT_FRAME_SUBTYPE_WATCH_OUTBOUND = 0x3,
  742. EXT_FRAME_SUBTYPE_TEE_INBOUND = 0x4,
  743. EXT_FRAME_SUBTYPE_REDIRECT_INBOUND = 0x5,
  744. EXT_FRAME_SUBTYPE_WATCH_INBOUND = 0x6
  745. };
  746. /**
  747. * EXT_FRAME flags
  748. */
  749. enum ExtFrameFlag
  750. {
  751. /**
  752. * A certifiate of membership was included (no longer used but still accepted)
  753. */
  754. EXT_FRAME_FLAG_COM_ATTACHED_deprecated = 0x01,
  755. // bits 0x02, 0x04, and 0x08 are occupied by the 3-bit ExtFrameSubtype value.
  756. /**
  757. * An OK(EXT_FRAME) acknowledgement was requested by the sender.
  758. */
  759. EXT_FRAME_FLAG_ACK_REQUESTED = 0x10
  760. };
  761. /**
  762. * NETWORK_CONFIG (or OK(NETWORK_CONFIG_REQUEST)) flags
  763. */
  764. enum NetworkConfigFlag
  765. {
  766. /**
  767. * Indicates that this network config chunk should be fast propagated via rumor mill flooding.
  768. */
  769. NETWORK_CONFIG_FLAG_FAST_PROPAGATE = 0x01
  770. };
  771. /****************************************************************************/
  772. /*
  773. * These are bit-packed structures for rapid parsing of packets or at least
  774. * the fixed size headers thereof. Not all packet types have these as some
  775. * are full of variable length fields are are more easily parsed through
  776. * incremental decoding.
  777. *
  778. * All fields larger than one byte are in big-endian byte order on the wire.
  779. */
  780. /**
  781. * Normal packet header
  782. *
  783. * @tparam PT Packet payload type (default: uint8_t[])
  784. */
  785. ZT_PACKED_STRUCT(struct Header
  786. {
  787. uint64_t packetId;
  788. uint8_t destination[5];
  789. uint8_t source[5];
  790. uint8_t flags;
  791. uint64_t mac;
  792. // --- begin encrypted envelope ---
  793. uint8_t verb;
  794. });
  795. /**
  796. * Packet fragment header
  797. */
  798. ZT_PACKED_STRUCT(struct FragmentHeader
  799. {
  800. uint64_t packetId;
  801. uint8_t destination[5];
  802. uint8_t fragmentIndicator; // always 0xff for fragments
  803. uint8_t counts; // total: most significant four bits, number: least significant four bits
  804. uint8_t hops; // top 5 bits unused and must be zero
  805. });
  806. ZT_PACKED_STRUCT(struct HELLO
  807. {
  808. Header h;
  809. uint8_t versionProtocol;
  810. uint8_t versionMajor;
  811. uint8_t versionMinor;
  812. uint16_t versionRev;
  813. uint64_t timestamp;
  814. });
  815. ZT_PACKED_STRUCT(struct RENDEZVOUS
  816. {
  817. Header h;
  818. uint8_t flags;
  819. uint8_t peerAddress[5];
  820. uint16_t port;
  821. uint8_t addressLength;
  822. });
  823. ZT_PACKED_STRUCT(struct FRAME
  824. {
  825. Header h;
  826. uint64_t networkId;
  827. uint16_t etherType;
  828. });
  829. ZT_PACKED_STRUCT(struct EXT_FRAME
  830. {
  831. Header h;
  832. uint64_t networkId;
  833. uint8_t flags;
  834. });
  835. ZT_PACKED_STRUCT(struct PUSH_DIRECT_PATHS
  836. {
  837. Header h;
  838. uint16_t numPaths;
  839. });
  840. ZT_PACKED_STRUCT(struct MULTICAST_LIKE
  841. {
  842. ZT_PACKED_STRUCT(struct Entry
  843. {
  844. uint64_t networkId;
  845. uint8_t mac[6];
  846. uint32_t adi;
  847. });
  848. Header h;
  849. });
  850. namespace OK {
  851. /**
  852. * OK response header
  853. *
  854. * @tparam PT OK payload type (default: uint8_t[])
  855. */
  856. ZT_PACKED_STRUCT(struct Header
  857. {
  858. Protocol::Header h;
  859. uint8_t inReVerb;
  860. uint64_t inRePacketId;
  861. });
  862. ZT_PACKED_STRUCT(struct WHOIS
  863. {
  864. OK::Header h;
  865. });
  866. ZT_PACKED_STRUCT(struct ECHO
  867. {
  868. OK::Header h;
  869. });
  870. ZT_PACKED_STRUCT(struct HELLO
  871. {
  872. OK::Header h;
  873. uint64_t timestampEcho;
  874. uint8_t versionProtocol;
  875. uint8_t versionMajor;
  876. uint8_t versionMinor;
  877. uint16_t versionRev;
  878. });
  879. ZT_PACKED_STRUCT(struct EXT_FRAME
  880. {
  881. OK::Header h;
  882. uint64_t networkId;
  883. uint8_t flags;
  884. uint8_t destMac[6];
  885. uint8_t sourceMac[6];
  886. uint16_t etherType;
  887. });
  888. ZT_PACKED_STRUCT(struct NETWORK_CONFIG
  889. {
  890. OK::Header h;
  891. uint64_t networkId;
  892. uint64_t configUpdateId;
  893. });
  894. } // namespace OK
  895. namespace ERROR {
  896. /**
  897. * Error header
  898. *
  899. * The error header comes after the packet header but before type-specific payloads.
  900. *
  901. * @tparam PT Error payload type (default: uint8_t[])
  902. */
  903. ZT_PACKED_STRUCT(struct Header
  904. {
  905. Protocol::Header h;
  906. int8_t inReVerb;
  907. uint64_t inRePacketId;
  908. uint8_t error;
  909. });
  910. ZT_PACKED_STRUCT(struct NEED_MEMBERSHIP_CERTIFICATE
  911. {
  912. ERROR::Header h;
  913. uint64_t networkId;
  914. });
  915. ZT_PACKED_STRUCT(struct UNSUPPORTED_OPERATION__NETWORK_CONFIG_REQUEST
  916. {
  917. ERROR::Header h;
  918. uint64_t networkId;
  919. });
  920. } // namespace ERROR
  921. /****************************************************************************/
  922. /**
  923. * Convenience function to pull packet ID from a raw buffer
  924. *
  925. * @param pkt Packet to read first 8 bytes from
  926. * @param packetSize Packet's actual size in bytes
  927. * @return Packet ID or 0 if packet size is less than 8
  928. */
  929. static ZT_INLINE uint64_t packetId(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= 8) ? Utils::loadBigEndian<uint64_t>(pkt.unsafeData) : 0ULL; }
  930. /**
  931. * @param Packet to extract hops from
  932. * @param packetSize Packet's actual size in bytes
  933. * @return 3-bit hops field embedded in packet flags field
  934. */
  935. static ZT_INLINE uint8_t packetHops(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= ZT_PROTO_PACKET_FLAGS_INDEX) ? (pkt.unsafeData[ZT_PROTO_PACKET_FLAGS_INDEX] & ZT_PROTO_FLAG_FIELD_HOPS_MASK) : 0; }
  936. /**
  937. * @param Packet to extract cipher ID from
  938. * @param packetSize Packet's actual size in bytes
  939. * @return 3-bit cipher field embedded in packet flags field
  940. */
  941. static ZT_INLINE uint8_t packetCipher(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= ZT_PROTO_PACKET_FLAGS_INDEX) ? ((pkt.unsafeData[ZT_PROTO_PACKET_FLAGS_INDEX] >> 3U) & 0x07U) : 0; }
  942. /**
  943. * @return 3-bit hops field embedded in packet flags field
  944. */
  945. static ZT_INLINE uint8_t packetHops(const Header &ph) noexcept { return (ph.flags & 0x07U); }
  946. /**
  947. * @return 3-bit cipher field embedded in packet flags field
  948. */
  949. static ZT_INLINE uint8_t packetCipher(const Header &ph) noexcept { return ((ph.flags >> 3U) & 0x07U); }
  950. /**
  951. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  952. *
  953. * This uses extra data from the packet to mangle the secret, yielding when
  954. * combined with Salsa20's conventional 64-bit nonce an effective nonce that's
  955. * more like 68 bits.
  956. *
  957. * @param in Input key (32 bytes)
  958. * @param out Output buffer (32 bytes)
  959. */
  960. static ZT_INLINE void salsa2012DeriveKey(const uint8_t *const in,uint8_t *const out,const Buf &packet,const unsigned int packetSize) noexcept
  961. {
  962. // IV and source/destination addresses. Using the addresses divides the
  963. // key space into two halves-- A->B and B->A (since order will change).
  964. #ifdef ZT_NO_UNALIGNED_ACCESS
  965. for(int i=0;i<18;++i)
  966. out[i] = in[i] ^ packet.unsafeData[i];
  967. #else
  968. *reinterpret_cast<uint64_t *>(out) = *reinterpret_cast<const uint64_t *>(in) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData);
  969. *reinterpret_cast<uint64_t *>(out + 8) = *reinterpret_cast<const uint64_t *>(in + 8) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData + 8);
  970. *reinterpret_cast<uint16_t *>(out + 16) = *reinterpret_cast<const uint16_t *>(in + 16) ^ *reinterpret_cast<const uint16_t *>(packet.unsafeData + 16);
  971. #endif
  972. // Flags, but with hop count masked off. Hop count is altered by forwarding
  973. // nodes and is the only field that is mutable by unauthenticated third parties.
  974. out[18] = in[18] ^ (packet.unsafeData[18] & 0xf8U);
  975. // Raw packet size in bytes -- thus each packet size defines a new key space.
  976. out[19] = in[19] ^ (uint8_t)packetSize;
  977. out[20] = in[20] ^ (uint8_t)(packetSize >> 8U); // little endian
  978. // Rest of raw key is used unchanged
  979. #ifdef ZT_NO_UNALIGNED_ACCESS
  980. for(int i=21;i<32;++i)
  981. out[i] = in[i];
  982. #else
  983. out[21] = in[21];
  984. out[22] = in[22];
  985. out[23] = in[23];
  986. *reinterpret_cast<uint64_t *>(out + 24) = *reinterpret_cast<const uint64_t *>(in + 24);
  987. #endif
  988. }
  989. /**
  990. * Create a short probe packet for probing a recipient for e.g. NAT traversal and path setup
  991. *
  992. * @param sender Sender identity
  993. * @param recipient Recipient identity
  994. * @param key Long-term shared secret key resulting from sender and recipient agreement
  995. * @return Probe packed into 64-bit integer (in big-endian byte order)
  996. */
  997. uint64_t createProbe(const Identity &sender,const Identity &recipient,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) noexcept;
  998. // Do not use directly
  999. extern std::atomic<uint64_t> _s_packetIdCtr;
  1000. /**
  1001. * Get a packet ID (and nonce) for a new packet
  1002. *
  1003. * @return Next packet ID
  1004. */
  1005. static ZT_INLINE uint64_t getPacketId() noexcept { return ++_s_packetIdCtr; }
  1006. /**
  1007. * Encrypt and compute packet MAC
  1008. *
  1009. * @param pkt Packet data to encrypt (in place)
  1010. * @param packetSize Packet size, must be at least ZT_PROTO_MIN_PACKET_LENGTH or crash will occur
  1011. * @param key Key to use for encryption (not per-packet key)
  1012. * @param cipherSuite Cipher suite to use for AEAD encryption or just MAC
  1013. */
  1014. void armor(Buf &pkt,int packetSize,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH],uint8_t cipherSuite) noexcept;
  1015. /**
  1016. * Attempt to compress packet payload
  1017. *
  1018. * This attempts compression and swaps the pointer in 'pkt' for a buffer holding
  1019. * compressed data on success. If compression did not shrink the packet, the original
  1020. * packet size is returned and 'pkt' remains unchanged. If compression is successful
  1021. * the compressed verb flag is also set.
  1022. *
  1023. * @param pkt Packet buffer value/result parameter: pointer may be swapped if compression is successful
  1024. * @param packetSize Total size of packet in bytes (including headers)
  1025. * @return New size of packet after compression or original size of compression wasn't helpful
  1026. */
  1027. int compress(SharedPtr<Buf> &pkt,int packetSize) noexcept;
  1028. } // namespace Protocol
  1029. } // namespace ZeroTier
  1030. #endif