Packet.hpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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 not necessarily the maximum hop counter after which
  66. * relaying is no longer performed.
  67. */
  68. #define ZT_PROTO_MAX_HOPS 7
  69. /**
  70. * Cipher suite: Curve25519/Poly1305/Salsa20/12 without payload encryption
  71. *
  72. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  73. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  74. * but the payload is not encrypted. This is currently only used to send
  75. * HELLO since that's the public key specification packet and must be
  76. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  77. * curve Diffie-Hellman.
  78. */
  79. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  80. /**
  81. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  82. *
  83. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  84. * stream as its one-time-use key followed by payload encryption with
  85. * the remaining Salsa20/12 key stream. Key agreement is performed using
  86. * Curve25519 elliptic curve Diffie-Hellman.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  89. /**
  90. * Cipher suite: Curve25519/AES256-GCM
  91. *
  92. * This specifies AES256 in GCM mode using GCM's built-in authentication
  93. * with Curve25519 elliptic curve Diffie-Hellman.
  94. *
  95. * (Not implemented yet in client but reserved for future use.)
  96. */
  97. #define ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM 2
  98. /**
  99. * Header flag indicating that a packet is fragmented
  100. *
  101. * If this flag is set, the receiver knows to expect more than one fragment.
  102. * See Packet::Fragment for details.
  103. */
  104. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  105. /**
  106. * Verb flag indicating payload is compressed with LZ4
  107. */
  108. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  109. /**
  110. * Rounds used for Salsa20 encryption in ZT
  111. */
  112. #define ZT_PROTO_SALSA20_ROUNDS 12
  113. // Indices of fields in normal packet header -- do not change as this
  114. // might require both code rework and will break compatibility.
  115. #define ZT_PACKET_IDX_IV 0
  116. #define ZT_PACKET_IDX_DEST 8
  117. #define ZT_PACKET_IDX_SOURCE 13
  118. #define ZT_PACKET_IDX_FLAGS 18
  119. #define ZT_PACKET_IDX_MAC 19
  120. #define ZT_PACKET_IDX_VERB 27
  121. #define ZT_PACKET_IDX_PAYLOAD 28
  122. /**
  123. * Packet buffer size (can be changed)
  124. */
  125. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  126. /**
  127. * Minimum viable packet length (also length of header)
  128. */
  129. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  130. // Indexes of fields in fragment header -- also can't be changed without
  131. // breaking compatibility.
  132. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  133. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  134. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  135. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  136. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  137. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  138. /**
  139. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  140. */
  141. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  142. /**
  143. * Minimum viable fragment length
  144. */
  145. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  146. /**
  147. * Length of LAN beacon packets
  148. */
  149. #define ZT_PROTO_BEACON_LENGTH 13
  150. /**
  151. * Index of address in a LAN beacon
  152. */
  153. #define ZT_PROTO_BEACON_IDX_ADDRESS 8
  154. // Destination address types from HELLO and OK(HELLO)
  155. #define ZT_PROTO_DEST_ADDRESS_TYPE_NONE 0
  156. #define ZT_PROTO_DEST_ADDRESS_TYPE_ETHERNET 1
  157. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV4 4
  158. #define ZT_PROTO_DEST_ADDRESS_TYPE_IPV6 6
  159. // Field incides for parsing verbs -------------------------------------------
  160. // Some verbs have variable-length fields. Those aren't fully defined here
  161. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  162. // See their respective handler functions.
  163. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  164. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  165. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  166. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  167. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  168. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  169. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  170. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  171. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  172. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  173. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  174. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  175. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  176. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  177. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  178. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  179. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  180. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  181. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  182. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  183. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  184. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  185. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  186. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  187. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  188. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  189. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  190. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  191. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  192. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  193. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  194. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  195. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  196. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  197. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  198. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  199. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  200. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  201. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  202. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  203. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  204. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  205. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  206. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  207. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  208. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  209. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  210. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  211. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  212. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  213. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  214. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  215. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  216. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  217. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  218. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  219. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  220. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  221. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  222. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  223. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  224. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  225. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  226. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  227. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  228. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  229. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  230. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  231. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  232. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  233. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  234. // ---------------------------------------------------------------------------
  235. namespace ZeroTier {
  236. /**
  237. * ZeroTier packet
  238. *
  239. * Packet format:
  240. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  241. * <[5] destination ZT address>
  242. * <[5] source ZT address>
  243. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  244. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  245. * [... -- begin encryption envelope -- ...]
  246. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  247. * [... verb-specific payload ...]
  248. *
  249. * Packets smaller than 28 bytes are invalid and silently discarded.
  250. *
  251. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  252. * selection allowing up to 8 cipher suites, F is flags (reserved, currently
  253. * all zero), and H is hop count.
  254. *
  255. * The three-bit hop count is the only part of a packet that is mutable in
  256. * transit without invalidating the MAC. All other bits in the packet are
  257. * immutable. This is because intermediate nodes can increment the hop
  258. * count up to 7 (protocol max).
  259. *
  260. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  261. *
  262. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  263. * sent in the clear, as it's the "here is my public key" message.
  264. *
  265. * Beacon format and beacon packets:
  266. * <[8] 8 random bytes>
  267. * <[5] sender ZT address>
  268. *
  269. * A beacon is a 13-byte packet containing only the address of the sender.
  270. * Receiving peers may or may not respond to beacons with a HELLO or other
  271. * message to initiate direct communication.
  272. *
  273. * Beacons may be used for direct LAN announcement or NAT traversal.
  274. */
  275. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  276. {
  277. public:
  278. /**
  279. * A packet fragment
  280. *
  281. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  282. * is sent with its normal header with the fragmented flag set. Remaining
  283. * fragments are sent this way.
  284. *
  285. * The fragmented bit indicates that there is at least one fragment. Fragments
  286. * themselves contain the total, so the receiver must "learn" this from the
  287. * first fragment it receives.
  288. *
  289. * Fragments are sent with the following format:
  290. * <[8] packet ID of packet whose fragment this belongs to>
  291. * <[5] destination ZT address>
  292. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  293. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  294. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  295. * <[...] fragment data>
  296. *
  297. * The protocol supports a maximum of 16 fragments. If a fragment is received
  298. * before its main packet header, it should be cached for a brief period of
  299. * time to see if its parent arrives. Loss of any fragment constitutes packet
  300. * loss; there is no retransmission mechanism. The receiver must wait for full
  301. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  302. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  303. */
  304. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  305. {
  306. public:
  307. Fragment() :
  308. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  309. {
  310. }
  311. template<unsigned int C2>
  312. Fragment(const Buffer<C2> &b)
  313. throw(std::out_of_range) :
  314. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  315. {
  316. }
  317. Fragment(const void *data,unsigned int len) :
  318. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  319. {
  320. }
  321. /**
  322. * Initialize from a packet
  323. *
  324. * @param p Original assembled packet
  325. * @param fragStart Start of fragment (raw index in packet data)
  326. * @param fragLen Length of fragment in bytes
  327. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  328. * @param fragTotal Total number of fragments (including 0)
  329. * @throws std::out_of_range Packet size would exceed buffer
  330. */
  331. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  332. throw(std::out_of_range)
  333. {
  334. init(p,fragStart,fragLen,fragNo,fragTotal);
  335. }
  336. /**
  337. * Initialize from a packet
  338. *
  339. * @param p Original assembled packet
  340. * @param fragStart Start of fragment (raw index in packet data)
  341. * @param fragLen Length of fragment in bytes
  342. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  343. * @param fragTotal Total number of fragments (including 0)
  344. * @throws std::out_of_range Packet size would exceed buffer
  345. */
  346. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  347. throw(std::out_of_range)
  348. {
  349. if ((fragStart + fragLen) > p.size())
  350. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  351. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  352. // NOTE: this copies both the IV/packet ID and the destination address.
  353. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  354. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  355. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  356. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  357. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  358. }
  359. /**
  360. * Get this fragment's destination
  361. *
  362. * @return Destination ZT address
  363. */
  364. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  365. /**
  366. * @return True if fragment is of a valid length
  367. */
  368. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  369. /**
  370. * @return ID of packet this is a fragment of
  371. */
  372. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  373. /**
  374. * @return Total number of fragments in packet
  375. */
  376. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  377. /**
  378. * @return Fragment number of this fragment
  379. */
  380. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  381. /**
  382. * @return Fragment ZT hop count
  383. */
  384. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  385. /**
  386. * Increment this packet's hop count
  387. */
  388. inline void incrementHops()
  389. {
  390. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  391. }
  392. /**
  393. * @return Length of payload in bytes
  394. */
  395. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  396. /**
  397. * @return Raw packet payload
  398. */
  399. inline const unsigned char *payload() const
  400. {
  401. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  402. }
  403. };
  404. /**
  405. * ZeroTier protocol verbs
  406. */
  407. enum Verb /* Max value: 32 (5 bits) */
  408. {
  409. /* No operation, payload ignored, no reply */
  410. VERB_NOP = 0,
  411. /* Announcement of a node's existence:
  412. * <[1] protocol version>
  413. * <[1] software major version>
  414. * <[1] software minor version>
  415. * <[2] software revision>
  416. * <[8] timestamp (ms since epoch)>
  417. * <[...] binary serialized identity (see Identity)>
  418. * <[1] destination address type>
  419. * [<[...] destination address>]
  420. *
  421. * This is the only message that ever must be sent in the clear, since it
  422. * is used to push an identity to a new peer.
  423. *
  424. * The destination address is the wire address to which this packet is
  425. * being sent, and in OK is *also* the destination address of the OK
  426. * packet. This can be used by the receiver to detect NAT, learn its real
  427. * external address if behind NAT, and detect changes to its external
  428. * address that require re-establishing connectivity.
  429. *
  430. * Destination address types and formats (not all of these are used now):
  431. * 0 - None -- no destination address data present
  432. * 1 - Ethernet address -- format: <[6] Ethernet MAC>
  433. * 4 - 6-byte IPv4 address -- format: <[4] IP>, <[2] port>
  434. * 6 - 18-byte IPv6 address -- format: <[16] IP>, <[2] port>
  435. *
  436. * OK payload:
  437. * <[8] timestamp (echoed from original HELLO)>
  438. * <[1] protocol version (of responder)>
  439. * <[1] software major version (of responder)>
  440. * <[1] software minor version (of responder)>
  441. * <[2] software revision (of responder)>
  442. * <[1] destination address type (for this OK, not copied from HELLO)>
  443. * [<[...] destination address>]
  444. *
  445. * ERROR has no payload.
  446. */
  447. VERB_HELLO = 1,
  448. /* Error response:
  449. * <[1] in-re verb>
  450. * <[8] in-re packet ID>
  451. * <[1] error code>
  452. * <[...] error-dependent payload>
  453. */
  454. VERB_ERROR = 2,
  455. /* Success response:
  456. * <[1] in-re verb>
  457. * <[8] in-re packet ID>
  458. * <[...] request-specific payload>
  459. */
  460. VERB_OK = 3,
  461. /* Query an identity by address:
  462. * <[5] address to look up>
  463. *
  464. * OK response payload:
  465. * <[...] binary serialized identity>
  466. *
  467. * ERROR response payload:
  468. * <[5] address>
  469. */
  470. VERB_WHOIS = 4,
  471. /* Meet another node at a given protocol address:
  472. * <[1] flags (unused, currently 0)>
  473. * <[5] ZeroTier address of peer that might be found at this address>
  474. * <[2] 16-bit protocol address port>
  475. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  476. * <[...] protocol address (network byte order)>
  477. *
  478. * This is sent by a relaying node to initiate NAT traversal between two
  479. * peers that are communicating by way of indirect relay. The relay will
  480. * send this to both peers at the same time on a periodic basis, telling
  481. * each where it might find the other on the network.
  482. *
  483. * Upon receipt a peer sends HELLO to establish a direct link.
  484. *
  485. * Nodes should implement rate control, limiting the rate at which they
  486. * respond to these packets to prevent their use in DDOS attacks. Nodes
  487. * may also ignore these messages if a peer is not known or is not being
  488. * actively communicated with.
  489. *
  490. * No OK or ERROR is generated.
  491. */
  492. VERB_RENDEZVOUS = 5,
  493. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  494. * <[8] 64-bit network ID>
  495. * <[2] 16-bit ethertype>
  496. * <[...] ethernet payload>
  497. *
  498. * MAC addresses are derived from the packet's source and destination
  499. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  500. * Ethernet framing and other optional flags and features when they
  501. * are not necessary.
  502. *
  503. * ERROR may be generated if a membership certificate is needed for a
  504. * closed network. Payload will be network ID.
  505. */
  506. VERB_FRAME = 6,
  507. /* Full Ethernet frame with MAC addressing and optional fields:
  508. * <[8] 64-bit network ID>
  509. * <[1] flags>
  510. * [<[...] certificate of network membership>]
  511. * <[6] destination MAC or all zero for destination node>
  512. * <[6] source MAC or all zero for node of origin>
  513. * <[2] 16-bit ethertype>
  514. * <[...] ethernet payload>
  515. *
  516. * Flags:
  517. * 0x01 - Certificate of network membership is attached
  518. *
  519. * An extended frame carries full MAC addressing, making them a
  520. * superset of VERB_FRAME. They're used for bridging or when we
  521. * want to attach a certificate since FRAME does not support that.
  522. *
  523. * Multicast frames may not be sent as EXT_FRAME.
  524. *
  525. * ERROR may be generated if a membership certificate is needed for a
  526. * closed network. Payload will be network ID.
  527. */
  528. VERB_EXT_FRAME = 7,
  529. /* DEPRECATED */
  530. VERB_P5_MULTICAST_FRAME = 8,
  531. /* Announce interest in multicast group(s):
  532. * <[8] 64-bit network ID>
  533. * <[6] multicast Ethernet address>
  534. * <[4] multicast additional distinguishing information (ADI)>
  535. * [... additional tuples of network/address/adi ...]
  536. *
  537. * LIKEs are sent to peers with whom you have a direct peer to peer
  538. * connection, and always including supernodes.
  539. *
  540. * OK/ERROR are not generated.
  541. */
  542. VERB_MULTICAST_LIKE = 9,
  543. /* Network member certificate replication/push:
  544. * <[...] serialized certificate of membership>
  545. * [ ... additional certificates may follow ...]
  546. *
  547. * Certificate contains network ID, peer it was issued for, etc.
  548. *
  549. * OK/ERROR are not generated.
  550. */
  551. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  552. /* Network configuration request:
  553. * <[8] 64-bit network ID>
  554. * <[2] 16-bit length of request meta-data dictionary>
  555. * <[...] string-serialized request meta-data>
  556. * [<[8] 64-bit revision of netconf we currently have>]
  557. *
  558. * This message requests network configuration from a node capable of
  559. * providing it. If the optional revision is included, a response is
  560. * only generated if there is a newer network configuration available.
  561. *
  562. * OK response payload:
  563. * <[8] 64-bit network ID>
  564. * <[2] 16-bit length of network configuration dictionary>
  565. * <[...] network configuration dictionary>
  566. *
  567. * OK returns a Dictionary (string serialized) containing the network's
  568. * configuration and IP address assignment information for the querying
  569. * node. It also contains a membership certificate that the querying
  570. * node can push to other peers to demonstrate its right to speak on
  571. * a given network.
  572. *
  573. * When a new network configuration is received, another config request
  574. * should be sent with the new netconf's revision. This confirms receipt
  575. * and also causes any subsequent changes to rapidly propagate as this
  576. * cycle will repeat until there are no changes. This is optional but
  577. * recommended behavior.
  578. *
  579. * ERROR response payload:
  580. * <[8] 64-bit network ID>
  581. *
  582. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  583. * and OBJ_NOT_FOUND if the queried network ID was not found.
  584. */
  585. VERB_NETWORK_CONFIG_REQUEST = 11,
  586. /* Network configuration refresh request:
  587. * <[...] array of 64-bit network IDs>
  588. *
  589. * This message can be sent by the network configuration master node
  590. * to request that nodes refresh their network configuration. It can
  591. * thus be used to "push" updates so that network config changes will
  592. * take effect quickly.
  593. *
  594. * It does not generate an OK or ERROR message, and is treated only as
  595. * a hint to refresh now.
  596. */
  597. VERB_NETWORK_CONFIG_REFRESH = 12,
  598. /* Request endpoints for multicast distribution:
  599. * <[8] 64-bit network ID>
  600. * <[1] flags>
  601. * <[6] MAC address of multicast group being queried>
  602. * <[4] 32-bit ADI for multicast group being queried>
  603. * <[4] 32-bit requested max number of multicast peers>
  604. * [<[...] network certificate of membership>]
  605. *
  606. * Flags:
  607. * 0x01 - Network certificate of membership is attached
  608. *
  609. * This message asks a peer for additional known endpoints that have
  610. * LIKEd a given multicast group. It's sent when the sender wishes
  611. * to send multicast but does not have the desired number of recipient
  612. * peers.
  613. *
  614. * OK response payload:
  615. * <[8] 64-bit network ID>
  616. * <[6] MAC address of multicast group being queried>
  617. * <[4] 32-bit ADI for multicast group being queried>
  618. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  619. * <[4] 32-bit total number of known members in this multicast group>
  620. * <[2] 16-bit number of members enumerated in this packet>
  621. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  622. *
  623. * If no endpoints are known, OK and ERROR are both optional. It's okay
  624. * to return nothing in that case since gathering is "lazy."
  625. *
  626. * ERROR response payload:
  627. * <[8] 64-bit network ID>
  628. * <[6] MAC address of multicast group being queried>
  629. * <[4] 32-bit ADI for multicast group being queried>
  630. *
  631. * ERRORs are optional and are only generated if permission is denied,
  632. * certificate of membership is out of date, etc.
  633. */
  634. VERB_MULTICAST_GATHER = 13,
  635. /* Multicast frame:
  636. * <[8] 64-bit network ID>
  637. * <[1] flags>
  638. * [<[...] network certificate of membership>]
  639. * [<[4] 32-bit implicit gather limit>]
  640. * [<[6] source MAC>]
  641. * <[6] destination MAC (multicast address)>
  642. * <[4] 32-bit multicast ADI (multicast address extension)>
  643. * <[2] 16-bit ethertype>
  644. * <[...] ethernet payload>
  645. *
  646. * Flags:
  647. * 0x01 - Network certificate of membership is attached
  648. * 0x02 - Implicit gather limit field is present
  649. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  650. *
  651. * OK and ERROR responses are optional. OK may be generated if there are
  652. * implicit gather results or if the recipient wants to send its own
  653. * updated certificate of network membership to the sender. ERROR may be
  654. * generated if a certificate is needed or if multicasts to this group
  655. * are no longer wanted (multicast unsubscribe).
  656. *
  657. * OK response payload:
  658. * <[8] 64-bit network ID>
  659. * <[6] MAC address of multicast group>
  660. * <[4] 32-bit ADI for multicast group>
  661. * <[1] flags>
  662. * [<[...] network certficate of membership>]
  663. * [<[...] implicit gather results if flag 0x01 is set>]
  664. *
  665. * OK flags (same bits as request flags):
  666. * 0x01 - OK includes certificate of network membership
  667. * 0x02 - OK includes implicit gather results
  668. *
  669. * ERROR response payload:
  670. * <[8] 64-bit network ID>
  671. * <[6] multicast group MAC>
  672. * <[4] 32-bit multicast group ADI>
  673. */
  674. VERB_MULTICAST_FRAME = 14
  675. };
  676. /**
  677. * Error codes for VERB_ERROR
  678. */
  679. enum ErrorCode
  680. {
  681. /* No error, not actually used in transit */
  682. ERROR_NONE = 0,
  683. /* Invalid request */
  684. ERROR_INVALID_REQUEST = 1,
  685. /* Bad/unsupported protocol version */
  686. ERROR_BAD_PROTOCOL_VERSION = 2,
  687. /* Unknown object queried (e.g. with WHOIS) */
  688. ERROR_OBJ_NOT_FOUND = 3,
  689. /* HELLO pushed an identity whose address is already claimed */
  690. ERROR_IDENTITY_COLLISION = 4,
  691. /* Verb or use case not supported/enabled by this node */
  692. ERROR_UNSUPPORTED_OPERATION = 5,
  693. /* Message to private network rejected -- no unexpired certificate on file */
  694. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  695. /* Tried to join network, but you're not a member */
  696. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  697. /* Multicasts to this group are not wanted */
  698. ERROR_UNWANTED_MULTICAST = 8
  699. };
  700. /**
  701. * @param v Verb
  702. * @return String representation (e.g. HELLO, OK)
  703. */
  704. static const char *verbString(Verb v)
  705. throw();
  706. /**
  707. * @param e Error code
  708. * @return String error name
  709. */
  710. static const char *errorString(ErrorCode e)
  711. throw();
  712. template<unsigned int C2>
  713. Packet(const Buffer<C2> &b) :
  714. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  715. {
  716. }
  717. Packet(const void *data,unsigned int len) :
  718. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(data,len)
  719. {
  720. }
  721. /**
  722. * Construct a new empty packet with a unique random packet ID
  723. *
  724. * Flags and hops will be zero. Other fields and data region are undefined.
  725. * Use the header access methods (setDestination() and friends) to fill out
  726. * the header. Payload should be appended; initial size is header size.
  727. */
  728. Packet() :
  729. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  730. {
  731. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  732. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  733. }
  734. /**
  735. * Make a copy of a packet with a new initialization vector and destination address
  736. *
  737. * This can be used to take one draft prototype packet and quickly make copies to
  738. * encrypt for different destinations.
  739. *
  740. * @param prototype Prototype packet
  741. * @param dest Destination ZeroTier address for new packet
  742. */
  743. Packet(const Packet &prototype,const Address &dest) :
  744. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  745. {
  746. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  747. setDestination(dest);
  748. }
  749. /**
  750. * Construct a new empty packet with a unique random packet ID
  751. *
  752. * @param dest Destination ZT address
  753. * @param source Source ZT address
  754. * @param v Verb
  755. */
  756. Packet(const Address &dest,const Address &source,const Verb v) :
  757. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  758. {
  759. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  760. setDestination(dest);
  761. setSource(source);
  762. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  763. setVerb(v);
  764. }
  765. /**
  766. * Reset this packet structure for reuse in place
  767. *
  768. * @param dest Destination ZT address
  769. * @param source Source ZT address
  770. * @param v Verb
  771. */
  772. inline void reset(const Address &dest,const Address &source,const Verb v)
  773. {
  774. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  775. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  776. setDestination(dest);
  777. setSource(source);
  778. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  779. setVerb(v);
  780. }
  781. /**
  782. * Generate a new IV / packet ID in place
  783. *
  784. * This can be used to re-use a packet buffer multiple times to send
  785. * technically different but otherwise identical copies of the same
  786. * packet.
  787. */
  788. inline void newInitializationVector()
  789. {
  790. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  791. }
  792. /**
  793. * Set this packet's destination
  794. *
  795. * @param dest ZeroTier address of destination
  796. */
  797. inline void setDestination(const Address &dest)
  798. {
  799. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  800. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  801. d[i] = dest[i];
  802. }
  803. /**
  804. * Set this packet's source
  805. *
  806. * @param source ZeroTier address of source
  807. */
  808. inline void setSource(const Address &source)
  809. {
  810. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  811. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  812. s[i] = source[i];
  813. }
  814. /**
  815. * Get this packet's destination
  816. *
  817. * @return Destination ZT address
  818. */
  819. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  820. /**
  821. * Get this packet's source
  822. *
  823. * @return Source ZT address
  824. */
  825. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  826. /**
  827. * @return True if packet is of valid length
  828. */
  829. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  830. /**
  831. * @return True if packet is fragmented (expect fragments)
  832. */
  833. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  834. /**
  835. * Set this packet's fragmented flag
  836. *
  837. * @param f Fragmented flag value
  838. */
  839. inline void setFragmented(bool f)
  840. {
  841. if (f)
  842. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  843. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  844. }
  845. /**
  846. * @return True if compressed (result only valid if unencrypted)
  847. */
  848. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  849. /**
  850. * @return ZeroTier forwarding hops (0 to 7)
  851. */
  852. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  853. /**
  854. * Increment this packet's hop count
  855. */
  856. inline void incrementHops()
  857. {
  858. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  859. b = (b & 0xf8) | ((b + 1) & 0x07);
  860. }
  861. /**
  862. * @return Cipher suite selector: 0 - 7 (see #defines)
  863. */
  864. inline unsigned int cipher() const
  865. {
  866. //return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  867. // Use DEPRECATED 0x80 "encrypted" flag -- this will go away once there are no more <1.0.0 peers on the net
  868. return (((*this)[ZT_PACKET_IDX_FLAGS] & 0x80) == 0) ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012;
  869. }
  870. /**
  871. * Set this packet's cipher suite
  872. *
  873. * This normally shouldn't be called directly as armor() will set it after
  874. * encrypting and MACing the packet.
  875. */
  876. inline void setCipher(unsigned int c)
  877. {
  878. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  879. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38);
  880. // Set both the new cipher suite spec field and the old DEPRECATED "encrypted" flag as long as there's <1.0.0 peers online
  881. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  882. b |= 0x80;
  883. else b &= 0x7f;
  884. }
  885. /**
  886. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  887. *
  888. * @return Packet ID
  889. */
  890. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  891. /**
  892. * Set packet verb
  893. *
  894. * This also has the side-effect of clearing any verb flags, such as
  895. * compressed, and so must only be done during packet composition.
  896. *
  897. * @param v New packet verb
  898. */
  899. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  900. /**
  901. * @return Packet verb (not including flag bits)
  902. */
  903. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  904. /**
  905. * @return Length of packet payload
  906. */
  907. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  908. /**
  909. * @return Raw packet payload
  910. */
  911. inline const unsigned char *payload() const { return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD); }
  912. /**
  913. * Armor packet for transport
  914. *
  915. * @param key 32-byte key
  916. * @param encryptPayload If true, encrypt packet payload, else just MAC
  917. */
  918. void armor(const void *key,bool encryptPayload);
  919. /**
  920. * Verify and (if encrypted) decrypt packet
  921. *
  922. * @param key 32-byte key
  923. * @return False if packet is invalid or failed MAC authenticity check
  924. */
  925. bool dearmor(const void *key);
  926. /**
  927. * Attempt to compress payload if not already (must be unencrypted)
  928. *
  929. * This requires that the payload at least contain the verb byte already
  930. * set. The compressed flag in the verb is set if compression successfully
  931. * results in a size reduction. If no size reduction occurs, compression
  932. * is not done and the flag is left cleared.
  933. *
  934. * @return True if compression occurred
  935. */
  936. bool compress();
  937. /**
  938. * Attempt to decompress payload if it is compressed (must be unencrypted)
  939. *
  940. * If payload is compressed, it is decompressed and the compressed verb
  941. * flag is cleared. Otherwise nothing is done and true is returned.
  942. *
  943. * @return True if data is now decompressed and valid, false on error
  944. */
  945. bool uncompress();
  946. private:
  947. static const unsigned char ZERO_KEY[32];
  948. /**
  949. * Deterministically mangle a 256-bit crypto key based on packet
  950. *
  951. * This uses extra data from the packet to mangle the secret, giving us an
  952. * effective IV that is somewhat more than 64 bits. This is "free" for
  953. * Salsa20 since it has negligible key setup time so using a different
  954. * key each time is fine.
  955. *
  956. * @param in Input key (32 bytes)
  957. * @param out Output buffer (32 bytes)
  958. */
  959. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  960. {
  961. const unsigned char *d = (const unsigned char *)data();
  962. // IV and source/destination addresses. Using the addresses divides the
  963. // key space into two halves-- A->B and B->A (since order will change).
  964. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  965. out[i] = in[i] ^ d[i];
  966. // Flags, but with hop count masked off. Hop count is altered by forwarding
  967. // nodes. It's one of the only parts of a packet modifiable by people
  968. // without the key.
  969. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  970. // Raw packet size in bytes -- thus each packet size defines a new
  971. // key space.
  972. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  973. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  974. // Rest of raw key is used unchanged
  975. for(unsigned int i=21;i<32;++i)
  976. out[i] = in[i];
  977. }
  978. };
  979. } // namespace ZeroTier
  980. #endif