Protocol.hpp 34 KB

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