Protocol.hpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. #include "SymmetricKey.hpp"
  24. /*
  25. * Packet format:
  26. * <[8] 64-bit packet ID / crypto IV>
  27. * <[5] destination ZT address>
  28. * <[5] source ZT address>
  29. * <[1] outer visible flags, cipher, and hop count (bits: FFCCHHH)>
  30. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  31. * [... -- begin encryption envelope -- ...]
  32. * <[1] inner envelope flags (MS 3 bits) and verb (LS 5 bits)>
  33. * [... verb-specific payload ...]
  34. *
  35. * Packets smaller than 28 bytes are invalid and silently discarded.
  36. *
  37. * The hop count field is masked during message authentication computation
  38. * and is thus the only field that is mutable in transit. It's incremented
  39. * when roots or other nodes forward packets and exists to prevent infinite
  40. * forwarding loops and to detect direct paths.
  41. *
  42. * HELLO is normally sent in the clear with the POLY1305_NONE cipher suite
  43. * and with Poly1305 computed on plain text (Salsa20/12 is still used to
  44. * generate a one time use Poly1305 key). As of protocol version 11 HELLO
  45. * also includes a terminating HMAC (last 48 bytes) that significantly
  46. * hardens HELLO authentication beyond what a 64-bit MAC can guarantee.
  47. *
  48. * Fragmented packets begin with a packet header whose fragment bit (bit
  49. * 0x40 in the flags field) is set. This constitutes fragment zero. The
  50. * total number of expected fragments is contained in each subsequent
  51. * fragment packet. Unfragmented packets must not have the fragment bit
  52. * set or the receiver will expect at least one additional fragment.
  53. *
  54. * --
  55. *
  56. * Packet fragment format (fragments beyond 0):
  57. * <[8] packet ID of packet to which this fragment belongs>
  58. * <[5] destination ZT address>
  59. * <[1] 0xff here signals that this is a fragment>
  60. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  61. * <[1] ZT hop count (least significant 3 bits; others are reserved)>
  62. * <[...] fragment data>
  63. *
  64. * The protocol supports a maximum of 16 fragments including fragment 0
  65. * which contains the full packet header (with fragment bit set). Fragments
  66. * thus always carry fragment numbers between 1 and 15. All fragments
  67. * belonging to the same packet must carry the same total fragment count in
  68. * the most significant 4 bits of the fragment numbering field.
  69. *
  70. * All fragments have the same packet ID and destination. The packet ID
  71. * doubles as the grouping identifier for fragment reassembly.
  72. *
  73. * Fragments do not carry their own packet MAC. The entire packet is
  74. * authenticated once it is assembled by the receiver. Incomplete packets
  75. * are discarded after a receiver configured period of time.
  76. */
  77. /*
  78. * Protocol versions
  79. *
  80. * 1 - 0.2.0 ... 0.2.5
  81. * 2 - 0.3.0 ... 0.4.5
  82. * + Added signature and originating peer to multicast frame
  83. * + Double size of multicast frame bloom filter
  84. * 3 - 0.5.0 ... 0.6.0
  85. * + Yet another multicast redesign
  86. * + New crypto completely changes key agreement cipher
  87. * 4 - 0.6.0 ... 1.0.6
  88. * + BREAKING CHANGE: New identity format based on hashcash design
  89. * 5 - 1.1.0 ... 1.1.5
  90. * + Supports echo
  91. * + Supports in-band world (root server definition) updates
  92. * + Clustering! (Though this will work with protocol v4 clients.)
  93. * + Otherwise backward compatible with protocol v4
  94. * 6 - 1.1.5 ... 1.1.10
  95. * + Network configuration format revisions including binary values
  96. * 7 - 1.1.10 ... 1.1.17
  97. * + Introduce trusted paths for local SDN use
  98. * 8 - 1.1.17 ... 1.2.0
  99. * + Multipart network configurations for large network configs
  100. * + Tags and Capabilities
  101. * + inline push of CertificateOfMembership deprecated
  102. * 9 - 1.2.0 ... 1.2.14
  103. * 10 - 1.4.0 ... 1.4.6
  104. * + Contained early pre-alpha versions of multipath, which are deprecated
  105. * 11 - 2.0.0 ... CURRENT
  106. * + New more WAN-efficient P2P-assisted multicast algorithm
  107. * + HELLO and OK(HELLO) include an extra HMAC to harden authentication
  108. * + HELLO and OK(HELLO) carry meta-data in a dictionary that's encrypted
  109. * + Forward secrecy, key lifetime management
  110. * + Old planet/moon stuff is DEAD! Independent roots are easier.
  111. * + AES encryption with the SIV construction AES-GMAC-SIV
  112. * + New combined Curve25519/NIST P-384 identity type (type 1)
  113. * + Short probe packets to reduce probe bandwidth
  114. * + More aggressive NAT traversal techniques for IPv4 symmetric NATs
  115. */
  116. #define ZT_PROTO_VERSION 11
  117. /**
  118. * Minimum supported protocol version
  119. */
  120. #define ZT_PROTO_VERSION_MIN 8
  121. /**
  122. * Maximum allowed packet size (can technically be increased up to 16384)
  123. */
  124. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_MIN_UDP_MTU)
  125. /**
  126. * Minimum viable packet length (outer header + verb)
  127. */
  128. #define ZT_PROTO_MIN_PACKET_LENGTH 28
  129. /**
  130. * Index at which the encrypted section of a packet begins
  131. */
  132. #define ZT_PROTO_PACKET_ENCRYPTED_SECTION_START 27
  133. /**
  134. * Index at which packet payload begins (after verb)
  135. */
  136. #define ZT_PROTO_PACKET_PAYLOAD_START 28
  137. /**
  138. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  139. *
  140. * This is a protocol constant. It's the maximum allowed by the length
  141. * of the hop counter -- three bits. A lower limit is specified as
  142. * the actual maximum hop count.
  143. */
  144. #define ZT_PROTO_MAX_HOPS 7
  145. /**
  146. * NONE/Poly1305 (legacy)
  147. */
  148. #define ZT_PROTO_CIPHER_SUITE__POLY1305_NONE 0
  149. /**
  150. * Salsa2012/Poly1305 (legacy)
  151. */
  152. #define ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012 1
  153. /**
  154. * No encryption or authentication at all!
  155. *
  156. * This is used for trusted paths. The MAC field will contain the
  157. * 64-bit trusted path ID. Both sides of a link must be configured
  158. * to trust a given network with the same trusted path ID for this
  159. * to be used. It's a high performance mode designed for use on
  160. * secure LANs.
  161. */
  162. #define ZT_PROTO_CIPHER_SUITE__NONE 2
  163. /**
  164. * AES-GMAC-SIV
  165. */
  166. #define ZT_PROTO_CIPHER_SUITE__AES_GMAC_SIV 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. * Length of a probe packet
  177. */
  178. #define ZT_PROTO_PROBE_LENGTH 4
  179. /**
  180. * Index at which packet fragment payload starts
  181. */
  182. #define ZT_PROTO_PACKET_FRAGMENT_PAYLOAD_START_AT ZT_PROTO_MIN_FRAGMENT_LENGTH
  183. /**
  184. * Header flag indicating that a packet is fragmented and more fragments should be expected
  185. */
  186. #define ZT_PROTO_FLAG_FRAGMENTED 0x40U
  187. /**
  188. * Mask for obtaining hops from the combined flags, cipher, and hops field
  189. */
  190. #define ZT_PROTO_FLAG_FIELD_HOPS_MASK 0x07U
  191. /**
  192. * Verb flag indicating payload is compressed with LZ4
  193. */
  194. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80U
  195. /**
  196. * Mask to extract just the verb from the verb / verb flags field
  197. */
  198. #define ZT_PROTO_VERB_MASK 0x1fU
  199. /**
  200. * AES-GMAC-SIV first of two keys
  201. */
  202. #define ZT_KBKDF_LABEL_AES_GMAC_SIV_K0 '0'
  203. /**
  204. * AES-GMAC-SIV second of two keys
  205. */
  206. #define ZT_KBKDF_LABEL_AES_GMAC_SIV_K1 '1'
  207. /**
  208. * Key used to encrypt dictionary in HELLO with AES-CTR.
  209. */
  210. #define ZT_KBKDF_LABEL_HELLO_DICTIONARY_ENCRYPT 'H'
  211. /**
  212. * Key used for extra HMAC-SHA384 authentication on some packets.
  213. */
  214. #define ZT_KBKDF_LABEL_PACKET_HMAC 'M'
  215. #define ZT_PROTO_PACKET_FRAGMENT_INDICATOR_INDEX 13
  216. #define ZT_PROTO_PACKET_FRAGMENT_COUNTS 14
  217. #define ZT_PROTO_PACKET_ID_INDEX 0
  218. #define ZT_PROTO_PACKET_DESTINATION_INDEX 8
  219. #define ZT_PROTO_PACKET_SOURCE_INDEX 13
  220. #define ZT_PROTO_PACKET_FLAGS_INDEX 18
  221. #define ZT_PROTO_PACKET_MAC_INDEX 19
  222. #define ZT_PROTO_PACKET_VERB_INDEX 27
  223. #define ZT_PROTO_HELLO_NODE_META_INSTANCE_ID "i"
  224. #define ZT_PROTO_HELLO_NODE_META_PREFERRED_CIPHER_MODE "a"
  225. #define ZT_PROTO_HELLO_NODE_META_LOCATOR "l"
  226. #define ZT_PROTO_HELLO_NODE_META_SOFTWARE_VENDOR "s"
  227. #define ZT_PROTO_HELLO_NODE_META_COMPLIANCE "c"
  228. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_PUBLIC "e"
  229. #define ZT_PROTO_HELLO_NODE_META_EPHEMERAL_ACK "E"
  230. static_assert(ZT_PROTO_MAX_PACKET_LENGTH < ZT_BUF_MEM_SIZE,"maximum packet length won't fit in Buf");
  231. static_assert(ZT_PROTO_PACKET_ENCRYPTED_SECTION_START == (ZT_PROTO_MIN_PACKET_LENGTH-1),"encrypted packet section must start right before protocol verb at one less than minimum packet size");
  232. namespace ZeroTier {
  233. namespace Protocol {
  234. /**
  235. * Packet verb (message type)
  236. */
  237. enum Verb
  238. {
  239. /**
  240. * No operation
  241. *
  242. * This packet does nothing, but it is sometimes sent as a probe to
  243. * trigger a HELLO exchange as the code will attempt HELLO when it
  244. * receives a packet from an unidentified source.
  245. */
  246. VERB_NOP = 0x00,
  247. /**
  248. * Announcement of a node's existence and vitals:
  249. * <[1] protocol version>
  250. * <[1] software major version (optional, 0 if unspecified)>
  251. * <[1] software minor version (optional, 0 if unspecified)>
  252. * <[2] software revision (optional, 0 if unspecified)>
  253. * <[8] timestamp>
  254. * <[...] binary serialized full sender identity>
  255. * <[...] physical destination of packet>
  256. * <[12] 96-bit CTR IV>
  257. * <[6] reserved bytes, currently used for legacy compatibility>
  258. * [... start of encrypted section ...]
  259. * <[2] 16-bit length of encrypted dictionary>
  260. * <[...] encrypted dictionary>
  261. * [... end of encrypted section ...]
  262. * <[48] HMAC-SHA384 of packet>
  263. *
  264. * HELLO is sent to initiate a new pairing between two nodes and
  265. * periodically to refresh information.
  266. *
  267. * HELLO is the only packet ever sent without whole payload encryption,
  268. * though an inner encrypted envelope exists to obscure all fields that
  269. * do not need to be sent in the clear. There is nothing in this
  270. * encrypted section that would be catastrophic if it leaked, but it's
  271. * good to proactively limit exposed information.
  272. *
  273. * Inner encryption is AES-CTR with a key derived using KBKDF and a
  274. * label indicating this specific usage. A 96-bit CTR IV precedes this
  275. * encrypted section.
  276. *
  277. * Authentication and encryption in HELLO and OK(HELLO) are always done
  278. * with the long-lived identity key, not ephemeral shared keys. This
  279. * is so ephemeral key negotiation can always occur on the first try
  280. * even if things get out of sync e.g. by one side restarting. Nothing
  281. * in HELLO is likely to be dangerous if decrypted later.
  282. *
  283. * HELLO and OK(HELLO) include an extra HMAC at the end of the packet.
  284. * This authenticates them to a level of certainty beyond that afforded
  285. * by regular AEAD. HMAC is computed over the whole packet prior to
  286. * packet MAC and with the 3-bit hop count field masked as it is
  287. * with regular packet AEAD, and it is then included in the regular
  288. * packet MAC.
  289. *
  290. * LEGACY: for legacy reasons the MAC field of HELLO is a poly1305
  291. * MAC initialized in the same manner as 1.x. Since HMAC provides
  292. * additional full 384-bit strength authentication this should not be
  293. * a problem for FIPS.
  294. *
  295. * Several legacy fields are present as well for the benefit of 1.x nodes.
  296. * These will go away and become simple reserved space once 1.x is no longer
  297. * supported. Some are self-explanatory. The "encrypted zero" is rather
  298. * strange. It's a 16-bit zero value encrypted using Salsa20/12 and the
  299. * long-lived identity key shared by the two peers. It tells 1.x that an
  300. * old encrypted field is no longer there and that it should stop parsing
  301. * the packet at that point.
  302. *
  303. * 1.x does not understand the dictionary and HMAC fields, but it will
  304. * ignore them due to the "encrypted zero" field indicating that the
  305. * packet contains no more information.
  306. *
  307. * Dictionary fields (defines start with ZT_PROTO_HELLO_NODE_META_):
  308. *
  309. * INSTANCE_ID - a 64-bit unique value generated on each node start
  310. * PREFERRED_CIPHER_MODE - preferred symmetric encryption mode
  311. * LOCATOR - signed record enumerating this node's trusted contact points
  312. * EPHEMERAL_PUBLIC - Ephemeral public key(s)
  313. *
  314. * OK will contain EPHEMERAL_PUBLIC (of the sender) and:
  315. *
  316. * EPHEMERAL_ACK - SHA384 of EPHEMERAL_PUBLIC received
  317. *
  318. * The following optional fields may also be present:
  319. *
  320. * HOSTNAME - arbitrary short host name for this node
  321. * CONTACT - arbitrary short contact information string for this node
  322. * SOFTWARE_VENDOR - short name or description of vendor, such as a URL
  323. * COMPLIANCE - bit mask containing bits for e.g. a FIPS-compliant node
  324. *
  325. * The timestamp field in OK is echoed but the others represent the sender
  326. * of the OK and are not echoes from HELLO. The dictionary in OK typically
  327. * only contains the EPHEMERAL fields, allowing the receiver of the OK to
  328. * confirm that both sides know the correct keys and thus begin using the
  329. * ephemeral shared secret to send packets.
  330. *
  331. * OK is sent encrypted with the usual AEAD, but still includes a full HMAC
  332. * as well (inside the cryptographic envelope).
  333. *
  334. * OK payload:
  335. * <[8] timestamp echoed from original HELLO>
  336. * <[1] protocol version of responding node>
  337. * <[1] software major version (optional)>
  338. * <[1] software minor version (optional)>
  339. * <[2] software revision (optional)>
  340. * <[...] physical destination address of packet>
  341. * <[2] 16-bit reserved field (zero for legacy compatibility)>
  342. * <[2] 16-bit length of dictionary>
  343. * <[...] dictionary>
  344. * <[48] HMAC-SHA384 of plaintext packet>
  345. */
  346. VERB_HELLO = 0x01,
  347. /**
  348. * Error response:
  349. * <[1] in-re verb>
  350. * <[8] in-re packet ID>
  351. * <[1] error code>
  352. * <[...] error-dependent payload, may be empty>
  353. *
  354. * An ERROR that does not pertain to a specific packet will have its verb
  355. * set to VERB_NOP and its packet ID set to zero.
  356. */
  357. VERB_ERROR = 0x02,
  358. /**
  359. * Success response:
  360. * <[1] in-re verb>
  361. * <[8] in-re packet ID>
  362. * <[...] response-specific payload>
  363. */
  364. VERB_OK = 0x03,
  365. /**
  366. * Query an identity by address:
  367. * <[5] address to look up>
  368. * [<[...] additional addresses to look up>
  369. *
  370. * OK response payload:
  371. * <[...] identity>
  372. * <[...] locator>
  373. * [... additional identity/locator pairs]
  374. *
  375. * If the address is not found, no response is generated. The semantics
  376. * of WHOIS is similar to ARP and NDP in that persistent retrying can
  377. * be performed.
  378. *
  379. * It is possible for an identity but a null/empty locator to be returned
  380. * if no locator is known for a node. Older versions may omit the locator.
  381. */
  382. VERB_WHOIS = 0x04,
  383. /**
  384. * Relay-mediated NAT traversal or firewall punching initiation:
  385. * <[1] flags>
  386. * <[5] ZeroTier address of other peer>
  387. * <[2] 16-bit number of endpoints where peer might be reached>
  388. * [<[...] endpoints to attempt>]
  389. *
  390. * Legacy packet format for pre-2.x peers:
  391. * <[1] flags (unused, currently 0)>
  392. * <[5] ZeroTier address of other peer>
  393. * <[2] 16-bit protocol address port>
  394. * <[1] protocol address length / type>
  395. * <[...] protocol address (network byte order)>
  396. *
  397. * When a root or other peer is relaying messages, it can periodically send
  398. * RENDEZVOUS to assist peers in establishing direct communication.
  399. *
  400. * Peers also directly exchange information via HELLO, so this serves as
  401. * a second way for peers to learn about their possible locations.
  402. *
  403. * It also serves another function: temporal coordination of NAT traversal
  404. * attempts. Some NATs traverse better if both sides first send "firewall
  405. * opener" packets and then send real packets and if this exchange is
  406. * coordinated in time so that the packets effectively pass each other in
  407. * flight.
  408. *
  409. * No OK or ERROR is generated.
  410. */
  411. VERB_RENDEZVOUS = 0x05,
  412. /**
  413. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  414. * <[8] 64-bit network ID>
  415. * <[2] 16-bit ethertype>
  416. * <[...] ethernet payload>
  417. *
  418. * MAC addresses are derived from the packet's source and destination
  419. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  420. * Ethernet framing and other optional flags and features when they
  421. * are not necessary.
  422. *
  423. * ERROR may be generated if a membership certificate is needed for a
  424. * closed network. Payload will be network ID.
  425. */
  426. VERB_FRAME = 0x06,
  427. /**
  428. * Full Ethernet frame with MAC addressing and optional fields:
  429. * <[8] 64-bit network ID>
  430. * <[1] flags>
  431. * <[6] destination MAC or all zero for destination node>
  432. * <[6] source MAC or all zero for node of origin>
  433. * <[2] 16-bit ethertype>
  434. * <[...] ethernet payload>
  435. *
  436. * Flags:
  437. * 0x01 - Certificate of network membership attached (DEPRECATED)
  438. * 0x02 - Most significant bit of subtype (see below)
  439. * 0x04 - Middle bit of subtype (see below)
  440. * 0x08 - Least significant bit of subtype (see below)
  441. * 0x10 - ACK requested in the form of OK(EXT_FRAME)
  442. *
  443. * Subtypes (0..7):
  444. * 0x0 - Normal frame (bridging can be determined by checking MAC)
  445. * 0x1 - TEEd outbound frame
  446. * 0x2 - REDIRECTed outbound frame
  447. * 0x3 - WATCHed outbound frame (TEE with ACK, ACK bit also set)
  448. * 0x4 - TEEd inbound frame
  449. * 0x5 - REDIRECTed inbound frame
  450. * 0x6 - WATCHed inbound frame
  451. * 0x7 - (reserved for future use)
  452. *
  453. * An extended frame carries full MAC addressing, making it a
  454. * superset of VERB_FRAME. If 0x20 is set then p2p or hub and
  455. * spoke multicast propagation is requested.
  456. *
  457. * OK payload (if ACK flag is set):
  458. * <[8] 64-bit network ID>
  459. * <[1] flags>
  460. * <[6] destination MAC or all zero for destination node>
  461. * <[6] source MAC or all zero for node of origin>
  462. * <[2] 16-bit ethertype>
  463. */
  464. VERB_EXT_FRAME = 0x07,
  465. /**
  466. * ECHO request (a.k.a. ping):
  467. * <[...] arbitrary payload>
  468. *
  469. * This generates OK with a copy of the transmitted payload. No ERROR
  470. * is generated. Response to ECHO requests is optional and ECHO may be
  471. * ignored if a node detects a possible flood.
  472. */
  473. VERB_ECHO = 0x08,
  474. /**
  475. * Announce interest in multicast group(s):
  476. * <[8] 64-bit network ID>
  477. * <[6] multicast Ethernet address>
  478. * <[4] multicast additional distinguishing information (ADI)>
  479. * [... additional tuples of network/address/adi ...]
  480. *
  481. * LIKEs may be sent to any peer, though a good implementation should
  482. * restrict them to peers on the same network they're for and to network
  483. * controllers and root servers. In the current network, root servers
  484. * will provide the service of final multicast cache.
  485. */
  486. VERB_MULTICAST_LIKE = 0x09,
  487. /**
  488. * Network credentials push:
  489. * [<[...] one or more certificates of membership>]
  490. * <[1] 0x00, null byte marking end of COM array>
  491. * <[2] 16-bit number of capabilities>
  492. * <[...] one or more serialized Capability>
  493. * <[2] 16-bit number of tags>
  494. * <[...] one or more serialized Tags>
  495. * <[2] 16-bit number of revocations>
  496. * <[...] one or more serialized Revocations>
  497. * <[2] 16-bit number of certificates of ownership>
  498. * <[...] one or more serialized CertificateOfOwnership>
  499. *
  500. * This can be sent by anyone at any time to push network credentials.
  501. * These will of course only be accepted if they are properly signed.
  502. * Credentials can be for any number of networks.
  503. *
  504. * The use of a zero byte to terminate the COM section is for legacy
  505. * backward compatibility. Newer fields are prefixed with a length.
  506. *
  507. * OK/ERROR are not generated.
  508. */
  509. VERB_NETWORK_CREDENTIALS = 0x0a,
  510. /**
  511. * Network configuration request:
  512. * <[8] 64-bit network ID>
  513. * <[2] 16-bit length of request meta-data dictionary>
  514. * <[...] string-serialized request meta-data>
  515. * <[8] 64-bit revision of netconf we currently have>
  516. * <[8] 64-bit timestamp of netconf we currently have>
  517. *
  518. * This message requests network configuration from a node capable of
  519. * providing it. Responses can be sent as OK(NETWORK_CONFIG_REQUEST)
  520. * or NETWORK_CONFIG messages. NETWORK_CONFIG can also be sent by
  521. * network controllers or other nodes unsolicited.
  522. *
  523. * OK response payload:
  524. * (same as VERB_NETWORK_CONFIG payload)
  525. *
  526. * ERROR response payload:
  527. * <[8] 64-bit network ID>
  528. */
  529. VERB_NETWORK_CONFIG_REQUEST = 0x0b,
  530. /**
  531. * Network configuration data push:
  532. * <[8] 64-bit network ID>
  533. * <[2] 16-bit length of network configuration dictionary chunk>
  534. * <[...] network configuration dictionary (may be incomplete)>
  535. * <[1] 8-bit flags>
  536. * <[8] 64-bit config update ID (should never be 0)>
  537. * <[4] 32-bit total length of assembled dictionary>
  538. * <[4] 32-bit index of chunk>
  539. * [ ... end signed portion ... ]
  540. * <[1] 8-bit reserved field (legacy)>
  541. * <[2] 16-bit length of chunk signature>
  542. * <[...] chunk signature>
  543. *
  544. * Network configurations can come from network controllers or theoretically
  545. * any other node, but each chunk must be signed by the network controller
  546. * that generated it originally. The config update ID is arbitrary and is merely
  547. * used by the receiver to group chunks. Chunk indexes must be sequential and
  548. * the total delivered chunks must yield a total network config equal to the
  549. * specified total length.
  550. *
  551. * Flags:
  552. * 0x01 - Use fast propagation -- rumor mill flood this chunk to other members
  553. *
  554. * An OK should be sent if the config is successfully received and
  555. * accepted.
  556. *
  557. * OK payload:
  558. * <[8] 64-bit network ID>
  559. * <[8] 64-bit config update ID>
  560. */
  561. VERB_NETWORK_CONFIG = 0x0c,
  562. /**
  563. * Request endpoints for multicast distribution:
  564. * <[8] 64-bit network ID>
  565. * <[1] flags>
  566. * <[6] MAC address of multicast group being queried>
  567. * <[4] 32-bit ADI for multicast group being queried>
  568. * <[4] 32-bit requested max number of multicast peers>
  569. *
  570. * This message asks a peer for additional known endpoints that have
  571. * LIKEd a given multicast group. It's sent when the sender wishes
  572. * to send multicast but does not have the desired number of recipient
  573. * peers.
  574. *
  575. * OK response payload: (multiple OKs can be generated)
  576. * <[8] 64-bit network ID>
  577. * <[6] MAC address of multicast group being queried>
  578. * <[4] 32-bit ADI for multicast group being queried>
  579. * <[4] 32-bit total number of known members in this multicast group>
  580. * <[2] 16-bit number of members enumerated in this packet>
  581. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  582. *
  583. * ERROR is not generated; queries that return no response are dropped.
  584. */
  585. VERB_MULTICAST_GATHER = 0x0d,
  586. // Deprecated multicast frame message type.
  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>
  595. * <[2] length of endpoint record>
  596. * <[...] endpoint>
  597. *
  598. * The following fields are also included if the node is pre-2.x:
  599. * <[1] address type (LEGACY)>
  600. * <[1] address length in bytes (LEGACY)>
  601. * <[...] address (LEGACY)>
  602. *
  603. * Path record flags:
  604. * 0x01 - reserved (legacy)
  605. * 0x02 - reserved (legacy)
  606. * 0x04 - Symmetric NAT detected at sender side
  607. * 0x08 - Request aggressive symmetric NAT traversal
  608. *
  609. * OK and ERROR are not generated.
  610. */
  611. VERB_PUSH_DIRECT_PATHS = 0x10,
  612. /**
  613. * A message with arbitrary user-definable content:
  614. * <[8] 64-bit arbitrary message type ID>
  615. * [<[...] message payload>]
  616. *
  617. * This can be used to send arbitrary messages over VL1. It generates no
  618. * OK or ERROR and has no special semantics outside of whatever the user
  619. * (via the ZeroTier core API) chooses to give it.
  620. *
  621. * Message type IDs less than or equal to 65535 are reserved for use by
  622. * ZeroTier, Inc. itself. We recommend making up random ones for your own
  623. * implementations.
  624. */
  625. VERB_USER_MESSAGE = 0x14,
  626. VERB_MULTICAST = 0x16,
  627. /**
  628. * Encapsulate a full ZeroTier packet in another:
  629. * <[...] raw encapsulated packet>
  630. *
  631. * Encapsulation exists to enable secure relaying as opposed to the usual
  632. * "dumb" relaying. The latter is faster but secure relaying has roles
  633. * where endpoint privacy is desired.
  634. *
  635. * Packet hop count is incremented as normal.
  636. */
  637. VERB_ENCAP = 0x17
  638. // protocol max: 0x1f
  639. };
  640. #ifdef ZT_DEBUG_SPEW
  641. static ZT_INLINE const char *verbName(const Verb v) noexcept
  642. {
  643. switch(v) {
  644. case VERB_NOP: return "NOP";
  645. case VERB_HELLO: return "HELLO";
  646. case VERB_ERROR: return "ERROR";
  647. case VERB_OK: return "OK";
  648. case VERB_WHOIS: return "WHOIS";
  649. case VERB_RENDEZVOUS: return "RENDEZVOUS";
  650. case VERB_FRAME: return "FRAME";
  651. case VERB_EXT_FRAME: return "EXT_FRAME";
  652. case VERB_ECHO: return "ECHO";
  653. case VERB_MULTICAST_LIKE: return "MULTICAST_LIKE";
  654. case VERB_NETWORK_CREDENTIALS: return "NETWORK_CREDENTIALS";
  655. case VERB_NETWORK_CONFIG_REQUEST: return "NETWORK_CONFIG_REQUEST";
  656. case VERB_NETWORK_CONFIG: return "NETWORK_CONFIG";
  657. case VERB_MULTICAST_GATHER: return "MULTICAST_GATHER";
  658. case VERB_MULTICAST_FRAME_deprecated: return "MULTICAST_FRAME_deprecated";
  659. case VERB_PUSH_DIRECT_PATHS: return "PUSH_DIRECT_PATHS";
  660. case VERB_USER_MESSAGE: return "USER_MESSAGE";
  661. case VERB_MULTICAST: return "MULTICAST";
  662. case VERB_ENCAP: return "ENCAP";
  663. default: return "(unknown)";
  664. }
  665. }
  666. #endif
  667. /**
  668. * Error codes used in ERROR packets.
  669. */
  670. enum ErrorCode
  671. {
  672. /* Invalid request */
  673. ERROR_INVALID_REQUEST = 0x01,
  674. /* Bad/unsupported protocol version */
  675. ERROR_BAD_PROTOCOL_VERSION = 0x02,
  676. /* Unknown object queried */
  677. ERROR_OBJ_NOT_FOUND = 0x03,
  678. /* Verb or use case not supported/enabled by this node */
  679. ERROR_UNSUPPORTED_OPERATION = 0x05,
  680. /* Network access denied; updated credentials needed */
  681. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 0x06,
  682. /* Tried to join network, but you're not a member */
  683. ERROR_NETWORK_ACCESS_DENIED_ = 0x07, /* extra _ at end to avoid Windows name conflict */
  684. /* Cannot deliver a forwarded ZeroTier packet (for any reason) */
  685. ERROR_CANNOT_DELIVER = 0x09
  686. };
  687. /**
  688. * EXT_FRAME subtypes, which are packed into three bits in the flags field.
  689. *
  690. * This allows the node to know whether this is a normal frame or one generated
  691. * by a special tee or redirect type flow rule.
  692. */
  693. enum ExtFrameSubtype
  694. {
  695. EXT_FRAME_SUBTYPE_NORMAL = 0x0,
  696. EXT_FRAME_SUBTYPE_TEE_OUTBOUND = 0x1,
  697. EXT_FRAME_SUBTYPE_REDIRECT_OUTBOUND = 0x2,
  698. EXT_FRAME_SUBTYPE_WATCH_OUTBOUND = 0x3,
  699. EXT_FRAME_SUBTYPE_TEE_INBOUND = 0x4,
  700. EXT_FRAME_SUBTYPE_REDIRECT_INBOUND = 0x5,
  701. EXT_FRAME_SUBTYPE_WATCH_INBOUND = 0x6
  702. };
  703. /**
  704. * EXT_FRAME flags
  705. */
  706. enum ExtFrameFlag
  707. {
  708. /**
  709. * A certifiate of membership was included (no longer used but still accepted)
  710. */
  711. EXT_FRAME_FLAG_COM_ATTACHED_deprecated = 0x01,
  712. // bits 0x02, 0x04, and 0x08 are occupied by the 3-bit ExtFrameSubtype value.
  713. /**
  714. * An OK(EXT_FRAME) acknowledgement was requested by the sender.
  715. */
  716. EXT_FRAME_FLAG_ACK_REQUESTED = 0x10
  717. };
  718. /**
  719. * NETWORK_CONFIG (or OK(NETWORK_CONFIG_REQUEST)) flags
  720. */
  721. enum NetworkConfigFlag
  722. {
  723. /**
  724. * Indicates that this network config chunk should be fast propagated via rumor mill flooding.
  725. */
  726. NETWORK_CONFIG_FLAG_FAST_PROPAGATE = 0x01
  727. };
  728. /**
  729. * Deterministically mangle a 256-bit crypto key based on packet characteristics
  730. *
  731. * This uses extra data from the packet to mangle the secret, yielding when
  732. * combined with Salsa20's conventional 64-bit nonce an effective nonce that's
  733. * more like 68 bits.
  734. *
  735. * @param in Input key (32 bytes)
  736. * @param out Output buffer (32 bytes)
  737. */
  738. static ZT_INLINE void salsa2012DeriveKey(const uint8_t *const in,uint8_t *const out,const Buf &packet,const unsigned int packetSize) noexcept
  739. {
  740. // IV and source/destination addresses. Using the addresses divides the
  741. // key space into two halves-- A->B and B->A (since order will change).
  742. #ifdef ZT_NO_UNALIGNED_ACCESS
  743. for(int i=0;i<18;++i)
  744. out[i] = in[i] ^ packet.unsafeData[i];
  745. #else
  746. *reinterpret_cast<uint64_t *>(out) = *reinterpret_cast<const uint64_t *>(in) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData);
  747. *reinterpret_cast<uint64_t *>(out + 8) = *reinterpret_cast<const uint64_t *>(in + 8) ^ *reinterpret_cast<const uint64_t *>(packet.unsafeData + 8);
  748. *reinterpret_cast<uint16_t *>(out + 16) = *reinterpret_cast<const uint16_t *>(in + 16) ^ *reinterpret_cast<const uint16_t *>(packet.unsafeData + 16);
  749. #endif
  750. // Flags, but with hop count masked off. Hop count is altered by forwarding
  751. // nodes and is the only field that is mutable by unauthenticated third parties.
  752. out[18] = in[18] ^ (packet.unsafeData[18] & 0xf8U);
  753. // Raw packet size in bytes -- thus each packet size defines a new key space.
  754. out[19] = in[19] ^ (uint8_t)packetSize;
  755. out[20] = in[20] ^ (uint8_t)(packetSize >> 8U); // little endian
  756. // Rest of raw key is used unchanged
  757. #ifdef ZT_NO_UNALIGNED_ACCESS
  758. for(int i=21;i<32;++i)
  759. out[i] = in[i];
  760. #else
  761. out[21] = in[21];
  762. out[22] = in[22];
  763. out[23] = in[23];
  764. *reinterpret_cast<uint64_t *>(out + 24) = *reinterpret_cast<const uint64_t *>(in + 24);
  765. #endif
  766. }
  767. /**
  768. * Fill out packet header fields (except for mac, which is filled out by armor())
  769. *
  770. * @param pkt Start of packet buffer
  771. * @param packetId Packet IV / cryptographic MAC
  772. * @param destination Destination ZT address
  773. * @param source Source (sending) ZT address
  774. * @param verb Protocol verb
  775. * @return Index of packet start
  776. */
  777. static ZT_INLINE int newPacket(uint8_t pkt[28],const uint64_t packetId,const Address destination,const Address source,const Verb verb) noexcept
  778. {
  779. Utils::storeAsIsEndian<uint64_t>(pkt + ZT_PROTO_PACKET_ID_INDEX,packetId);
  780. destination.copyTo(pkt + ZT_PROTO_PACKET_DESTINATION_INDEX);
  781. source.copyTo(pkt + ZT_PROTO_PACKET_SOURCE_INDEX);
  782. pkt[ZT_PROTO_PACKET_FLAGS_INDEX] = 0;
  783. Utils::storeAsIsEndian<uint64_t>(pkt + ZT_PROTO_PACKET_MAC_INDEX,0);
  784. pkt[ZT_PROTO_PACKET_VERB_INDEX] = (uint8_t)verb;
  785. return ZT_PROTO_PACKET_VERB_INDEX + 1;
  786. }
  787. static ZT_INLINE int newPacket(Buf &pkt,const uint64_t packetId,const Address destination,const Address source,const Verb verb) noexcept { return newPacket(pkt.unsafeData,packetId,destination,source,verb); }
  788. /**
  789. * Encrypt and compute packet MAC
  790. *
  791. * @param pkt Packet data to encrypt (in place)
  792. * @param packetSize Packet size, must be at least ZT_PROTO_MIN_PACKET_LENGTH or crash will occur
  793. * @param key Key to use for encryption
  794. * @param cipherSuite Cipher suite to use for AEAD encryption or just MAC
  795. */
  796. static ZT_INLINE void armor(uint8_t *const pkt,const int packetSize,const SharedPtr<SymmetricKey> &key,const uint8_t cipherSuite) noexcept
  797. {
  798. #if 0
  799. Protocol::Header &ph = pkt.as<Protocol::Header>(); // NOLINT(hicpp-use-auto,modernize-use-auto)
  800. ph.flags = (ph.flags & 0xc7U) | ((cipherSuite << 3U) & 0x38U); // flags: FFCCCHHH where CCC is cipher
  801. switch(cipherSuite) {
  802. case ZT_PROTO_CIPHER_SUITE__POLY1305_NONE: {
  803. uint8_t perPacketKey[ZT_SYMMETRIC_KEY_SIZE];
  804. salsa2012DeriveKey(key,perPacketKey,pkt,packetSize);
  805. Salsa20 s20(perPacketKey,&ph.packetId);
  806. uint8_t macKey[ZT_POLY1305_KEY_SIZE];
  807. s20.crypt12(Utils::ZERO256,macKey,ZT_POLY1305_KEY_SIZE);
  808. // only difference here is that we don't encrypt the payload
  809. uint64_t mac[2];
  810. poly1305(mac,pkt.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START,packetSize - ZT_PROTO_PACKET_ENCRYPTED_SECTION_START,macKey);
  811. ph.mac = mac[0];
  812. } break;
  813. case ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012: {
  814. uint8_t perPacketKey[ZT_SYMMETRIC_KEY_SIZE];
  815. salsa2012DeriveKey(key,perPacketKey,pkt,packetSize);
  816. Salsa20 s20(perPacketKey,&ph.packetId);
  817. uint8_t macKey[ZT_POLY1305_KEY_SIZE];
  818. s20.crypt12(Utils::ZERO256,macKey,ZT_POLY1305_KEY_SIZE);
  819. const unsigned int encLen = packetSize - ZT_PROTO_PACKET_ENCRYPTED_SECTION_START;
  820. s20.crypt12(pkt.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START,pkt.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START,encLen);
  821. uint64_t mac[2];
  822. poly1305(mac,pkt.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START,encLen,macKey);
  823. ph.mac = mac[0];
  824. } break;
  825. case ZT_PROTO_CIPHER_SUITE__AES_GMAC_SIV: {
  826. } break;
  827. }
  828. #endif
  829. }
  830. /**
  831. * Attempt to compress packet payload
  832. *
  833. * This attempts compression and swaps the pointer in 'pkt' for a buffer holding
  834. * compressed data on success. If compression did not shrink the packet, the original
  835. * packet size is returned and 'pkt' remains unchanged. If compression is successful
  836. * the compressed verb flag is also set.
  837. *
  838. * @param pkt Packet buffer value/result parameter: pointer may be swapped if compression is successful
  839. * @param packetSize Total size of packet in bytes (including headers)
  840. * @return New size of packet after compression or original size of compression wasn't helpful
  841. */
  842. static ZT_INLINE int compress(SharedPtr<Buf> &pkt,int packetSize) noexcept
  843. {
  844. // TODO
  845. return packetSize;
  846. }
  847. } // namespace Protocol
  848. } // namespace ZeroTier
  849. #endif