Packet.hpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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 ... CURRENT
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  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. // Destination address types from HELLO, OK(HELLO), and other message types
  214. #define ZT_PROTO_DEST_ADDRESS_TYPE_NONE 0
  215. #define ZT_PROTO_DEST_ADDRESS_TYPE_ZEROTIER 1 // reserved but unused
  216. #define ZT_PROTO_DEST_ADDRESS_TYPE_ETHERNET 2 // future use
  217. #define ZT_PROTO_DEST_ADDRESS_TYPE_BLUETOOTH 3 // future use
  218. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV4 4
  219. #define ZT_PROTO_DEST_ADDRESS_TYPE_LTE_DIRECT 5 // future use
  220. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV6 6
  221. // Ephemeral key record flags
  222. #define ZT_PROTO_EPHEMERAL_KEY_FLAG_FIPS 0x01 // future use
  223. // Ephemeral key record symmetric cipher types
  224. #define ZT_PROTO_EPHEMERAL_KEY_SYMMETRIC_CIPHER_SALSA2012_POLY1305 0x01
  225. #define ZT_PROTO_EPHEMERAL_KEY_SYMMETRIC_CIPHER_AES256_GCM 0x02
  226. // Ephemeral key record public key types
  227. #define ZT_PROTO_EPHEMERAL_KEY_PK_C25519 0x01
  228. #define ZT_PROTO_EPHEMERAL_KEY_PK_NISTP256 0x02
  229. // Field incides for parsing verbs -------------------------------------------
  230. // Some verbs have variable-length fields. Those aren't fully defined here
  231. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  232. // See their respective handler functions.
  233. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  234. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  235. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  236. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  237. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  238. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  239. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  240. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  241. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  242. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  243. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  244. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  245. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  246. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  247. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  248. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  249. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  250. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  251. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  252. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  253. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  254. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  255. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  256. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  257. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  258. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  259. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  260. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  261. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  262. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  263. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  264. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  265. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  266. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  267. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  268. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  269. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  270. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  271. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  272. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  273. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  274. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  275. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  276. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  277. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  278. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  279. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  280. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  281. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  282. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  283. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  284. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  285. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  286. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  287. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  288. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  289. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  290. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  291. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  292. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  293. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  294. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  295. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  296. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  297. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  298. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  299. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  300. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  301. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  302. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  303. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  304. // ---------------------------------------------------------------------------
  305. namespace ZeroTier {
  306. /**
  307. * ZeroTier packet
  308. *
  309. * Packet format:
  310. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  311. * <[5] destination ZT address>
  312. * <[5] source ZT address>
  313. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  314. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  315. * [... -- begin encryption envelope -- ...]
  316. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  317. * [... verb-specific payload ...]
  318. *
  319. * Packets smaller than 28 bytes are invalid and silently discarded.
  320. *
  321. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  322. * selection allowing up to 7 cipher suites, F is outside-envelope flags,
  323. * and H is hop count.
  324. *
  325. * The three-bit hop count is the only part of a packet that is mutable in
  326. * transit without invalidating the MAC. All other bits in the packet are
  327. * immutable. This is because intermediate nodes can increment the hop
  328. * count up to 7 (protocol max).
  329. *
  330. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  331. *
  332. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  333. * sent in the clear, as it's the "here is my public key" message.
  334. */
  335. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  336. {
  337. public:
  338. /**
  339. * A packet fragment
  340. *
  341. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  342. * is sent with its normal header with the fragmented flag set. Remaining
  343. * fragments are sent this way.
  344. *
  345. * The fragmented bit indicates that there is at least one fragment. Fragments
  346. * themselves contain the total, so the receiver must "learn" this from the
  347. * first fragment it receives.
  348. *
  349. * Fragments are sent with the following format:
  350. * <[8] packet ID of packet whose fragment this belongs to>
  351. * <[5] destination ZT address>
  352. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  353. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  354. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  355. * <[...] fragment data>
  356. *
  357. * The protocol supports a maximum of 16 fragments. If a fragment is received
  358. * before its main packet header, it should be cached for a brief period of
  359. * time to see if its parent arrives. Loss of any fragment constitutes packet
  360. * loss; there is no retransmission mechanism. The receiver must wait for full
  361. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  362. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  363. */
  364. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  365. {
  366. public:
  367. Fragment() :
  368. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  369. {
  370. }
  371. template<unsigned int C2>
  372. Fragment(const Buffer<C2> &b)
  373. throw(std::out_of_range) :
  374. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  375. {
  376. }
  377. Fragment(const void *data,unsigned int len) :
  378. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  379. {
  380. }
  381. /**
  382. * Initialize from a packet
  383. *
  384. * @param p Original assembled packet
  385. * @param fragStart Start of fragment (raw index in packet data)
  386. * @param fragLen Length of fragment in bytes
  387. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  388. * @param fragTotal Total number of fragments (including 0)
  389. * @throws std::out_of_range Packet size would exceed buffer
  390. */
  391. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  392. throw(std::out_of_range)
  393. {
  394. init(p,fragStart,fragLen,fragNo,fragTotal);
  395. }
  396. /**
  397. * Initialize from a packet
  398. *
  399. * @param p Original assembled packet
  400. * @param fragStart Start of fragment (raw index in packet data)
  401. * @param fragLen Length of fragment in bytes
  402. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  403. * @param fragTotal Total number of fragments (including 0)
  404. * @throws std::out_of_range Packet size would exceed buffer
  405. */
  406. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  407. throw(std::out_of_range)
  408. {
  409. if ((fragStart + fragLen) > p.size())
  410. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  411. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  412. // NOTE: this copies both the IV/packet ID and the destination address.
  413. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  414. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  415. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  416. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  417. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  418. }
  419. /**
  420. * Get this fragment's destination
  421. *
  422. * @return Destination ZT address
  423. */
  424. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  425. /**
  426. * @return True if fragment is of a valid length
  427. */
  428. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  429. /**
  430. * @return ID of packet this is a fragment of
  431. */
  432. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  433. /**
  434. * @return Total number of fragments in packet
  435. */
  436. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  437. /**
  438. * @return Fragment number of this fragment
  439. */
  440. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  441. /**
  442. * @return Fragment ZT hop count
  443. */
  444. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  445. /**
  446. * Increment this packet's hop count
  447. */
  448. inline void incrementHops()
  449. {
  450. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  451. }
  452. /**
  453. * @return Length of payload in bytes
  454. */
  455. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  456. /**
  457. * @return Raw packet payload
  458. */
  459. inline const unsigned char *payload() const
  460. {
  461. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  462. }
  463. };
  464. /**
  465. * ZeroTier protocol verbs
  466. */
  467. enum Verb /* Max value: 32 (5 bits) */
  468. {
  469. /* No operation, payload ignored, no reply */
  470. VERB_NOP = 0,
  471. /* Announcement of a node's existence:
  472. * <[1] protocol version>
  473. * <[1] software major version>
  474. * <[1] software minor version>
  475. * <[2] software revision>
  476. * <[8] timestamp (ms since epoch)>
  477. * <[...] binary serialized identity (see Identity)>
  478. * <[1] destination address type>
  479. * [<[...] destination address>]
  480. *
  481. * This is the only message that ever must be sent in the clear, since it
  482. * is used to push an identity to a new peer.
  483. *
  484. * The destination address is the wire address to which this packet is
  485. * being sent, and in OK is *also* the destination address of the OK
  486. * packet. This can be used by the receiver to detect NAT, learn its real
  487. * external address if behind NAT, and detect changes to its external
  488. * address that require re-establishing connectivity.
  489. *
  490. * Destination address types and formats (not all of these are used now):
  491. * 0 - None -- no destination address data present
  492. * 1 - Ethernet address -- format: <[6] Ethernet MAC>
  493. * 4 - 6-byte IPv4 UDP address/port -- format: <[4] IP>, <[2] port>
  494. * 6 - 18-byte IPv6 UDP address/port -- format: <[16] IP>, <[2] port>
  495. *
  496. * OK payload:
  497. * <[8] timestamp (echoed from original HELLO)>
  498. * <[1] protocol version (of responder)>
  499. * <[1] software major version (of responder)>
  500. * <[1] software minor version (of responder)>
  501. * <[2] software revision (of responder)>
  502. * <[1] destination address type (for this OK, not copied from HELLO)>
  503. * [<[...] destination address>]
  504. *
  505. * ERROR has no payload.
  506. */
  507. VERB_HELLO = 1,
  508. /* Error response:
  509. * <[1] in-re verb>
  510. * <[8] in-re packet ID>
  511. * <[1] error code>
  512. * <[...] error-dependent payload>
  513. */
  514. VERB_ERROR = 2,
  515. /* Success response:
  516. * <[1] in-re verb>
  517. * <[8] in-re packet ID>
  518. * <[...] request-specific payload>
  519. */
  520. VERB_OK = 3,
  521. /* Query an identity by address:
  522. * <[5] address to look up>
  523. *
  524. * OK response payload:
  525. * <[...] binary serialized identity>
  526. *
  527. * ERROR response payload:
  528. * <[5] address>
  529. */
  530. VERB_WHOIS = 4,
  531. /* Meet another node at a given protocol address:
  532. * <[1] flags (unused, currently 0)>
  533. * <[5] ZeroTier address of peer that might be found at this address>
  534. * <[2] 16-bit protocol address port>
  535. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  536. * <[...] protocol address (network byte order)>
  537. *
  538. * This is sent by a relaying node to initiate NAT traversal between two
  539. * peers that are communicating by way of indirect relay. The relay will
  540. * send this to both peers at the same time on a periodic basis, telling
  541. * each where it might find the other on the network.
  542. *
  543. * Upon receipt a peer sends HELLO to establish a direct link.
  544. *
  545. * Nodes should implement rate control, limiting the rate at which they
  546. * respond to these packets to prevent their use in DDOS attacks. Nodes
  547. * may also ignore these messages if a peer is not known or is not being
  548. * actively communicated with.
  549. *
  550. * No OK or ERROR is generated.
  551. */
  552. VERB_RENDEZVOUS = 5,
  553. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  554. * <[8] 64-bit network ID>
  555. * <[2] 16-bit ethertype>
  556. * <[...] ethernet payload>
  557. *
  558. * MAC addresses are derived from the packet's source and destination
  559. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  560. * Ethernet framing and other optional flags and features when they
  561. * are not necessary.
  562. *
  563. * ERROR may be generated if a membership certificate is needed for a
  564. * closed network. Payload will be network ID.
  565. */
  566. VERB_FRAME = 6,
  567. /* Full Ethernet frame with MAC addressing and optional fields:
  568. * <[8] 64-bit network ID>
  569. * <[1] flags>
  570. * [<[...] certificate of network membership>]
  571. * <[6] destination MAC or all zero for destination node>
  572. * <[6] source MAC or all zero for node of origin>
  573. * <[2] 16-bit ethertype>
  574. * <[...] ethernet payload>
  575. *
  576. * Flags:
  577. * 0x01 - Certificate of network membership is attached
  578. *
  579. * An extended frame carries full MAC addressing, making them a
  580. * superset of VERB_FRAME. They're used for bridging or when we
  581. * want to attach a certificate since FRAME does not support that.
  582. *
  583. * Multicast frames may not be sent as EXT_FRAME.
  584. *
  585. * ERROR may be generated if a membership certificate is needed for a
  586. * closed network. Payload will be network ID.
  587. */
  588. VERB_EXT_FRAME = 7,
  589. /* DEPRECATED */
  590. VERB_P5_MULTICAST_FRAME = 8,
  591. /* Announce interest in multicast group(s):
  592. * <[8] 64-bit network ID>
  593. * <[6] multicast Ethernet address>
  594. * <[4] multicast additional distinguishing information (ADI)>
  595. * [... additional tuples of network/address/adi ...]
  596. *
  597. * LIKEs are sent to peers with whom you have a direct peer to peer
  598. * connection, and always including root servers.
  599. *
  600. * OK/ERROR are not generated.
  601. */
  602. VERB_MULTICAST_LIKE = 9,
  603. /* Network member certificate replication/push:
  604. * <[...] serialized certificate of membership>
  605. * [ ... additional certificates may follow ...]
  606. *
  607. * This is sent in response to ERROR_NEED_MEMBERSHIP_CERTIFICATE and may
  608. * be pushed at any other time to keep exchanged certificates up to date.
  609. *
  610. * OK/ERROR are not generated.
  611. */
  612. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  613. /* Network configuration request:
  614. * <[8] 64-bit network ID>
  615. * <[2] 16-bit length of request meta-data dictionary>
  616. * <[...] string-serialized request meta-data>
  617. * [<[8] 64-bit revision of netconf we currently have>]
  618. *
  619. * This message requests network configuration from a node capable of
  620. * providing it. If the optional revision is included, a response is
  621. * only generated if there is a newer network configuration available.
  622. *
  623. * OK response payload:
  624. * <[8] 64-bit network ID>
  625. * <[2] 16-bit length of network configuration dictionary>
  626. * <[...] network configuration dictionary>
  627. *
  628. * OK returns a Dictionary (string serialized) containing the network's
  629. * configuration and IP address assignment information for the querying
  630. * node. It also contains a membership certificate that the querying
  631. * node can push to other peers to demonstrate its right to speak on
  632. * a given network.
  633. *
  634. * When a new network configuration is received, another config request
  635. * should be sent with the new netconf's revision. This confirms receipt
  636. * and also causes any subsequent changes to rapidly propagate as this
  637. * cycle will repeat until there are no changes. This is optional but
  638. * recommended behavior.
  639. *
  640. * ERROR response payload:
  641. * <[8] 64-bit network ID>
  642. *
  643. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  644. * and OBJ_NOT_FOUND if the queried network ID was not found.
  645. */
  646. VERB_NETWORK_CONFIG_REQUEST = 11,
  647. /* Network configuration refresh request:
  648. * <[...] array of 64-bit network IDs>
  649. *
  650. * This can be sent by the network controller to inform a node that it
  651. * should now make a NETWORK_CONFIG_REQUEST.
  652. *
  653. * It does not generate an OK or ERROR message, and is treated only as
  654. * a hint to refresh now.
  655. */
  656. VERB_NETWORK_CONFIG_REFRESH = 12,
  657. /* Request endpoints for multicast distribution:
  658. * <[8] 64-bit network ID>
  659. * <[1] flags>
  660. * <[6] MAC address of multicast group being queried>
  661. * <[4] 32-bit ADI for multicast group being queried>
  662. * <[4] 32-bit requested max number of multicast peers>
  663. * [<[...] network certificate of membership>]
  664. *
  665. * Flags:
  666. * 0x01 - Network certificate of membership is attached
  667. *
  668. * This message asks a peer for additional known endpoints that have
  669. * LIKEd a given multicast group. It's sent when the sender wishes
  670. * to send multicast but does not have the desired number of recipient
  671. * peers.
  672. *
  673. * OK response payload:
  674. * <[8] 64-bit network ID>
  675. * <[6] MAC address of multicast group being queried>
  676. * <[4] 32-bit ADI for multicast group being queried>
  677. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  678. * <[4] 32-bit total number of known members in this multicast group>
  679. * <[2] 16-bit number of members enumerated in this packet>
  680. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  681. *
  682. * If no endpoints are known, OK and ERROR are both optional. It's okay
  683. * to return nothing in that case since gathering is "lazy."
  684. *
  685. * ERROR response payload:
  686. * <[8] 64-bit network ID>
  687. * <[6] MAC address of multicast group being queried>
  688. * <[4] 32-bit ADI for multicast group being queried>
  689. *
  690. * ERRORs are optional and are only generated if permission is denied,
  691. * certificate of membership is out of date, etc.
  692. */
  693. VERB_MULTICAST_GATHER = 13,
  694. /* Multicast frame:
  695. * <[8] 64-bit network ID>
  696. * <[1] flags>
  697. * [<[...] network certificate of membership>]
  698. * [<[4] 32-bit implicit gather limit>]
  699. * [<[6] source MAC>]
  700. * <[6] destination MAC (multicast address)>
  701. * <[4] 32-bit multicast ADI (multicast address extension)>
  702. * <[2] 16-bit ethertype>
  703. * <[...] ethernet payload>
  704. *
  705. * Flags:
  706. * 0x01 - Network certificate of membership is attached
  707. * 0x02 - Implicit gather limit field is present
  708. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  709. *
  710. * OK and ERROR responses are optional. OK may be generated if there are
  711. * implicit gather results or if the recipient wants to send its own
  712. * updated certificate of network membership to the sender. ERROR may be
  713. * generated if a certificate is needed or if multicasts to this group
  714. * are no longer wanted (multicast unsubscribe).
  715. *
  716. * OK response payload:
  717. * <[8] 64-bit network ID>
  718. * <[6] MAC address of multicast group>
  719. * <[4] 32-bit ADI for multicast group>
  720. * <[1] flags>
  721. * [<[...] network certficate of membership>]
  722. * [<[...] implicit gather results if flag 0x01 is set>]
  723. *
  724. * OK flags (same bits as request flags):
  725. * 0x01 - OK includes certificate of network membership
  726. * 0x02 - OK includes implicit gather results
  727. *
  728. * ERROR response payload:
  729. * <[8] 64-bit network ID>
  730. * <[6] multicast group MAC>
  731. * <[4] 32-bit multicast group ADI>
  732. */
  733. VERB_MULTICAST_FRAME = 14,
  734. /* Ephemeral (PFS) key push: (UNFINISHED, NOT IMPLEMENTED YET)
  735. * <[2] flags (unused and reserved, must be 0)>
  736. * <[2] length of padding / extra field section>
  737. * <[...] padding / extra field section>
  738. * <[8] 64-bit PFS key set ID sender holds for recipient (0==none)>
  739. * <[8] 64-bit PFS key set ID of this key set>
  740. * [... begin PFS key record ...]
  741. * <[1] flags>
  742. * <[1] symmetric cipher ID>
  743. * <[1] public key type ID>
  744. * <[2] public key length in bytes>
  745. * <[...] public key>
  746. * [... additional records may follow up to max packet length ...]
  747. *
  748. * This message is sent to negotiate an ephemeral key. If the recipient's
  749. * current key pair for the sender does not match the one the sender
  750. * claims to have on file, it must respond with its own SET_EPHEMERAL_KEY.
  751. *
  752. * PFS key IDs are random and must not be zero, since zero indicates that
  753. * the sender does not have an ephemeral key on file for the recipient.
  754. *
  755. * One or more records may be sent. If multiple records are present,
  756. * the first record with common symmetric cipher, public key type,
  757. * and relevant flags must be used.
  758. *
  759. * The padding section may be filled with an arbitrary amount of random
  760. * or empty payload. This may be used as a countermeasure to prevent PFS
  761. * key pushes from being recognized by packet size vs. other packets in
  762. * the stream. This also provides potential space for additional fields
  763. * that might be indicated in the future by flags.
  764. *
  765. * Flags (all unspecified flags must be zero):
  766. * 0x01 - FIPS mode, only use record if FIPS compliant crypto in use
  767. *
  768. * Symmetric cipher IDs:
  769. * 0x01 - Salsa20/12 with Poly1305 authentication (ZT default)
  770. * 0x02 - AES256-GCM combined crypto and authentication
  771. *
  772. * Public key types:
  773. * 0x01 - Curve25519 ECDH with SHA-512 KDF
  774. * 0x02 - NIST P-256 ECDH with SHA-512 KDF
  775. *
  776. * Once both peers have a PFS key, they will attempt to send PFS key
  777. * encrypted messages with the PFS flag set using the negotiated
  778. * cipher/auth type.
  779. *
  780. * Note: most of these features such as FIPS and other cipher suites are
  781. * not implemented yet. They're just specified in the protocol for future
  782. * use to support e.g. FIPS requirements.
  783. *
  784. * OK response payload:
  785. * <[8] PFS key set ID of received key set>
  786. * <[1] index in record list of chosen key record>
  787. */
  788. VERB_SET_EPHEMERAL_KEY = 15,
  789. /* Push of potential endpoints for direct communication:
  790. * <[2] 16-bit number of paths>
  791. * <[...] paths>
  792. *
  793. * Path record format:
  794. * <[1] flags>
  795. * <[1] metric from 0 (highest priority) to 255 (lowest priority)>
  796. * <[2] length of extended path characteristics or 0 for none>
  797. * <[...] extended path characteristics>
  798. * <[1] address type>
  799. * <[1] address length in bytes>
  800. * <[...] address>
  801. *
  802. * Path record flags:
  803. * 0x01 - Forget this path if it is currently known
  804. * 0x02 - Blacklist this path, do not use
  805. * 0x04 - Reliable path (no NAT keepalives, etc. are necessary)
  806. * 0x08 - Disable encryption (trust: privacy)
  807. * 0x10 - Disable encryption and authentication (trust: ultimate)
  808. *
  809. * Address types and addresses are of the same format as the destination
  810. * address type and address in HELLO.
  811. *
  812. * The receiver may, upon receiving a push, attempt to establish a
  813. * direct link to one or more of the indicated addresses. It is the
  814. * responsibility of the sender to limit which peers it pushes direct
  815. * paths to to those with whom it has a trust relationship. The receiver
  816. * must obey any restrictions provided such as exclusivity or blacklists.
  817. * OK responses to this message are optional.
  818. *
  819. * Note that a direct path push does not imply that learned paths can't
  820. * be used unless they are blacklisted explicitly or unless flag 0x01
  821. * is set.
  822. *
  823. * Only a subset of this functionality is currently implemented: basic
  824. * path pushing and learning. Metrics, most flags, and OK responses are
  825. * not yet implemented as of 1.0.4.
  826. *
  827. * OK response payload:
  828. * <[2] 16-bit number of active direct paths we already have>
  829. * <[2] 16-bit number of paths in push that we don't already have>
  830. * <[2] 16-bit number of new paths we are trying (or will try)>
  831. *
  832. * ERROR is presently not sent.
  833. */
  834. VERB_PUSH_DIRECT_PATHS = 16
  835. };
  836. /**
  837. * Error codes for VERB_ERROR
  838. */
  839. enum ErrorCode
  840. {
  841. /* No error, not actually used in transit */
  842. ERROR_NONE = 0,
  843. /* Invalid request */
  844. ERROR_INVALID_REQUEST = 1,
  845. /* Bad/unsupported protocol version */
  846. ERROR_BAD_PROTOCOL_VERSION = 2,
  847. /* Unknown object queried (e.g. with WHOIS) */
  848. ERROR_OBJ_NOT_FOUND = 3,
  849. /* HELLO pushed an identity whose address is already claimed */
  850. ERROR_IDENTITY_COLLISION = 4,
  851. /* Verb or use case not supported/enabled by this node */
  852. ERROR_UNSUPPORTED_OPERATION = 5,
  853. /* Message to private network rejected -- no unexpired certificate on file */
  854. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  855. /* Tried to join network, but you're not a member */
  856. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  857. /* Multicasts to this group are not wanted */
  858. ERROR_UNWANTED_MULTICAST = 8
  859. };
  860. /**
  861. * @param v Verb
  862. * @return String representation (e.g. HELLO, OK)
  863. */
  864. static const char *verbString(Verb v)
  865. throw();
  866. /**
  867. * @param e Error code
  868. * @return String error name
  869. */
  870. static const char *errorString(ErrorCode e)
  871. throw();
  872. template<unsigned int C2>
  873. Packet(const Buffer<C2> &b) :
  874. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  875. {
  876. }
  877. Packet(const void *data,unsigned int len) :
  878. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  879. {
  880. }
  881. /**
  882. * Construct a new empty packet with a unique random packet ID
  883. *
  884. * Flags and hops will be zero. Other fields and data region are undefined.
  885. * Use the header access methods (setDestination() and friends) to fill out
  886. * the header. Payload should be appended; initial size is header size.
  887. */
  888. Packet() :
  889. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  890. {
  891. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  892. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  893. }
  894. /**
  895. * Make a copy of a packet with a new initialization vector and destination address
  896. *
  897. * This can be used to take one draft prototype packet and quickly make copies to
  898. * encrypt for different destinations.
  899. *
  900. * @param prototype Prototype packet
  901. * @param dest Destination ZeroTier address for new packet
  902. */
  903. Packet(const Packet &prototype,const Address &dest) :
  904. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  905. {
  906. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  907. setDestination(dest);
  908. }
  909. /**
  910. * Construct a new empty packet with a unique random packet ID
  911. *
  912. * @param dest Destination ZT address
  913. * @param source Source ZT address
  914. * @param v Verb
  915. */
  916. Packet(const Address &dest,const Address &source,const Verb v) :
  917. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  918. {
  919. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  920. setDestination(dest);
  921. setSource(source);
  922. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  923. setVerb(v);
  924. }
  925. /**
  926. * Reset this packet structure for reuse in place
  927. *
  928. * @param dest Destination ZT address
  929. * @param source Source ZT address
  930. * @param v Verb
  931. */
  932. inline void reset(const Address &dest,const Address &source,const Verb v)
  933. {
  934. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  935. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  936. setDestination(dest);
  937. setSource(source);
  938. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags, cipher ID, and hops
  939. setVerb(v);
  940. }
  941. /**
  942. * Generate a new IV / packet ID in place
  943. *
  944. * This can be used to re-use a packet buffer multiple times to send
  945. * technically different but otherwise identical copies of the same
  946. * packet.
  947. */
  948. inline void newInitializationVector() { Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8); }
  949. /**
  950. * Set this packet's destination
  951. *
  952. * @param dest ZeroTier address of destination
  953. */
  954. inline void setDestination(const Address &dest) { dest.copyTo(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  955. /**
  956. * Set this packet's source
  957. *
  958. * @param source ZeroTier address of source
  959. */
  960. inline void setSource(const Address &source) { source.copyTo(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  961. /**
  962. * Get this packet's destination
  963. *
  964. * @return Destination ZT address
  965. */
  966. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  967. /**
  968. * Get this packet's source
  969. *
  970. * @return Source ZT address
  971. */
  972. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  973. /**
  974. * @return True if packet is of valid length
  975. */
  976. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  977. /**
  978. * @return True if packet is fragmented (expect fragments)
  979. */
  980. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  981. /**
  982. * Set this packet's fragmented flag
  983. *
  984. * @param f Fragmented flag value
  985. */
  986. inline void setFragmented(bool f)
  987. {
  988. if (f)
  989. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  990. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  991. }
  992. /**
  993. * @return True if compressed (result only valid if unencrypted)
  994. */
  995. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  996. /**
  997. * @return ZeroTier forwarding hops (0 to 7)
  998. */
  999. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  1000. /**
  1001. * Increment this packet's hop count
  1002. */
  1003. inline void incrementHops()
  1004. {
  1005. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1006. b = (b & 0xf8) | ((b + 1) & 0x07);
  1007. }
  1008. /**
  1009. * @return Cipher suite selector: 0 - 7 (see #defines)
  1010. */
  1011. inline unsigned int cipher() const
  1012. {
  1013. // Note: this uses the new cipher spec field, which is incompatible with <1.0.0 peers
  1014. return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  1015. }
  1016. /**
  1017. * Set this packet's cipher suite
  1018. */
  1019. inline void setCipher(unsigned int c)
  1020. {
  1021. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  1022. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38); // bits: FFCCCHHH
  1023. // DEPRECATED "encrypted" flag -- used by pre-1.0.3 peers
  1024. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  1025. b |= ZT_PROTO_FLAG_ENCRYPTED;
  1026. else b &= (~ZT_PROTO_FLAG_ENCRYPTED);
  1027. }
  1028. /**
  1029. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  1030. *
  1031. * @return Packet ID
  1032. */
  1033. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  1034. /**
  1035. * Set packet verb
  1036. *
  1037. * This also has the side-effect of clearing any verb flags, such as
  1038. * compressed, and so must only be done during packet composition.
  1039. *
  1040. * @param v New packet verb
  1041. */
  1042. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  1043. /**
  1044. * @return Packet verb (not including flag bits)
  1045. */
  1046. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  1047. /**
  1048. * @return Length of packet payload
  1049. */
  1050. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  1051. /**
  1052. * @return Raw packet payload
  1053. */
  1054. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  1055. /**
  1056. * Armor packet for transport
  1057. *
  1058. * @param key 32-byte key
  1059. * @param encryptPayload If true, encrypt packet payload, else just MAC
  1060. */
  1061. void armor(const void *key,bool encryptPayload);
  1062. /**
  1063. * Verify and (if encrypted) decrypt packet
  1064. *
  1065. * @param key 32-byte key
  1066. * @return False if packet is invalid or failed MAC authenticity check
  1067. */
  1068. bool dearmor(const void *key);
  1069. /**
  1070. * Attempt to compress payload if not already (must be unencrypted)
  1071. *
  1072. * This requires that the payload at least contain the verb byte already
  1073. * set. The compressed flag in the verb is set if compression successfully
  1074. * results in a size reduction. If no size reduction occurs, compression
  1075. * is not done and the flag is left cleared.
  1076. *
  1077. * @return True if compression occurred
  1078. */
  1079. bool compress();
  1080. /**
  1081. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1082. *
  1083. * If payload is compressed, it is decompressed and the compressed verb
  1084. * flag is cleared. Otherwise nothing is done and true is returned.
  1085. *
  1086. * @return True if data is now decompressed and valid, false on error
  1087. */
  1088. bool uncompress();
  1089. private:
  1090. static const unsigned char ZERO_KEY[32];
  1091. /**
  1092. * Deterministically mangle a 256-bit crypto key based on packet
  1093. *
  1094. * This uses extra data from the packet to mangle the secret, giving us an
  1095. * effective IV that is somewhat more than 64 bits. This is "free" for
  1096. * Salsa20 since it has negligible key setup time so using a different
  1097. * key each time is fine.
  1098. *
  1099. * @param in Input key (32 bytes)
  1100. * @param out Output buffer (32 bytes)
  1101. */
  1102. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1103. {
  1104. const unsigned char *d = (const unsigned char *)data();
  1105. // IV and source/destination addresses. Using the addresses divides the
  1106. // key space into two halves-- A->B and B->A (since order will change).
  1107. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1108. out[i] = in[i] ^ d[i];
  1109. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1110. // nodes. It's one of the only parts of a packet modifiable by people
  1111. // without the key.
  1112. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1113. // Raw packet size in bytes -- thus each packet size defines a new
  1114. // key space.
  1115. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1116. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1117. // Rest of raw key is used unchanged
  1118. for(unsigned int i=21;i<32;++i)
  1119. out[i] = in[i];
  1120. }
  1121. };
  1122. } // namespace ZeroTier
  1123. #endif