Packet.hpp 54 KB

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