Packet.hpp 55 KB

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