Packet.hpp 52 KB

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