Packet.hpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_N_PACKET_HPP
  19. #define ZT_N_PACKET_HPP
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <string>
  24. #include <iostream>
  25. #include "Constants.hpp"
  26. #include "Address.hpp"
  27. #include "Poly1305.hpp"
  28. #include "Salsa20.hpp"
  29. #include "Utils.hpp"
  30. #include "Buffer.hpp"
  31. #ifdef ZT_USE_SYSTEM_LZ4
  32. #include <lz4.h>
  33. #else
  34. #include "../ext/lz4/lz4.h"
  35. #endif
  36. /**
  37. * Protocol version -- incremented only for major changes
  38. *
  39. * 1 - 0.2.0 ... 0.2.5
  40. * 2 - 0.3.0 ... 0.4.5
  41. * + Added signature and originating peer to multicast frame
  42. * + Double size of multicast frame bloom filter
  43. * 3 - 0.5.0 ... 0.6.0
  44. * + Yet another multicast redesign
  45. * + New crypto completely changes key agreement cipher
  46. * 4 - 0.6.0 ... 1.0.6
  47. * + New identity format based on hashcash design
  48. * 5 - 1.1.0 ... 1.1.5
  49. * + Supports circuit test, proof of work, and echo
  50. * + Supports in-band world (root server definition) updates
  51. * + Clustering! (Though this will work with protocol v4 clients.)
  52. * + Otherwise backward compatible with protocol v4
  53. * 6 - 1.1.5 ... 1.1.10
  54. * + Deprecate old dictionary-based network config format
  55. * + Introduce new binary serialized network config and meta-data
  56. * 7 - 1.1.10 -- CURRENT
  57. * + Introduce trusted paths for local SDN use
  58. */
  59. #define ZT_PROTO_VERSION 7
  60. /**
  61. * Minimum supported protocol version
  62. */
  63. #define ZT_PROTO_VERSION_MIN 4
  64. /**
  65. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  66. *
  67. * This is a protocol constant. It's the maximum allowed by the length
  68. * of the hop counter -- three bits. See node/Constants.hpp for the
  69. * pragmatic forwarding limit, which is typically lower.
  70. */
  71. #define ZT_PROTO_MAX_HOPS 7
  72. /**
  73. * Cipher suite: Curve25519/Poly1305/Salsa20/12/NOCRYPT
  74. *
  75. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  76. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  77. * but the payload is not encrypted. This is currently only used to send
  78. * HELLO since that's the public key specification packet and must be
  79. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  80. * curve Diffie-Hellman.
  81. */
  82. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  83. /**
  84. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  85. *
  86. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  87. * stream as its one-time-use key followed by payload encryption with
  88. * the remaining Salsa20/12 key stream. Key agreement is performed using
  89. * Curve25519 elliptic curve Diffie-Hellman.
  90. */
  91. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  92. /**
  93. * Cipher suite: NONE
  94. *
  95. * This differs from POLY1305/NONE in that *no* crypto is done, not even
  96. * authentication. This is for trusted local LAN interconnects for internal
  97. * SDN use within a data center.
  98. *
  99. * For this mode the MAC field becomes a trusted path ID and must match the
  100. * configured ID of a trusted path or the packet is discarded.
  101. */
  102. #define ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH 2
  103. /**
  104. * DEPRECATED payload encrypted flag, may be re-used in the future.
  105. *
  106. * This has been replaced by the three-bit cipher suite selection field.
  107. */
  108. #define ZT_PROTO_FLAG_ENCRYPTED 0x80
  109. /**
  110. * Header flag indicating that a packet is fragmented
  111. *
  112. * If this flag is set, the receiver knows to expect more than one fragment.
  113. * See Packet::Fragment for details.
  114. */
  115. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  116. /**
  117. * Verb flag indicating payload is compressed with LZ4
  118. */
  119. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  120. /**
  121. * Rounds used for Salsa20 encryption in ZT
  122. *
  123. * Discussion:
  124. *
  125. * DJB (Salsa20's designer) designed Salsa20 with a significant margin of 20
  126. * rounds, but has said repeatedly that 12 is likely sufficient. So far (as of
  127. * July 2015) there are no published attacks against 12 rounds, let alone 20.
  128. *
  129. * In cryptography, a "break" means something different from what it means in
  130. * common discussion. If a cipher is 256 bits strong and someone finds a way
  131. * to reduce key search to 254 bits, this constitues a "break" in the academic
  132. * literature. 254 bits is still far beyond what can be leveraged to accomplish
  133. * a "break" as most people would understand it -- the actual decryption and
  134. * reading of traffic.
  135. *
  136. * Nevertheless, "attacks only get better" as cryptographers like to say. As
  137. * a result, they recommend not using anything that's shown any weakness even
  138. * if that weakness is so far only meaningful to academics. It may be a sign
  139. * of a deeper problem.
  140. *
  141. * So why choose a lower round count?
  142. *
  143. * Turns out the speed difference is nontrivial. On a Macbook Pro (Core i3) 20
  144. * rounds of SSE-optimized Salsa20 achieves ~508mb/sec/core, while 12 rounds
  145. * hits ~832mb/sec/core. ZeroTier is designed for multiple objectives:
  146. * security, simplicity, and performance. In this case a deference was made
  147. * for performance.
  148. *
  149. * Meta discussion:
  150. *
  151. * The cipher is not the thing you should be paranoid about.
  152. *
  153. * I'll qualify that. If the cipher is known to be weak, like RC4, or has a
  154. * key size that is too small, like DES, then yes you should worry about
  155. * the cipher.
  156. *
  157. * But if the cipher is strong and your adversary is anyone other than the
  158. * intelligence apparatus of a major superpower, you are fine in that
  159. * department.
  160. *
  161. * Go ahead. Search for the last ten vulnerabilities discovered in SSL. Not
  162. * a single one involved the breaking of a cipher. Now broaden your search.
  163. * Look for issues with SSH, IPSec, etc. The only cipher-related issues you
  164. * will find might involve the use of RC4 or MD5, algorithms with known
  165. * issues or small key/digest sizes. But even weak ciphers are difficult to
  166. * exploit in the real world -- you usually need a lot of data and a lot of
  167. * compute time. No, virtually EVERY security vulnerability you will find
  168. * involves a problem with the IMPLEMENTATION not with the cipher.
  169. *
  170. * A flaw in ZeroTier's protocol or code is incredibly, unbelievably
  171. * more likely than a flaw in Salsa20 or any other cipher or cryptographic
  172. * primitive it uses. We're talking odds of dying in a car wreck vs. odds of
  173. * being personally impacted on the head by a meteorite. Nobody without a
  174. * billion dollar budget is going to break into your network by actually
  175. * cracking Salsa20/12 (or even /8) in the field.
  176. *
  177. * So stop worrying about the cipher unless you are, say, the Kremlin and your
  178. * adversary is the NSA and the GCHQ. In that case... well that's above my
  179. * pay grade. I'll just say defense in depth.
  180. */
  181. #define ZT_PROTO_SALSA20_ROUNDS 12
  182. /**
  183. * PUSH_DIRECT_PATHS flag: forget path
  184. */
  185. #define ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH 0x01
  186. /**
  187. * PUSH_DIRECT_PATHS flag: cluster redirect
  188. */
  189. #define ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT 0x02
  190. // Field indexes in packet header
  191. #define ZT_PACKET_IDX_IV 0
  192. #define ZT_PACKET_IDX_DEST 8
  193. #define ZT_PACKET_IDX_SOURCE 13
  194. #define ZT_PACKET_IDX_FLAGS 18
  195. #define ZT_PACKET_IDX_MAC 19
  196. #define ZT_PACKET_IDX_VERB 27
  197. #define ZT_PACKET_IDX_PAYLOAD 28
  198. /**
  199. * Packet buffer size (can be changed)
  200. *
  201. * The current value is big enough for ZT_MAX_PACKET_FRAGMENTS, the pragmatic
  202. * packet fragment limit, times the default UDP MTU. Most packets won't be
  203. * this big.
  204. */
  205. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  206. /**
  207. * Minimum viable packet length (a.k.a. header length)
  208. */
  209. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  210. // Indexes of fields in fragment header
  211. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  212. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  213. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  214. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  215. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  216. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  217. /**
  218. * Magic number found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR
  219. */
  220. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  221. /**
  222. * Minimum viable fragment length
  223. */
  224. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  225. // Field incides for parsing verbs -------------------------------------------
  226. // Some verbs have variable-length fields. Those aren't fully defined here
  227. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  228. // See their respective handler functions.
  229. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  230. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  231. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  232. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  233. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  234. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  235. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  236. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  237. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  238. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  239. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  240. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  241. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  242. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  243. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  244. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  245. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  246. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  247. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  248. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  249. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  250. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  251. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  252. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  253. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  254. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  255. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  256. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  257. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  258. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  259. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  260. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  261. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  262. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  263. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  264. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  265. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  266. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  267. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  268. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  269. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  270. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  271. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  272. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  273. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  274. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  275. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  276. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  277. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  278. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  279. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  280. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  281. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  282. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  283. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  284. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  285. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  286. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  287. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  288. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  289. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  290. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  291. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  292. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  293. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  294. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  295. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  296. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  297. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  298. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  299. // ---------------------------------------------------------------------------
  300. namespace ZeroTier {
  301. /**
  302. * ZeroTier packet
  303. *
  304. * Packet format:
  305. * <[8] 64-bit random packet ID and crypto initialization vector>
  306. * <[5] destination ZT address>
  307. * <[5] source ZT address>
  308. * <[1] flags/cipher/hops>
  309. * <[8] 64-bit MAC (or trusted path ID in trusted path mode)>
  310. * [... -- begin encryption envelope -- ...]
  311. * <[1] encrypted flags (MS 3 bits) and verb (LS 5 bits)>
  312. * [... verb-specific payload ...]
  313. *
  314. * Packets smaller than 28 bytes are invalid and silently discarded.
  315. *
  316. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  317. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  318. * and H is hop count.
  319. *
  320. * The three-bit hop count is the only part of a packet that is mutable in
  321. * transit without invalidating the MAC. All other bits in the packet are
  322. * immutable. This is because intermediate nodes can increment the hop
  323. * count up to 7 (protocol max).
  324. *
  325. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  326. * sent in the clear, as it's the "here is my public key" message.
  327. */
  328. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  329. {
  330. public:
  331. /**
  332. * A packet fragment
  333. *
  334. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  335. * is sent with its normal header with the fragmented flag set. Remaining
  336. * fragments are sent this way.
  337. *
  338. * The fragmented bit indicates that there is at least one fragment. Fragments
  339. * themselves contain the total, so the receiver must "learn" this from the
  340. * first fragment it receives.
  341. *
  342. * Fragments are sent with the following format:
  343. * <[8] packet ID of packet whose fragment this belongs to>
  344. * <[5] destination ZT address>
  345. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  346. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  347. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  348. * <[...] fragment data>
  349. *
  350. * The protocol supports a maximum of 16 fragments. If a fragment is received
  351. * before its main packet header, it should be cached for a brief period of
  352. * time to see if its parent arrives. Loss of any fragment constitutes packet
  353. * loss; there is no retransmission mechanism. The receiver must wait for full
  354. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  355. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  356. */
  357. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  358. {
  359. public:
  360. Fragment() :
  361. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  362. {
  363. }
  364. template<unsigned int C2>
  365. Fragment(const Buffer<C2> &b)
  366. throw(std::out_of_range) :
  367. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  368. {
  369. }
  370. Fragment(const void *data,unsigned int len) :
  371. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  372. {
  373. }
  374. /**
  375. * Initialize from a packet
  376. *
  377. * @param p Original assembled packet
  378. * @param fragStart Start of fragment (raw index in packet data)
  379. * @param fragLen Length of fragment in bytes
  380. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  381. * @param fragTotal Total number of fragments (including 0)
  382. * @throws std::out_of_range Packet size would exceed buffer
  383. */
  384. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  385. throw(std::out_of_range)
  386. {
  387. init(p,fragStart,fragLen,fragNo,fragTotal);
  388. }
  389. /**
  390. * Initialize from a packet
  391. *
  392. * @param p Original assembled packet
  393. * @param fragStart Start of fragment (raw index in packet data)
  394. * @param fragLen Length of fragment in bytes
  395. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  396. * @param fragTotal Total number of fragments (including 0)
  397. * @throws std::out_of_range Packet size would exceed buffer
  398. */
  399. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  400. throw(std::out_of_range)
  401. {
  402. if ((fragStart + fragLen) > p.size())
  403. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  404. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  405. // NOTE: this copies both the IV/packet ID and the destination address.
  406. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  407. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  408. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  409. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  410. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  411. }
  412. /**
  413. * Get this fragment's destination
  414. *
  415. * @return Destination ZT address
  416. */
  417. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  418. /**
  419. * @return True if fragment is of a valid length
  420. */
  421. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  422. /**
  423. * @return ID of packet this is a fragment of
  424. */
  425. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  426. /**
  427. * @return Total number of fragments in packet
  428. */
  429. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  430. /**
  431. * @return Fragment number of this fragment
  432. */
  433. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  434. /**
  435. * @return Fragment ZT hop count
  436. */
  437. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  438. /**
  439. * Increment this packet's hop count
  440. */
  441. inline void incrementHops()
  442. {
  443. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  444. }
  445. /**
  446. * @return Length of payload in bytes
  447. */
  448. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  449. /**
  450. * @return Raw packet payload
  451. */
  452. inline const unsigned char *payload() const
  453. {
  454. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  455. }
  456. };
  457. /**
  458. * ZeroTier protocol verbs
  459. */
  460. enum Verb /* Max value: 32 (5 bits) */
  461. {
  462. /**
  463. * No operation (ignored, no reply)
  464. */
  465. VERB_NOP = 0,
  466. /**
  467. * Announcement of a node's existence:
  468. * <[1] protocol version>
  469. * <[1] software major version>
  470. * <[1] software minor version>
  471. * <[2] software revision>
  472. * <[8] timestamp (ms since epoch)>
  473. * <[...] binary serialized identity (see Identity)>
  474. * <[1] destination address type>
  475. * [<[...] destination address>]
  476. * <[8] 64-bit world ID of current world>
  477. * <[8] 64-bit timestamp of current world>
  478. *
  479. * This is the only message that ever must be sent in the clear, since it
  480. * is used to push an identity to a new peer.
  481. *
  482. * The destination address is the wire address to which this packet is
  483. * being sent, and in OK is *also* the destination address of the OK
  484. * packet. This can be used by the receiver to detect NAT, learn its real
  485. * external address if behind NAT, and detect changes to its external
  486. * address that require re-establishing connectivity.
  487. *
  488. * Destination address types and formats (not all of these are used now):
  489. * 0x00 - None -- no destination address data present
  490. * 0x01 - Ethernet address -- format: <[6] Ethernet MAC>
  491. * 0x04 - 6-byte IPv4 UDP address/port -- format: <[4] IP>, <[2] port>
  492. * 0x06 - 18-byte IPv6 UDP address/port -- format: <[16] IP>, <[2] port>
  493. *
  494. * OK payload:
  495. * <[8] timestamp (echoed from original HELLO)>
  496. * <[1] protocol version (of responder)>
  497. * <[1] software major version (of responder)>
  498. * <[1] software minor version (of responder)>
  499. * <[2] software revision (of responder)>
  500. * <[1] destination address type (for this OK, not copied from HELLO)>
  501. * [<[...] destination address>]
  502. * <[2] 16-bit length of world update or 0 if none>
  503. * [[...] world update]
  504. *
  505. * ERROR has no payload.
  506. */
  507. VERB_HELLO = 1,
  508. /**
  509. * Error response:
  510. * <[1] in-re verb>
  511. * <[8] in-re packet ID>
  512. * <[1] error code>
  513. * <[...] error-dependent payload>
  514. */
  515. VERB_ERROR = 2,
  516. /**
  517. * Success response:
  518. * <[1] in-re verb>
  519. * <[8] in-re packet ID>
  520. * <[...] request-specific payload>
  521. */
  522. VERB_OK = 3,
  523. /**
  524. * Query an identity by address:
  525. * <[5] address to look up>
  526. *
  527. * OK response payload:
  528. * <[...] binary serialized identity>
  529. *
  530. * If querying a cluster, duplicate OK responses may occasionally occur.
  531. * These should be discarded.
  532. *
  533. * If the address is not found, no response is generated. WHOIS requests
  534. * will time out much like ARP requests and similar do in L2.
  535. */
  536. VERB_WHOIS = 4,
  537. /**
  538. * Meet another node at a given protocol address:
  539. * <[1] flags (unused, currently 0)>
  540. * <[5] ZeroTier address of peer that might be found at this address>
  541. * <[2] 16-bit protocol address port>
  542. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  543. * <[...] protocol address (network byte order)>
  544. *
  545. * This is sent by a relaying node to initiate NAT traversal between two
  546. * peers that are communicating by way of indirect relay. The relay will
  547. * send this to both peers at the same time on a periodic basis, telling
  548. * each where it might find the other on the network.
  549. *
  550. * Upon receipt a peer sends HELLO to establish a direct link.
  551. *
  552. * Nodes should implement rate control, limiting the rate at which they
  553. * respond to these packets to prevent their use in DDOS attacks. Nodes
  554. * may also ignore these messages if a peer is not known or is not being
  555. * actively communicated with.
  556. *
  557. * Unfortunately the physical address format in this message pre-dates
  558. * InetAddress's serialization format. :( ZeroTier is four years old and
  559. * yes we've accumulated a tiny bit of cruft here and there.
  560. *
  561. * No OK or ERROR is generated.
  562. */
  563. VERB_RENDEZVOUS = 5,
  564. /**
  565. * ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  566. * <[8] 64-bit network ID>
  567. * <[2] 16-bit ethertype>
  568. * <[...] ethernet payload>
  569. *
  570. * MAC addresses are derived from the packet's source and destination
  571. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  572. * Ethernet framing and other optional flags and features when they
  573. * are not necessary.
  574. *
  575. * ERROR may be generated if a membership certificate is needed for a
  576. * closed network. Payload will be network ID.
  577. */
  578. VERB_FRAME = 6,
  579. /**
  580. * Full Ethernet frame with MAC addressing and optional fields:
  581. * <[8] 64-bit network ID>
  582. * <[1] flags>
  583. * [<[...] certificate of network membership>]
  584. * <[6] destination MAC or all zero for destination node>
  585. * <[6] source MAC or all zero for node of origin>
  586. * <[2] 16-bit ethertype>
  587. * <[...] ethernet payload>
  588. *
  589. * Flags:
  590. * 0x01 - Certificate of network membership is attached
  591. *
  592. * An extended frame carries full MAC addressing, making them a
  593. * superset of VERB_FRAME. They're used for bridging or when we
  594. * want to attach a certificate since FRAME does not support that.
  595. *
  596. * Multicast frames may not be sent as EXT_FRAME.
  597. *
  598. * ERROR may be generated if a membership certificate is needed for a
  599. * closed network. Payload will be network ID.
  600. */
  601. VERB_EXT_FRAME = 7,
  602. /**
  603. * ECHO request (a.k.a. ping):
  604. * <[...] arbitrary payload>
  605. *
  606. * This generates OK with a copy of the transmitted payload. No ERROR
  607. * is generated. Response to ECHO requests is optional and ECHO may be
  608. * ignored if a node detects a possible flood.
  609. */
  610. VERB_ECHO = 8,
  611. /**
  612. * Announce interest in multicast group(s):
  613. * <[8] 64-bit network ID>
  614. * <[6] multicast Ethernet address>
  615. * <[4] multicast additional distinguishing information (ADI)>
  616. * [... additional tuples of network/address/adi ...]
  617. *
  618. * LIKEs may be sent to any peer, though a good implementation should
  619. * restrict them to peers on the same network they're for and to network
  620. * controllers and root servers. In the current network, root servers
  621. * will provide the service of final multicast cache.
  622. *
  623. * It is recommended that NETWORK_MEMBERSHIP_CERTIFICATE pushes be sent
  624. * along with MULTICAST_LIKE when pushing LIKEs to peers that do not
  625. * share a network membership (such as root servers), since this can be
  626. * used to authenticate GATHER requests and limit responses to peers
  627. * authorized to talk on a network. (Should be an optional field here,
  628. * but saving one or two packets every five minutes is not worth an
  629. * ugly hack or protocol rev.)
  630. *
  631. * OK/ERROR are not generated.
  632. */
  633. VERB_MULTICAST_LIKE = 9,
  634. /**
  635. * Network member certificate replication/push:
  636. * <[...] serialized certificate of membership>
  637. * [ ... additional certificates may follow ...]
  638. *
  639. * This is sent in response to ERROR_NEED_MEMBERSHIP_CERTIFICATE and may
  640. * be pushed at any other time to keep exchanged certificates up to date.
  641. *
  642. * OK/ERROR are not generated.
  643. */
  644. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  645. /**
  646. * DEPRECATED but still supported, interpreted as an object request:
  647. *
  648. * /controller/network/<network ID>/member/<requester address>
  649. *
  650. * When received in this manner the response is sent via the old
  651. * OK(NETWORK_CONFIG_REQUEST) instead of OK(REQUEST_OBJECT).
  652. *
  653. * OK response payload:
  654. * <[8] 64-bit network ID>
  655. * <[2] 16-bit length of network configuration dictionary>
  656. * <[...] network configuration dictionary>
  657. *
  658. * ERROR response payload:
  659. * <[8] 64-bit network ID>
  660. */
  661. VERB_NETWORK_CONFIG_REQUEST = 11,
  662. /**
  663. * Request endpoints for multicast distribution:
  664. * <[8] 64-bit network ID>
  665. * <[1] flags>
  666. * <[6] MAC address of multicast group being queried>
  667. * <[4] 32-bit ADI for multicast group being queried>
  668. * <[4] 32-bit requested max number of multicast peers>
  669. * [<[...] network certificate of membership>]
  670. *
  671. * Flags:
  672. * 0x01 - Network certificate of membership is attached
  673. *
  674. * This message asks a peer for additional known endpoints that have
  675. * LIKEd a given multicast group. It's sent when the sender wishes
  676. * to send multicast but does not have the desired number of recipient
  677. * peers.
  678. *
  679. * More than one OK response can occur if the response is broken up across
  680. * multiple packets or if querying a clustered node.
  681. *
  682. * OK response payload:
  683. * <[8] 64-bit network ID>
  684. * <[6] MAC address of multicast group being queried>
  685. * <[4] 32-bit ADI for multicast group being queried>
  686. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  687. * <[4] 32-bit total number of known members in this multicast group>
  688. * <[2] 16-bit number of members enumerated in this packet>
  689. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  690. *
  691. * ERROR is not generated; queries that return no response are dropped.
  692. */
  693. VERB_MULTICAST_GATHER = 13,
  694. /**
  695. * Multicast frame:
  696. * <[8] 64-bit network ID>
  697. * <[1] flags>
  698. * [<[...] network certificate of membership>]
  699. * [<[4] 32-bit implicit gather limit>]
  700. * [<[6] source MAC>]
  701. * <[6] destination MAC (multicast address)>
  702. * <[4] 32-bit multicast ADI (multicast address extension)>
  703. * <[2] 16-bit ethertype>
  704. * <[...] ethernet payload>
  705. *
  706. * Flags:
  707. * 0x01 - Network certificate of membership is attached
  708. * 0x02 - Implicit gather limit field is present
  709. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  710. *
  711. * OK and ERROR responses are optional. OK may be generated if there are
  712. * implicit gather results or if the recipient wants to send its own
  713. * updated certificate of network membership to the sender. ERROR may be
  714. * generated if a certificate is needed or if multicasts to this group
  715. * are no longer wanted (multicast unsubscribe).
  716. *
  717. * OK response payload:
  718. * <[8] 64-bit network ID>
  719. * <[6] MAC address of multicast group>
  720. * <[4] 32-bit ADI for multicast group>
  721. * <[1] flags>
  722. * [<[...] network certficate of membership>]
  723. * [<[...] implicit gather results if flag 0x01 is set>]
  724. *
  725. * OK flags (same bits as request flags):
  726. * 0x01 - OK includes certificate of network membership
  727. * 0x02 - OK includes implicit gather results
  728. *
  729. * ERROR response payload:
  730. * <[8] 64-bit network ID>
  731. * <[6] multicast group MAC>
  732. * <[4] 32-bit multicast group ADI>
  733. */
  734. VERB_MULTICAST_FRAME = 14,
  735. /**
  736. * Push of potential endpoints for direct communication:
  737. * <[2] 16-bit number of paths>
  738. * <[...] paths>
  739. *
  740. * Path record format:
  741. * <[1] 8-bit path flags>
  742. * <[2] length of extended path characteristics or 0 for none>
  743. * <[...] extended path characteristics>
  744. * <[1] address type>
  745. * <[1] address length in bytes>
  746. * <[...] address>
  747. *
  748. * Path record flags:
  749. * 0x01 - Forget this path if currently known (not implemented yet)
  750. * 0x02 - Cluster redirect -- use this in preference to others
  751. *
  752. * The receiver may, upon receiving a push, attempt to establish a
  753. * direct link to one or more of the indicated addresses. It is the
  754. * responsibility of the sender to limit which peers it pushes direct
  755. * paths to to those with whom it has a trust relationship. The receiver
  756. * must obey any restrictions provided such as exclusivity or blacklists.
  757. * OK responses to this message are optional.
  758. *
  759. * Note that a direct path push does not imply that learned paths can't
  760. * be used unless they are blacklisted explicitly or unless flag 0x01
  761. * is set.
  762. *
  763. * Only a subset of this functionality is currently implemented: basic
  764. * path pushing and learning. Blacklisting and trust are not fully
  765. * implemented yet (encryption is still always used).
  766. *
  767. * OK and ERROR are not generated.
  768. */
  769. VERB_PUSH_DIRECT_PATHS = 16,
  770. /**
  771. * Source-routed circuit test message:
  772. * <[5] address of originator of circuit test>
  773. * <[2] 16-bit flags>
  774. * <[8] 64-bit timestamp>
  775. * <[8] 64-bit test ID (arbitrary, set by tester)>
  776. * <[2] 16-bit originator credential length (includes type)>
  777. * [[1] originator credential type (for authorizing test)]
  778. * [[...] originator credential]
  779. * <[2] 16-bit length of additional fields>
  780. * [[...] additional fields]
  781. * [ ... end of signed portion of request ... ]
  782. * <[2] 16-bit length of signature of request>
  783. * <[...] signature of request by originator>
  784. * <[2] 16-bit previous hop credential length (including type)>
  785. * [[1] previous hop credential type]
  786. * [[...] previous hop credential]
  787. * <[...] next hop(s) in path>
  788. *
  789. * Flags:
  790. * 0x01 - Report back to originator at middle hops
  791. * 0x02 - Report back to originator at last hop
  792. *
  793. * Originator credential types:
  794. * 0x01 - 64-bit network ID for which originator is controller
  795. *
  796. * Previous hop credential types:
  797. * 0x01 - Certificate of network membership
  798. *
  799. * Path record format:
  800. * <[1] 8-bit flags (unused, must be zero)>
  801. * <[1] 8-bit breadth (number of next hops)>
  802. * <[...] one or more ZeroTier addresses of next hops>
  803. *
  804. * The circuit test allows a device to send a message that will traverse
  805. * the network along a specified path, with each hop optionally reporting
  806. * back to the tester via VERB_CIRCUIT_TEST_REPORT.
  807. *
  808. * Each circuit test packet includes a digital signature by the originator
  809. * of the request, as well as a credential by which that originator claims
  810. * authorization to perform the test. Currently this signature is ed25519,
  811. * but in the future flags might be used to indicate an alternative
  812. * algorithm. For example, the originator might be a network controller.
  813. * In this case the test might be authorized if the recipient is a member
  814. * of a network controlled by it, and if the previous hop(s) are also
  815. * members. Each hop may include its certificate of network membership.
  816. *
  817. * Circuit test paths consist of a series of records. When a node receives
  818. * an authorized circuit test, it:
  819. *
  820. * (1) Reports back to circuit tester as flags indicate
  821. * (2) Reads and removes the next hop from the packet's path
  822. * (3) Sends the packet along to next hop(s), if any.
  823. *
  824. * It is perfectly legal for a path to contain the same hop more than
  825. * once. In fact, this can be a very useful test to determine if a hop
  826. * can be reached bidirectionally and if so what that connectivity looks
  827. * like.
  828. *
  829. * The breadth field in source-routed path records allows a hop to forward
  830. * to more than one recipient, allowing the tester to specify different
  831. * forms of graph traversal in a test.
  832. *
  833. * There is no hard limit to the number of hops in a test, but it is
  834. * practically limited by the maximum size of a (possibly fragmented)
  835. * ZeroTier packet.
  836. *
  837. * Support for circuit tests is optional. If they are not supported, the
  838. * node should respond with an UNSUPPORTED_OPERATION error. If a circuit
  839. * test request is not authorized, it may be ignored or reported as
  840. * an INVALID_REQUEST. No OK messages are generated, but TEST_REPORT
  841. * messages may be sent (see below).
  842. *
  843. * ERROR packet format:
  844. * <[8] 64-bit timestamp (echoed from original>
  845. * <[8] 64-bit test ID (echoed from original)>
  846. */
  847. VERB_CIRCUIT_TEST = 17,
  848. /**
  849. * Circuit test hop report:
  850. * <[8] 64-bit timestamp (from original test)>
  851. * <[8] 64-bit test ID (from original test)>
  852. * <[8] 64-bit reserved field (set to 0, currently unused)>
  853. * <[1] 8-bit vendor ID (set to 0, currently unused)>
  854. * <[1] 8-bit reporter protocol version>
  855. * <[1] 8-bit reporter major version>
  856. * <[1] 8-bit reporter minor version>
  857. * <[2] 16-bit reporter revision>
  858. * <[2] 16-bit reporter OS/platform>
  859. * <[2] 16-bit reporter architecture>
  860. * <[2] 16-bit error code (set to 0, currently unused)>
  861. * <[8] 64-bit report flags (set to 0, currently unused)>
  862. * <[8] 64-bit source packet ID>
  863. * <[5] upstream ZeroTier address from which test was received>
  864. * <[1] 8-bit source packet hop count (ZeroTier hop count)>
  865. * <[...] local wire address on which packet was received>
  866. * <[...] remote wire address from which packet was received>
  867. * <[2] 16-bit length of additional fields>
  868. * <[...] additional fields>
  869. * <[1] 8-bit number of next hops (breadth)>
  870. * <[...] next hop information>
  871. *
  872. * Next hop information record format:
  873. * <[5] ZeroTier address of next hop>
  874. * <[...] current best direct path address, if any, 0 if none>
  875. *
  876. * Circuit test reports can be sent by hops in a circuit test to report
  877. * back results. They should include information about the sender as well
  878. * as about the paths to which next hops are being sent.
  879. *
  880. * If a test report is received and no circuit test was sent, it should be
  881. * ignored. This message generates no OK or ERROR response.
  882. */
  883. VERB_CIRCUIT_TEST_REPORT = 18,
  884. /**
  885. * Request proof of work:
  886. * <[1] 8-bit proof of work type>
  887. * <[1] 8-bit proof of work difficulty>
  888. * <[2] 16-bit length of proof of work challenge>
  889. * <[...] proof of work challenge>
  890. *
  891. * This requests that a peer perform a proof of work calucation. It can be
  892. * sent by highly trusted peers (e.g. root servers, network controllers)
  893. * under suspected denial of service conditions in an attempt to filter
  894. * out "non-serious" peers and remain responsive to those proving their
  895. * intent to actually communicate.
  896. *
  897. * If the peer obliges to perform the work, it does so and responds with
  898. * an OK containing the result. Otherwise it may ignore the message or
  899. * response with an ERROR_INVALID_REQUEST or ERROR_UNSUPPORTED_OPERATION.
  900. *
  901. * Proof of work type IDs:
  902. * 0x01 - Salsa20/12+SHA512 hashcash function
  903. *
  904. * Salsa20/12+SHA512 is based on the following composite hash function:
  905. *
  906. * (1) Compute SHA512(candidate)
  907. * (2) Use the first 256 bits of the result of #1 as a key to encrypt
  908. * 131072 zero bytes with Salsa20/12 (with a zero IV).
  909. * (3) Compute SHA512(the result of step #2)
  910. * (4) Accept this candiate if the first [difficulty] bits of the result
  911. * from step #3 are zero. Otherwise generate a new candidate and try
  912. * again.
  913. *
  914. * This is performed repeatedly on candidates generated by appending the
  915. * supplied challenge to an arbitrary nonce until a valid candidate
  916. * is found. This chosen prepended nonce is then returned as the result
  917. * in OK.
  918. *
  919. * OK payload:
  920. * <[2] 16-bit length of result>
  921. * <[...] computed proof of work>
  922. *
  923. * ERROR has no payload.
  924. */
  925. VERB_REQUEST_PROOF_OF_WORK = 19,
  926. /**
  927. * Request an object or a chunk of an object with optional meta-data:
  928. * <[8] 64-bit chunk offset>
  929. * <[2] 16-bit chunk length or 0 for any / sender-preferred>
  930. * <[2] 16-bit object path length in bytes>
  931. * <[...] object path>
  932. * <[2] 16-bit length of request meta-data dictionary>
  933. * <[...] request meta-data dictionary>
  934. *
  935. * This is used to request an object. Objects can be things like network
  936. * configs, software updates, etc. This provides an in-band way to
  937. * distribute such things and obsoletes the network config specific
  938. * messages. (They are still supported for backward compatibility.)
  939. *
  940. * The use of path and request/response meta-data makes the semantics of
  941. * this analogous to HTTP POST, and it could therefore be mapped to
  942. * HTTP POST requests to permit plugins that leverage the ZT protocol
  943. * to do out-of-band things like special authentication, etc.
  944. *
  945. * Large objects can be transferred via repeated calls with higher and
  946. * higher chunk offsets and then SHA-512 verified on receipt, but this is
  947. * not efficient. It should not be used heavily as an alternative to
  948. * TCP. It's a bit more like X-Modem and other old-school SEND/ACK
  949. * protocols. It is potentially a good idea for software updates since
  950. * it means that ZT can update itself even on networks with no "vanilla"
  951. * Internet access.
  952. *
  953. * OK and ERROR responses are optional but recommended. ERROR responses
  954. * can include OBJECT_NOT_FOUND.
  955. *
  956. * OK response payload:
  957. * <[16] first 16 bytes of SHA-512 of complete object>
  958. * <[8] 64-bit total object size>
  959. * <[8] 64-bit chunk offset>
  960. * <[2] 16-bit length of chunk payload>
  961. * <[...] chunk payload>
  962. */
  963. VERB_REQUEST_OBJECT = 20,
  964. /**
  965. * Notification of a remote object update:
  966. * <[8] 64-bit total object size or 0 if unspecified here>
  967. * <[16] first 16 bytes of SHA-512 of object (if size specified)>
  968. * <[2] 16-bit length of object path>
  969. * <[...] object path>
  970. * <[2] 16-bit length of meta-data dictionary>
  971. * <[...] meta-data dictionary>
  972. *
  973. * This can be sent to notify another peer that an object has updated and
  974. * should be re-requested. The receiving peer is not required to do anything
  975. * or send anything in response to this. If the first size field is zero, the
  976. * SHA-512 hash is also unspecified and should be zero. This means that the
  977. * object was updated but must be re-requested.
  978. */
  979. VERB_OBJECT_UPDATED = 21
  980. };
  981. /**
  982. * Error codes for VERB_ERROR
  983. */
  984. enum ErrorCode
  985. {
  986. /* No error, not actually used in transit */
  987. ERROR_NONE = 0,
  988. /* Invalid request */
  989. ERROR_INVALID_REQUEST = 1,
  990. /* Bad/unsupported protocol version */
  991. ERROR_BAD_PROTOCOL_VERSION = 2,
  992. /* Unknown object queried */
  993. ERROR_OBJ_NOT_FOUND = 3,
  994. /* HELLO pushed an identity whose address is already claimed */
  995. ERROR_IDENTITY_COLLISION = 4,
  996. /* Verb or use case not supported/enabled by this node */
  997. ERROR_UNSUPPORTED_OPERATION = 5,
  998. /* Message to private network rejected -- no unexpired certificate on file */
  999. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  1000. /* Tried to join network, but you're not a member */
  1001. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  1002. /* Multicasts to this group are not wanted */
  1003. ERROR_UNWANTED_MULTICAST = 8
  1004. };
  1005. //#ifdef ZT_TRACE
  1006. static const char *verbString(Verb v)
  1007. throw();
  1008. static const char *errorString(ErrorCode e)
  1009. throw();
  1010. //#endif
  1011. template<unsigned int C2>
  1012. Packet(const Buffer<C2> &b) :
  1013. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  1014. {
  1015. }
  1016. Packet(const void *data,unsigned int len) :
  1017. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  1018. {
  1019. }
  1020. /**
  1021. * Construct a new empty packet with a unique random packet ID
  1022. *
  1023. * Flags and hops will be zero. Other fields and data region are undefined.
  1024. * Use the header access methods (setDestination() and friends) to fill out
  1025. * the header. Payload should be appended; initial size is header size.
  1026. */
  1027. Packet() :
  1028. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  1029. {
  1030. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1031. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  1032. }
  1033. /**
  1034. * Make a copy of a packet with a new initialization vector and destination address
  1035. *
  1036. * This can be used to take one draft prototype packet and quickly make copies to
  1037. * encrypt for different destinations.
  1038. *
  1039. * @param prototype Prototype packet
  1040. * @param dest Destination ZeroTier address for new packet
  1041. */
  1042. Packet(const Packet &prototype,const Address &dest) :
  1043. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  1044. {
  1045. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1046. setDestination(dest);
  1047. }
  1048. /**
  1049. * Construct a new empty packet with a unique random packet ID
  1050. *
  1051. * @param dest Destination ZT address
  1052. * @param source Source ZT address
  1053. * @param v Verb
  1054. */
  1055. Packet(const Address &dest,const Address &source,const Verb v) :
  1056. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  1057. {
  1058. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1059. setDestination(dest);
  1060. setSource(source);
  1061. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  1062. setVerb(v);
  1063. }
  1064. /**
  1065. * Reset this packet structure for reuse in place
  1066. *
  1067. * @param dest Destination ZT address
  1068. * @param source Source ZT address
  1069. * @param v Verb
  1070. */
  1071. inline void reset(const Address &dest,const Address &source,const Verb v)
  1072. {
  1073. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  1074. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  1075. setDestination(dest);
  1076. setSource(source);
  1077. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  1078. setVerb(v);
  1079. }
  1080. /**
  1081. * Generate a new IV / packet ID in place
  1082. *
  1083. * This can be used to re-use a packet buffer multiple times to send
  1084. * technically different but otherwise identical copies of the same
  1085. * packet.
  1086. */
  1087. inline void newInitializationVector() { Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8); }
  1088. /**
  1089. * Set this packet's destination
  1090. *
  1091. * @param dest ZeroTier address of destination
  1092. */
  1093. inline void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1094. /**
  1095. * Set this packet's source
  1096. *
  1097. * @param source ZeroTier address of source
  1098. */
  1099. inline void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1100. /**
  1101. * Get this packet's destination
  1102. *
  1103. * @return Destination ZT address
  1104. */
  1105. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1106. /**
  1107. * Get this packet's source
  1108. *
  1109. * @return Source ZT address
  1110. */
  1111. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  1112. /**
  1113. * @return True if packet is of valid length
  1114. */
  1115. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  1116. /**
  1117. * @return True if packet is fragmented (expect fragments)
  1118. */
  1119. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  1120. /**
  1121. * Set this packet's fragmented flag
  1122. *
  1123. * @param f Fragmented flag value
  1124. */
  1125. inline void setFragmented(bool f)
  1126. {
  1127. if (f)
  1128. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  1129. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  1130. }
  1131. /**
  1132. * @return True if compressed (result only valid if unencrypted)
  1133. */
  1134. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  1135. /**
  1136. * @return ZeroTier forwarding hops (0 to 7)
  1137. */
  1138. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  1139. /**
  1140. * Increment this packet's hop count
  1141. */
  1142. inline void incrementHops()
  1143. {
  1144. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1145. b = (b & 0xf8) | ((b + 1) & 0x07);
  1146. }
  1147. /**
  1148. * @return Cipher suite selector: 0 - 7 (see #defines)
  1149. */
  1150. inline unsigned int cipher() const
  1151. {
  1152. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  1153. }
  1154. /**
  1155. * Set this packet's cipher suite
  1156. */
  1157. inline void setCipher(unsigned int c)
  1158. {
  1159. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1160. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  1161. // Set DEPRECATED "encrypted" flag -- used by pre-1.0.3 peers
  1162. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1163. b |= ZT_PROTO_FLAG_ENCRYPTED;
  1164. else b &= (~ZT_PROTO_FLAG_ENCRYPTED);
  1165. }
  1166. /**
  1167. * Get the trusted path ID for this packet (only meaningful if cipher is trusted path)
  1168. *
  1169. * @return Trusted path ID (from MAC field)
  1170. */
  1171. inline uint64_t trustedPathId() const { return at<uint64_t>(ZT_PACKET_IDX_MAC); }
  1172. /**
  1173. * Set this packet's trusted path ID and set the cipher spec to trusted path
  1174. *
  1175. * @param tpid Trusted path ID
  1176. */
  1177. inline void setTrusted(const uint64_t tpid)
  1178. {
  1179. setCipher(ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH);
  1180. setAt(ZT_PACKET_IDX_MAC,tpid);
  1181. }
  1182. /**
  1183. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  1184. *
  1185. * @return Packet ID
  1186. */
  1187. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  1188. /**
  1189. * Set packet verb
  1190. *
  1191. * This also has the side-effect of clearing any verb flags, such as
  1192. * compressed, and so must only be done during packet composition.
  1193. *
  1194. * @param v New packet verb
  1195. */
  1196. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  1197. /**
  1198. * @return Packet verb (not including flag bits)
  1199. */
  1200. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  1201. /**
  1202. * @return Length of packet payload
  1203. */
  1204. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1205. /**
  1206. * @return Raw packet payload
  1207. */
  1208. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1209. /**
  1210. * Armor packet for transport
  1211. *
  1212. * @param key 32-byte key
  1213. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1214. */
  1215. void armor(const void *key,bool encryptPayload);
  1216. /**
  1217. * Verify and (if encrypted) decrypt packet
  1218. *
  1219. * This does not handle trusted path mode packets and will return false
  1220. * for these. These are handled in IncomingPacket if the sending physical
  1221. * address and MAC field match a trusted path.
  1222. *
  1223. * @param key 32-byte key
  1224. * @return False if packet is invalid or failed MAC authenticity check
  1225. */
  1226. bool dearmor(const void *key);
  1227. /**
  1228. * Attempt to compress payload if not already (must be unencrypted)
  1229. *
  1230. * This requires that the payload at least contain the verb byte already
  1231. * set. The compressed flag in the verb is set if compression successfully
  1232. * results in a size reduction. If no size reduction occurs, compression
  1233. * is not done and the flag is left cleared.
  1234. *
  1235. * @return True if compression occurred
  1236. */
  1237. bool compress();
  1238. /**
  1239. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1240. *
  1241. * If payload is compressed, it is decompressed and the compressed verb
  1242. * flag is cleared. Otherwise nothing is done and true is returned.
  1243. *
  1244. * @return True if data is now decompressed and valid, false on error
  1245. */
  1246. bool uncompress();
  1247. private:
  1248. static const unsigned char ZERO_KEY[32];
  1249. /**
  1250. * Deterministically mangle a 256-bit crypto key based on packet
  1251. *
  1252. * This uses extra data from the packet to mangle the secret, giving us an
  1253. * effective IV that is somewhat more than 64 bits. This is "free" for
  1254. * Salsa20 since it has negligible key setup time so using a different
  1255. * key each time is fine.
  1256. *
  1257. * @param in Input key (32 bytes)
  1258. * @param out Output buffer (32 bytes)
  1259. */
  1260. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1261. {
  1262. const unsigned char *d = (const unsigned char *)data();
  1263. // IV and source/destination addresses. Using the addresses divides the
  1264. // key space into two halves-- A->B and B->A (since order will change).
  1265. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1266. out[i] = in[i] ^ d[i];
  1267. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1268. // nodes. It's one of the only parts of a packet modifiable by people
  1269. // without the key.
  1270. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1271. // Raw packet size in bytes -- thus each packet size defines a new
  1272. // key space.
  1273. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1274. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1275. // Rest of raw key is used unchanged
  1276. for(unsigned int i=21;i<32;++i)
  1277. out[i] = in[i];
  1278. }
  1279. };
  1280. } // namespace ZeroTier
  1281. #endif