Protocol.hpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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_KEY_C25519 "e0"
  227. /**
  228. * HELLO exchange meta-data: ephemeral NIST P-384 public key
  229. */
  230. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_KEY_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_WILL_RELAY_TO "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>
  270. * <[1] software minor version>
  271. * <[2] software revision>
  272. * <[8] timestamp for determining latency>
  273. * <[...] binary serialized identity>
  274. * <[...] physical destination address of packet>
  275. * [... begin encrypted region ...]
  276. * <[2] 16-bit reserved (legacy) field, always 0>
  277. * <[2] 16-bit length of meta-data dictionary>
  278. * <[...] meta-data dictionary>
  279. * <[2] 16-bit length of any additional fields>
  280. * [... end encrypted region ...]
  281. * <[48] HMAC-SHA384 of packet (with hops field masked to 0)>
  282. *
  283. * HELLO is sent using the POLY1305_NONE cipher setting (MAC but
  284. * no encryption) and as of protocol version 11 contains an extra
  285. * HMAC-SHA384 MAC for additional authentication hardening.
  286. *
  287. * The physical desgination address is the raw InetAddress to which the
  288. * packet was sent, regardless of any relaying used.
  289. *
  290. * HELLO packets have an encrypted section that is encrypted with
  291. * Salsa20/12 using the two peers' long-term negotiated keys and with
  292. * the packet ID (with least significant 3 bits masked to 0 for legacy
  293. * reasons) as the Salsa20/12 IV. This encryption is technically not
  294. * necessary but serves to protect the privacy of locators and other
  295. * fields for a little added defense in depth. Note to auditors: for FIPS
  296. * or other auditing purposes this crypto can be ignored as its
  297. * compromise poses no risk to peer or network authentication or transport
  298. * data privacy. HMAC is computed after this encryption is performed and
  299. * is verified before decryption is performed.
  300. *
  301. * A valid and successfully authenticated HELLO will generate the following
  302. * OK response which contains much of the same information about the
  303. * responding peer.
  304. *
  305. * OK payload:
  306. * <[8] timestamp echoed from original HELLO packet>
  307. * <[1] protocol version>
  308. * <[1] software major version>
  309. * <[1] software minor version>
  310. * <[2] software revision>
  311. * <[...] physical destination address of packet>
  312. * <[2] 16-bit reserved (legacy) field, currently must be 0>
  313. * <[2] 16-bit length of meta-data dictionary>
  314. * <[...] meta-data dictionary>
  315. * <[2] 16-bit length of any additional fields>
  316. * <[48] HMAC-SHA384 of plaintext packet (with hops masked to 0)>
  317. */
  318. VERB_HELLO = 0x01,
  319. /**
  320. * Error response:
  321. * <[1] in-re verb>
  322. * <[8] in-re packet ID>
  323. * <[1] error code>
  324. * <[...] error-dependent payload, may be empty>
  325. *
  326. * An ERROR that does not pertain to a specific packet will have its verb
  327. * set to VERB_NOP and its packet ID set to zero.
  328. */
  329. VERB_ERROR = 0x02,
  330. /**
  331. * Success response:
  332. * <[1] in-re verb>
  333. * <[8] in-re packet ID>
  334. * <[...] request-specific payload>
  335. */
  336. VERB_OK = 0x03,
  337. /**
  338. * Query an identity by address:
  339. * <[5] address to look up>
  340. * [<[...] additional addresses to look up>
  341. *
  342. * OK response payload:
  343. * <[...] identity>
  344. * <[...] locator>
  345. * [... additional identity/locator pairs]
  346. *
  347. * If the address is not found, no response is generated. The semantics
  348. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  349. * be performed.
  350. *
  351. * It is possible for an identity but a null/empty locator to be returned
  352. * if no locator is known for a node. Older versions may omit the locator.
  353. */
  354. VERB_WHOIS = 0x04,
  355. /**
  356. * Relay-mediated NAT traversal or firewall punching initiation:
  357. * <[1] flags (unused, currently 0)>
  358. * <[5] ZeroTier address of peer that might be found at this address>
  359. * <[2] 16-bit protocol address port>
  360. * <[1] protocol address length / type>
  361. * <[...] protocol address (network byte order)>
  362. *
  363. * This is sent by a third party node to inform a node of where another
  364. * may be located. These are currently only allowed from roots.
  365. *
  366. * The protocol address format differs from the standard InetAddress
  367. * encoding for legacy reasons, but it's not hard to decode. The following
  368. * values are valid for the protocol address length (type) field:
  369. *
  370. * 4 - IPv4 IP address
  371. * 16 - IPv6 IP address
  372. * 255 - Endpoint object, unmarshaled in place (port ignored)
  373. *
  374. * No OK or ERROR is generated.
  375. */
  376. VERB_RENDEZVOUS = 0x05,
  377. /**
  378. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  379. * <[8] 64-bit network ID>
  380. * <[2] 16-bit ethertype>
  381. * <[...] ethernet payload>
  382. *
  383. * MAC addresses are derived from the packet's source and destination
  384. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  385. * Ethernet framing and other optional flags and features when they
  386. * are not necessary.
  387. *
  388. * ERROR may be generated if a membership certificate is needed for a
  389. * closed network. Payload will be network ID.
  390. */
  391. VERB_FRAME = 0x06,
  392. /**
  393. * Full Ethernet frame with MAC addressing and optional fields:
  394. * <[8] 64-bit network ID>
  395. * <[1] flags>
  396. * <[6] destination MAC or all zero for destination node>
  397. * <[6] source MAC or all zero for node of origin>
  398. * <[2] 16-bit ethertype>
  399. * <[...] ethernet payload>
  400. *
  401. * Flags:
  402. * 0x01 - Certificate of network membership attached (DEPRECATED)
  403. * 0x02 - Most significant bit of subtype (see below)
  404. * 0x04 - Middle bit of subtype (see below)
  405. * 0x08 - Least significant bit of subtype (see below)
  406. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  407. *
  408. * Subtypes (0..7):
  409. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  410. * 0x1 - TEEd outbound frame
  411. * 0x2 - REDIRECTed outbound frame
  412. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  413. * 0x4 - TEEd inbound frame
  414. * 0x5 - REDIRECTed inbound frame
  415. * 0x6 - WATCHed inbound frame
  416. * 0x7 - (reserved for future use)
  417. *
  418. * An extended frame carries full MAC addressing, making it a
  419. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  420. * spoke multicast propagation is requested.
  421. *
  422. * OK payload (if ACK flag is set):
  423. * <[8] 64-bit network ID>
  424. * <[1] flags>
  425. * <[6] destination MAC or all zero for destination node>
  426. * <[6] source MAC or all zero for node of origin>
  427. * <[2] 16-bit ethertype>
  428. */
  429. VERB_EXT_FRAME = 0x07,
  430. /**
  431. * ECHO request (a.k.a. ping):
  432. * <[...] arbitrary payload>
  433. *
  434. * This generates OK with a copy of the transmitted payload. No ERROR
  435. * is generated. Response to ECHO requests is optional and ECHO may be
  436. * ignored if a node detects a possible flood.
  437. */
  438. VERB_ECHO = 0x08,
  439. /**
  440. * Announce interest in multicast group(s):
  441. * <[8] 64-bit network ID>
  442. * <[6] multicast Ethernet address>
  443. * <[4] multicast additional distinguishing information (ADI)>
  444. * [... additional tuples of network/address/adi ...]
  445. *
  446. * LIKEs may be sent to any peer, though a good implementation should
  447. * restrict them to peers on the same network they're for and to network
  448. * controllers and root servers. In the current network, root servers
  449. * will provide the service of final multicast cache.
  450. */
  451. VERB_MULTICAST_LIKE = 0x09,
  452. /**
  453. * Network credentials push:
  454. * [<[...] one or more certificates of membership>]
  455. * <[1] 0x00, null byte marking end of COM array>
  456. * <[2] 16-bit number of capabilities>
  457. * <[...] one or more serialized Capability>
  458. * <[2] 16-bit number of tags>
  459. * <[...] one or more serialized Tags>
  460. * <[2] 16-bit number of revocations>
  461. * <[...] one or more serialized Revocations>
  462. * <[2] 16-bit number of certificates of ownership>
  463. * <[...] one or more serialized CertificateOfOwnership>
  464. *
  465. * This can be sent by anyone at any time to push network credentials.
  466. * These will of course only be accepted if they are properly signed.
  467. * Credentials can be for any number of networks.
  468. *
  469. * The use of a zero byte to terminate the COM section is for legacy
  470. * backward compatibility. Newer fields are prefixed with a length.
  471. *
  472. * OK/ERROR are not generated.
  473. */
  474. VERB_NETWORK_CREDENTIALS = 0x0a,
  475. /**
  476. * Network configuration request:
  477. * <[8] 64-bit network ID>
  478. * <[2] 16-bit length of request meta-data dictionary>
  479. * <[...] string-serialized request meta-data>
  480. * <[8] 64-bit revision of netconf we currently have>
  481. * <[8] 64-bit timestamp of netconf we currently have>
  482. *
  483. * This message requests network configuration from a node capable of
  484. * providing it. Responses can be sent as OK(NETWORK_CONFIG_REQUEST)
  485. * or NETWORK_CONFIG messages. NETWORK_CONFIG can also be sent by
  486. * network controllers or other nodes unsolicited.
  487. *
  488. * OK response payload:
  489. * (same as VERB_NETWORK_CONFIG payload)
  490. *
  491. * ERROR response payload:
  492. * <[8] 64-bit network ID>
  493. */
  494. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  495. /**
  496. * Network configuration data push:
  497. * <[8] 64-bit network ID>
  498. * <[2] 16-bit length of network configuration dictionary chunk>
  499. * <[...] network configuration dictionary (may be incomplete)>
  500. * <[1] 8-bit flags>
  501. * <[8] 64-bit config update ID (should never be 0)>
  502. * <[4] 32-bit total length of assembled dictionary>
  503. * <[4] 32-bit index of chunk>
  504. * [ ... end signed portion ... ]
  505. * <[1] 8-bit reserved field (legacy)>
  506. * <[2] 16-bit length of chunk signature>
  507. * <[...] chunk signature>
  508. *
  509. * Network configurations can come from network controllers or theoretically
  510. * any other node, but each chunk must be signed by the network controller
  511. * that generated it originally. The config update ID is arbitrary and is merely
  512. * used by the receiver to group chunks. Chunk indexes must be sequential and
  513. * the total delivered chunks must yield a total network config equal to the
  514. * specified total length.
  515. *
  516. * Flags:
  517. * 0x01 - Use fast propagation -- rumor mill flood this chunk to other members
  518. *
  519. * An OK should be sent if the config is successfully received and
  520. * accepted.
  521. *
  522. * OK payload:
  523. * <[8] 64-bit network ID>
  524. * <[8] 64-bit config update ID>
  525. */
  526. VERB_NETWORK_CONFIG = 0x0c,
  527. /**
  528. * Request endpoints for multicast distribution:
  529. * <[8] 64-bit network ID>
  530. * <[1] flags>
  531. * <[6] MAC address of multicast group being queried>
  532. * <[4] 32-bit ADI for multicast group being queried>
  533. * <[4] 32-bit requested max number of multicast peers>
  534. *
  535. * This message asks a peer for additional known endpoints that have
  536. * LIKEd a given multicast group. It's sent when the sender wishes
  537. * to send multicast but does not have the desired number of recipient
  538. * peers.
  539. *
  540. * OK response payload: (multiple OKs can be generated)
  541. * <[8] 64-bit network ID>
  542. * <[6] MAC address of multicast group being queried>
  543. * <[4] 32-bit ADI for multicast group being queried>
  544. * <[4] 32-bit total number of known members in this multicast group>
  545. * <[2] 16-bit number of members enumerated in this packet>
  546. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  547. *
  548. * ERROR is not generated; queries that return no response are dropped.
  549. */
  550. VERB_MULTICAST_GATHER = 0x0d,
  551. /** *** DEPRECATED ***
  552. * Multicast frame:
  553. * <[8] 64-bit network ID>
  554. * <[1] flags>
  555. * [<[4] 32-bit implicit gather limit>]
  556. * [<[6] source MAC>]
  557. * <[6] destination MAC (multicast address)>
  558. * <[4] 32-bit multicast ADI (multicast address extension)>
  559. * <[2] 16-bit ethertype>
  560. * <[...] ethernet payload>
  561. *
  562. * Flags:
  563. * 0x01 - Network certificate of membership attached (DEPRECATED)
  564. * 0x02 - Implicit gather limit field is present
  565. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  566. * 0x08 - Please replicate (sent to multicast replicators)
  567. *
  568. * OK and ERROR responses are optional. OK may be generated if there are
  569. * implicit gather results or if the recipient wants to send its own
  570. * updated certificate of network membership to the sender. ERROR may be
  571. * generated if a certificate is needed or if multicasts to this group
  572. * are no longer wanted (multicast unsubscribe).
  573. *
  574. * OK response payload:
  575. * <[8] 64-bit network ID>
  576. * <[6] MAC address of multicast group>
  577. * <[4] 32-bit ADI for multicast group>
  578. * <[1] flags>
  579. * [<[...] network certificate of membership (DEPRECATED)>]
  580. * [<[...] implicit gather results if flag 0x01 is set>]
  581. *
  582. * OK flags (same bits as request flags):
  583. * 0x01 - OK includes certificate of network membership (DEPRECATED)
  584. * 0x02 - OK includes implicit gather results
  585. *
  586. * ERROR response payload:
  587. * <[8] 64-bit network ID>
  588. * <[6] multicast group MAC>
  589. * <[4] 32-bit multicast group ADI>
  590. */
  591. VERB_MULTICAST_FRAME_deprecated = 0x0e,
  592. /**
  593. * Push of potential endpoints for direct communication:
  594. * <[2] 16-bit number of paths>
  595. * <[...] paths>
  596. *
  597. * Path record format:
  598. * <[1] 8-bit path flags>
  599. * <[2] length of extended path characteristics or 0 for none>
  600. * <[...] extended path characteristics>
  601. * <[1] address type>
  602. * <[1] address record length in bytes>
  603. * <[...] address>
  604. *
  605. * Path flags:
  606. * 0x01 - Sender is likely behind a symmetric NAT
  607. * 0x02 - Use BFG1024 algorithm for symmetric NAT-t if conditions met
  608. *
  609. * The receiver may, upon receiving a push, attempt to establish a
  610. * direct link to one or more of the indicated addresses. It is the
  611. * responsibility of the sender to limit which peers it pushes direct
  612. * paths to to those with whom it has a trust relationship. The receiver
  613. * must obey any restrictions provided such as exclusivity or blacklists.
  614. * OK responses to this message are optional.
  615. *
  616. * Note that a direct path push does not imply that learned paths can't
  617. * be used unless they are blacklisted explicitly or unless flag 0x01
  618. * is set.
  619. *
  620. * OK and ERROR are not generated.
  621. */
  622. VERB_PUSH_DIRECT_PATHS = 0x10,
  623. /**
  624. * A message with arbitrary user-definable content:
  625. * <[8] 64-bit arbitrary message type ID>
  626. * [<[...] message payload>]
  627. *
  628. * This can be used to send arbitrary messages over VL1. It generates no
  629. * OK or ERROR and has no special semantics outside of whatever the user
  630. * (via the ZeroTier core API) chooses to give it.
  631. *
  632. * Message type IDs less than or equal to 65535 are reserved for use by
  633. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  634. * implementations.
  635. */
  636. VERB_USER_MESSAGE = 0x14,
  637. /**
  638. * Encapsulate a ZeroTier packet for multicast distribution:
  639. * [... begin signed portion ...]
  640. * <[1] 8-bit flags>
  641. * <[5] 40-bit ZeroTier address of sender>
  642. * <[2] 16-bit length of inner payload>
  643. * <[1] inner payload verb>
  644. * <[...] inner payload data>
  645. * [... end signed portion ...]
  646. * <[2] 16-bit length of signature or 0 if un-signed>
  647. * [<[...] optional signature of multicast>]
  648. * <[...] address (min prefix) list>
  649. */
  650. VERB_MULTICAST = 0x16,
  651. /**
  652. * Encapsulate a full ZeroTier packet in another:
  653. * <[...] raw encapsulated packet>
  654. *
  655. * Encapsulation exists to enable secure relaying as opposed to the usual
  656. * "dumb" relaying. The latter is faster but secure relaying has roles
  657. * where endpoint privacy is desired. Multiply nested ENCAP packets
  658. * could allow ZeroTier to act as an onion router.
  659. *
  660. * When encapsulated packets are forwarded they do have their hop count
  661. * field incremented.
  662. */
  663. VERB_ENCAP = 0x17
  664. // protocol max: 0x1f
  665. };
  666. /**
  667. * Error codes used in ERROR packets.
  668. */
  669. enum ErrorCode
  670. {
  671. /* Invalid request */
  672. ERROR_INVALID_REQUEST = 0x01,
  673. /* Bad/unsupported protocol version */
  674. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  675. /* Unknown object queried */
  676. ERROR_OBJ_NOT_FOUND = 0x03,
  677. /* Verb or use case not supported/enabled by this node */
  678. ERROR_UNSUPPORTED_OPERATION = 0x05,
  679. /* Network access denied; updated credentials needed */
  680. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  681. /* Tried to join network, but you're not a member */
  682. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  683. /* Cannot deliver a forwarded ZeroTier packet (for any reason) */
  684. ERROR_CANNOT_DELIVER = 0x09
  685. };
  686. /**
  687. * EXT_FRAME subtypes, which are packed into three bits in the flags field.
  688. *
  689. * This allows the node to know whether this is a normal frame or one generated
  690. * by a special tee or redirect type flow rule.
  691. */
  692. enum ExtFrameSubtype
  693. {
  694. EXT_FRAME_SUBTYPE_NORMAL = 0x0,
  695. EXT_FRAME_SUBTYPE_TEE_OUTBOUND = 0x1,
  696. EXT_FRAME_SUBTYPE_REDIRECT_OUTBOUND = 0x2,
  697. EXT_FRAME_SUBTYPE_WATCH_OUTBOUND = 0x3,
  698. EXT_FRAME_SUBTYPE_TEE_INBOUND = 0x4,
  699. EXT_FRAME_SUBTYPE_REDIRECT_INBOUND = 0x5,
  700. EXT_FRAME_SUBTYPE_WATCH_INBOUND = 0x6
  701. };
  702. /**
  703. * EXT_FRAME flags
  704. */
  705. enum ExtFrameFlag
  706. {
  707. /**
  708. * A certifiate of membership was included (no longer used but still accepted)
  709. */
  710. EXT_FRAME_FLAG_COM_ATTACHED_deprecated = 0x01,
  711. // bits 0x02, 0x04, and 0x08 are occupied by the 3-bit ExtFrameSubtype value.
  712. /**
  713. * An OK(EXT_FRAME) acknowledgement was requested by the sender.
  714. */
  715. EXT_FRAME_FLAG_ACK_REQUESTED = 0x10
  716. };
  717. /**
  718. * NETWORK_CONFIG (or OK(NETWORK_CONFIG_REQUEST)) flags
  719. */
  720. enum NetworkConfigFlag
  721. {
  722. /**
  723. * Indicates that this network config chunk should be fast propagated via rumor mill flooding.
  724. */
  725. NETWORK_CONFIG_FLAG_FAST_PROPAGATE = 0x01
  726. };
  727. /****************************************************************************/
  728. /*
  729. * These are bit-packed structures for rapid parsing of packets or at least
  730. * the fixed size headers thereof. Not all packet types have these as some
  731. * are full of variable length fields are are more easily parsed through
  732. * incremental decoding.
  733. *
  734. * All fields larger than one byte are in big-endian byte order on the wire.
  735. */
  736. /**
  737. * Normal packet header
  738. *
  739. * @tparam PT Packet payload type (default: uint8_t[])
  740. */
  741. ZT_PACKED_STRUCT(struct Header
  742. {
  743. uint64_t packetId;
  744. uint8_t destination[5];
  745. uint8_t source[5];
  746. uint8_t flags;
  747. uint64_t mac;
  748. // --- begin encrypted envelope ---
  749. uint8_t verb;
  750. });
  751. /**
  752. * Packet fragment header
  753. */
  754. ZT_PACKED_STRUCT(struct FragmentHeader
  755. {
  756. uint64_t packetId;
  757. uint8_t destination[5];
  758. uint8_t fragmentIndicator; // always 0xff for fragments
  759. uint8_t counts; // total: most significant four bits, number: least significant four bits
  760. uint8_t hops; // top 5 bits unused and must be zero
  761. });
  762. ZT_PACKED_STRUCT(struct HELLO
  763. {
  764. Header h;
  765. uint8_t versionProtocol;
  766. uint8_t versionMajor;
  767. uint8_t versionMinor;
  768. uint16_t versionRev;
  769. uint64_t timestamp;
  770. });
  771. ZT_PACKED_STRUCT(struct RENDEZVOUS
  772. {
  773. Header h;
  774. uint8_t flags;
  775. uint8_t peerAddress[5];
  776. uint16_t port;
  777. uint8_t addressLength;
  778. });
  779. ZT_PACKED_STRUCT(struct FRAME
  780. {
  781. Header h;
  782. uint64_t networkId;
  783. uint16_t etherType;
  784. });
  785. ZT_PACKED_STRUCT(struct EXT_FRAME
  786. {
  787. Header h;
  788. uint64_t networkId;
  789. uint8_t flags;
  790. });
  791. ZT_PACKED_STRUCT(struct PUSH_DIRECT_PATHS
  792. {
  793. Header h;
  794. uint16_t numPaths;
  795. });
  796. ZT_PACKED_STRUCT(struct MULTICAST_LIKE
  797. {
  798. ZT_PACKED_STRUCT(struct Entry
  799. {
  800. uint64_t networkId;
  801. uint8_t mac[6];
  802. uint32_t adi;
  803. });
  804. Header h;
  805. });
  806. namespace OK {
  807. /**
  808. * OK response header
  809. *
  810. * @tparam PT OK payload type (default: uint8_t[])
  811. */
  812. ZT_PACKED_STRUCT(struct Header
  813. {
  814. Protocol::Header h;
  815. uint8_t inReVerb;
  816. uint64_t inRePacketId;
  817. });
  818. ZT_PACKED_STRUCT(struct WHOIS
  819. {
  820. OK::Header h;
  821. });
  822. ZT_PACKED_STRUCT(struct ECHO
  823. {
  824. OK::Header h;
  825. });
  826. ZT_PACKED_STRUCT(struct HELLO
  827. {
  828. OK::Header h;
  829. uint64_t timestampEcho;
  830. uint8_t versionProtocol;
  831. uint8_t versionMajor;
  832. uint8_t versionMinor;
  833. uint16_t versionRev;
  834. });
  835. ZT_PACKED_STRUCT(struct EXT_FRAME
  836. {
  837. OK::Header h;
  838. uint64_t networkId;
  839. uint8_t flags;
  840. uint8_t destMac[6];
  841. uint8_t sourceMac[6];
  842. uint16_t etherType;
  843. });
  844. ZT_PACKED_STRUCT(struct NETWORK_CONFIG
  845. {
  846. OK::Header h;
  847. uint64_t networkId;
  848. uint64_t configUpdateId;
  849. });
  850. } // namespace OK
  851. namespace ERROR {
  852. /**
  853. * Error header
  854. *
  855. * The error header comes after the packet header but before type-specific payloads.
  856. *
  857. * @tparam PT Error payload type (default: uint8_t[])
  858. */
  859. ZT_PACKED_STRUCT(struct Header
  860. {
  861. Protocol::Header h;
  862. int8_t inReVerb;
  863. uint64_t inRePacketId;
  864. uint8_t error;
  865. });
  866. ZT_PACKED_STRUCT(struct NEED_MEMBERSHIP_CERTIFICATE
  867. {
  868. ERROR::Header h;
  869. uint64_t networkId;
  870. });
  871. ZT_PACKED_STRUCT(struct UNSUPPORTED_OPERATION__NETWORK_CONFIG_REQUEST
  872. {
  873. ERROR::Header h;
  874. uint64_t networkId;
  875. });
  876. } // namespace ERROR
  877. /****************************************************************************/
  878. /**
  879. * Convenience function to pull packet ID from a raw buffer
  880. *
  881. * @param pkt Packet to read first 8 bytes from
  882. * @param packetSize Packet's actual size in bytes
  883. * @return Packet ID or 0 if packet size is less than 8
  884. */
  885. static ZT_INLINE uint64_t packetId(const Buf &pkt,const unsigned int packetSize) noexcept { return (packetSize >= 8) ? Utils::loadBigEndian<uint64_t>(pkt.unsafeData) : 0ULL; }
  886. /**
  887. * @param Packet to extract hops from
  888. * @param packetSize Packet's actual size in bytes
  889. * @return 3-bit hops field embedded in packet flags field
  890. */
  891. 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; }
  892. /**
  893. * @param Packet to extract cipher ID from
  894. * @param packetSize Packet's actual size in bytes
  895. * @return 3-bit cipher field embedded in packet flags field
  896. */
  897. 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; }
  898. /**
  899. * @return 3-bit hops field embedded in packet flags field
  900. */
  901. static ZT_INLINE uint8_t packetHops(const Header &ph) noexcept { return (ph.flags & 0x07U); }
  902. /**
  903. * @return 3-bit cipher field embedded in packet flags field
  904. */
  905. static ZT_INLINE uint8_t packetCipher(const Header &ph) noexcept { return ((ph.flags >> 3U) & 0x07U); }
  906. /**
  907. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  908. *
  909. * This uses extra data from the packet to mangle the secret, yielding when
  910. * combined with Salsa20's conventional 64-bit nonce an effective nonce that's
  911. * more like 68 bits.
  912. *
  913. * @param in Input key (32 bytes)
  914. * @param out Output buffer (32 bytes)
  915. */
  916. static ZT_INLINE void salsa2012DeriveKey(const uint8_t *const in,uint8_t *const out,const Buf &packet,const unsigned int packetSize) noexcept
  917. {
  918. // IV and source/destination addresses. Using the addresses divides the
  919. // key space into two halves-- A->B and B->A (since order will change).
  920. #ifdef ZT_NO_UNALIGNED_ACCESS
  921. for(int i=0;i<18;++i)
  922. out[i] = in[i] ^ packet.unsafeData[i];
  923. #else
  924. *reinterpret_cast<uint64_t *>(out) = *reinterpret_cast<const uint64_t *>(in) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData);
  925. *reinterpret_cast<uint64_t *>(out + 8) = *reinterpret_cast<const uint64_t *>(in + 8) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData + 8);
  926. *reinterpret_cast<uint16_t *>(out + 16) = *reinterpret_cast<const uint16_t *>(in + 16) ^ *reinterpret_cast<const uint16_t *>(packet.unsafeData + 16);
  927. #endif
  928. // Flags, but with hop count masked off. Hop count is altered by forwarding
  929. // nodes and is the only field that is mutable by unauthenticated third parties.
  930. out[18] = in[18] ^ (packet.unsafeData[18] & 0xf8U);
  931. // Raw packet size in bytes -- thus each packet size defines a new key space.
  932. out[19] = in[19] ^ (uint8_t)packetSize;
  933. out[20] = in[20] ^ (uint8_t)(packetSize >> 8U); // little endian
  934. // Rest of raw key is used unchanged
  935. #ifdef ZT_NO_UNALIGNED_ACCESS
  936. for(int i=21;i<32;++i)
  937. out[i] = in[i];
  938. #else
  939. out[21] = in[21];
  940. out[22] = in[22];
  941. out[23] = in[23];
  942. *reinterpret_cast<uint64_t *>(out + 24) = *reinterpret_cast<const uint64_t *>(in + 24);
  943. #endif
  944. }
  945. /**
  946. * Create a short probe packet for probing a recipient for e.g. NAT traversal and path setup
  947. *
  948. * @param sender Sender identity
  949. * @param recipient Recipient identity
  950. * @param key Long-term shared secret key resulting from sender and recipient agreement
  951. * @return Probe packed into 64-bit integer (in big-endian byte order)
  952. */
  953. uint64_t createProbe(const Identity &sender,const Identity &recipient,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) noexcept;
  954. // Do not use directly
  955. extern std::atomic<uint64_t> _s_packetIdCtr;
  956. /**
  957. * Get a packet ID (and nonce) for a new packet
  958. *
  959. * @return Next packet ID
  960. */
  961. static ZT_INLINE uint64_t getPacketId() noexcept { return ++_s_packetIdCtr; }
  962. /**
  963. * Encrypt and compute packet MAC
  964. *
  965. * @param pkt Packet data to encrypt (in place)
  966. * @param packetSize Packet size, must be at least ZT_PROTO_MIN_PACKET_LENGTH or crash will occur
  967. * @param key Key to use for encryption (not per-packet key)
  968. * @param cipherSuite Cipher suite to use for AEAD encryption or just MAC
  969. */
  970. void armor(Buf &pkt,int packetSize,const uint8_t key[ZT_PEER_SECRET_KEY_LENGTH],uint8_t cipherSuite) noexcept;
  971. /**
  972. * Attempt to compress packet payload
  973. *
  974. * This attempts compression and swaps the pointer in 'pkt' for a buffer holding
  975. * compressed data on success. If compression did not shrink the packet, the original
  976. * packet size is returned and 'pkt' remains unchanged. If compression is successful
  977. * the compressed verb flag is also set.
  978. *
  979. * @param pkt Packet buffer value/result parameter: pointer may be swapped if compression is successful
  980. * @param packetSize Total size of packet in bytes (including headers)
  981. * @return New size of packet after compression or original size of compression wasn't helpful
  982. */
  983. int compress(SharedPtr<Buf> &pkt,int packetSize) noexcept;
  984. } // namespace Protocol
  985. } // namespace ZeroTier
  986. #endif