Packet.hpp 50 KB

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