Packet.hpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. /**
  318. * Initialize from a packet
  319. *
  320. * @param p Original assembled packet
  321. * @param fragStart Start of fragment (raw index in packet data)
  322. * @param fragLen Length of fragment in bytes
  323. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  324. * @param fragTotal Total number of fragments (including 0)
  325. * @throws std::out_of_range Packet size would exceed buffer
  326. */
  327. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  328. throw(std::out_of_range)
  329. {
  330. init(p,fragStart,fragLen,fragNo,fragTotal);
  331. }
  332. /**
  333. * Initialize from a packet
  334. *
  335. * @param p Original assembled packet
  336. * @param fragStart Start of fragment (raw index in packet data)
  337. * @param fragLen Length of fragment in bytes
  338. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  339. * @param fragTotal Total number of fragments (including 0)
  340. * @throws std::out_of_range Packet size would exceed buffer
  341. */
  342. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  343. throw(std::out_of_range)
  344. {
  345. if ((fragStart + fragLen) > p.size())
  346. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  347. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  348. // NOTE: this copies both the IV/packet ID and the destination address.
  349. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  350. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  351. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  352. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  353. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  354. }
  355. /**
  356. * Get this fragment's destination
  357. *
  358. * @return Destination ZT address
  359. */
  360. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  361. /**
  362. * @return True if fragment is of a valid length
  363. */
  364. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  365. /**
  366. * @return ID of packet this is a fragment of
  367. */
  368. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  369. /**
  370. * @return Total number of fragments in packet
  371. */
  372. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  373. /**
  374. * @return Fragment number of this fragment
  375. */
  376. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  377. /**
  378. * @return Fragment ZT hop count
  379. */
  380. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  381. /**
  382. * Increment this packet's hop count
  383. */
  384. inline void incrementHops()
  385. {
  386. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  387. }
  388. /**
  389. * @return Length of payload in bytes
  390. */
  391. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  392. /**
  393. * @return Raw packet payload
  394. */
  395. inline const unsigned char *payload() const
  396. {
  397. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  398. }
  399. };
  400. /**
  401. * ZeroTier protocol verbs
  402. */
  403. enum Verb /* Max value: 32 (5 bits) */
  404. {
  405. /* No operation, payload ignored, no reply */
  406. VERB_NOP = 0,
  407. /* Announcement of a node's existence:
  408. * <[1] protocol version>
  409. * <[1] software major version>
  410. * <[1] software minor version>
  411. * <[2] software revision>
  412. * <[8] timestamp (ms since epoch)>
  413. * <[...] binary serialized identity (see Identity)>
  414. * <[1] destination address type>
  415. * [<[...] destination address>]
  416. *
  417. * This is the only message that ever must be sent in the clear, since it
  418. * is used to push an identity to a new peer.
  419. *
  420. * The destination address is the wire address to which this packet is
  421. * being sent, and in OK is *also* the destination address of the OK
  422. * packet. This can be used by the receiver to detect NAT, learn its real
  423. * external address if behind NAT, and detect changes to its external
  424. * address that require re-establishing connectivity.
  425. *
  426. * Destination address types and formats (not all of these are used now):
  427. * 0 - None -- no destination address data present
  428. * 1 - Ethernet address -- format: <[6] Ethernet MAC>
  429. * 4 - 6-byte IPv4 address -- format: <[4] IP>, <[2] port>
  430. * 6 - 18-byte IPv6 address -- format: <[16] IP>, <[2] port>
  431. *
  432. * OK payload:
  433. * <[8] timestamp (echoed from original HELLO)>
  434. * <[1] protocol version (of responder)>
  435. * <[1] software major version (of responder)>
  436. * <[1] software minor version (of responder)>
  437. * <[2] software revision (of responder)>
  438. * <[1] destination address type (for this OK, not copied from HELLO)>
  439. * [<[...] destination address>]
  440. *
  441. * ERROR has no payload.
  442. */
  443. VERB_HELLO = 1,
  444. /* Error response:
  445. * <[1] in-re verb>
  446. * <[8] in-re packet ID>
  447. * <[1] error code>
  448. * <[...] error-dependent payload>
  449. */
  450. VERB_ERROR = 2,
  451. /* Success response:
  452. * <[1] in-re verb>
  453. * <[8] in-re packet ID>
  454. * <[...] request-specific payload>
  455. */
  456. VERB_OK = 3,
  457. /* Query an identity by address:
  458. * <[5] address to look up>
  459. *
  460. * OK response payload:
  461. * <[...] binary serialized identity>
  462. *
  463. * ERROR response payload:
  464. * <[5] address>
  465. */
  466. VERB_WHOIS = 4,
  467. /* Meet another node at a given protocol address:
  468. * <[1] flags (unused, currently 0)>
  469. * <[5] ZeroTier address of peer that might be found at this address>
  470. * <[2] 16-bit protocol address port>
  471. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  472. * <[...] protocol address (network byte order)>
  473. *
  474. * This is sent by a relaying node to initiate NAT traversal between two
  475. * peers that are communicating by way of indirect relay. The relay will
  476. * send this to both peers at the same time on a periodic basis, telling
  477. * each where it might find the other on the network.
  478. *
  479. * Upon receipt a peer sends HELLO to establish a direct link.
  480. *
  481. * Nodes should implement rate control, limiting the rate at which they
  482. * respond to these packets to prevent their use in DDOS attacks. Nodes
  483. * may also ignore these messages if a peer is not known or is not being
  484. * actively communicated with.
  485. *
  486. * No OK or ERROR is generated.
  487. */
  488. VERB_RENDEZVOUS = 5,
  489. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  490. * <[8] 64-bit network ID>
  491. * <[2] 16-bit ethertype>
  492. * <[...] ethernet payload>
  493. *
  494. * MAC addresses are derived from the packet's source and destination
  495. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  496. * Ethernet framing and other optional flags and features when they
  497. * are not necessary.
  498. *
  499. * ERROR may be generated if a membership certificate is needed for a
  500. * closed network. Payload will be network ID.
  501. */
  502. VERB_FRAME = 6,
  503. /* Full Ethernet frame with MAC addressing and optional fields:
  504. * <[8] 64-bit network ID>
  505. * <[1] flags>
  506. * [<[...] certificate of network membership>]
  507. * <[6] destination MAC or all zero for destination node>
  508. * <[6] source MAC or all zero for node of origin>
  509. * <[2] 16-bit ethertype>
  510. * <[...] ethernet payload>
  511. *
  512. * Flags:
  513. * 0x01 - Certificate of network membership is attached
  514. *
  515. * An extended frame carries full MAC addressing, making them a
  516. * superset of VERB_FRAME. They're used for bridging or when we
  517. * want to attach a certificate since FRAME does not support that.
  518. *
  519. * Multicast frames may not be sent as EXT_FRAME.
  520. *
  521. * ERROR may be generated if a membership certificate is needed for a
  522. * closed network. Payload will be network ID.
  523. */
  524. VERB_EXT_FRAME = 7,
  525. /* DEPRECATED */
  526. VERB_P5_MULTICAST_FRAME = 8,
  527. /* Announce interest in multicast group(s):
  528. * <[8] 64-bit network ID>
  529. * <[6] multicast Ethernet address>
  530. * <[4] multicast additional distinguishing information (ADI)>
  531. * [... additional tuples of network/address/adi ...]
  532. *
  533. * LIKEs are sent to peers with whom you have a direct peer to peer
  534. * connection, and always including supernodes.
  535. *
  536. * OK/ERROR are not generated.
  537. */
  538. VERB_MULTICAST_LIKE = 9,
  539. /* Network member certificate replication/push:
  540. * <[...] serialized certificate of membership>
  541. * [ ... additional certificates may follow ...]
  542. *
  543. * Certificate contains network ID, peer it was issued for, etc.
  544. *
  545. * OK/ERROR are not generated.
  546. */
  547. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  548. /* Network configuration request:
  549. * <[8] 64-bit network ID>
  550. * <[2] 16-bit length of request meta-data dictionary>
  551. * <[...] string-serialized request meta-data>
  552. * [<[8] 64-bit revision of netconf we currently have>]
  553. *
  554. * This message requests network configuration from a node capable of
  555. * providing it. If the optional revision is included, a response is
  556. * only generated if there is a newer network configuration available.
  557. *
  558. * OK response payload:
  559. * <[8] 64-bit network ID>
  560. * <[2] 16-bit length of network configuration dictionary>
  561. * <[...] network configuration dictionary>
  562. *
  563. * OK returns a Dictionary (string serialized) containing the network's
  564. * configuration and IP address assignment information for the querying
  565. * node. It also contains a membership certificate that the querying
  566. * node can push to other peers to demonstrate its right to speak on
  567. * a given network.
  568. *
  569. * When a new network configuration is received, another config request
  570. * should be sent with the new netconf's revision. This confirms receipt
  571. * and also causes any subsequent changes to rapidly propagate as this
  572. * cycle will repeat until there are no changes. This is optional but
  573. * recommended behavior.
  574. *
  575. * ERROR response payload:
  576. * <[8] 64-bit network ID>
  577. *
  578. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  579. * and OBJ_NOT_FOUND if the queried network ID was not found.
  580. */
  581. VERB_NETWORK_CONFIG_REQUEST = 11,
  582. /* Network configuration refresh request:
  583. * <[...] array of 64-bit network IDs>
  584. *
  585. * This message can be sent by the network configuration master node
  586. * to request that nodes refresh their network configuration. It can
  587. * thus be used to "push" updates so that network config changes will
  588. * take effect quickly.
  589. *
  590. * It does not generate an OK or ERROR message, and is treated only as
  591. * a hint to refresh now.
  592. */
  593. VERB_NETWORK_CONFIG_REFRESH = 12,
  594. /* Request endpoints for multicast distribution:
  595. * <[8] 64-bit network ID>
  596. * <[1] flags>
  597. * <[6] MAC address of multicast group being queried>
  598. * <[4] 32-bit ADI for multicast group being queried>
  599. * <[4] 32-bit requested max number of multicast peers>
  600. * [<[...] network certificate of membership>]
  601. *
  602. * Flags:
  603. * 0x01 - Network certificate of membership is attached
  604. *
  605. * This message asks a peer for additional known endpoints that have
  606. * LIKEd a given multicast group. It's sent when the sender wishes
  607. * to send multicast but does not have the desired number of recipient
  608. * peers.
  609. *
  610. * OK response payload:
  611. * <[8] 64-bit network ID>
  612. * <[6] MAC address of multicast group being queried>
  613. * <[4] 32-bit ADI for multicast group being queried>
  614. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  615. * <[4] 32-bit total number of known members in this multicast group>
  616. * <[2] 16-bit number of members enumerated in this packet>
  617. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  618. *
  619. * If no endpoints are known, OK and ERROR are both optional. It's okay
  620. * to return nothing in that case since gathering is "lazy."
  621. *
  622. * ERROR response payload:
  623. * <[8] 64-bit network ID>
  624. * <[6] MAC address of multicast group being queried>
  625. * <[4] 32-bit ADI for multicast group being queried>
  626. *
  627. * ERRORs are optional and are only generated if permission is denied,
  628. * certificate of membership is out of date, etc.
  629. */
  630. VERB_MULTICAST_GATHER = 13,
  631. /* Multicast frame:
  632. * <[8] 64-bit network ID>
  633. * <[1] flags>
  634. * [<[...] network certificate of membership>]
  635. * [<[4] 32-bit implicit gather limit>]
  636. * [<[6] source MAC>]
  637. * <[6] destination MAC (multicast address)>
  638. * <[4] 32-bit multicast ADI (multicast address extension)>
  639. * <[2] 16-bit ethertype>
  640. * <[...] ethernet payload>
  641. *
  642. * Flags:
  643. * 0x01 - Network certificate of membership is attached
  644. * 0x02 - Implicit gather limit field is present
  645. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  646. *
  647. * OK and ERROR responses are optional. OK may be generated if there are
  648. * implicit gather results or if the recipient wants to send its own
  649. * updated certificate of network membership to the sender. ERROR may be
  650. * generated if a certificate is needed or if multicasts to this group
  651. * are no longer wanted (multicast unsubscribe).
  652. *
  653. * OK response payload:
  654. * <[8] 64-bit network ID>
  655. * <[6] MAC address of multicast group>
  656. * <[4] 32-bit ADI for multicast group>
  657. * <[1] flags>
  658. * [<[...] network certficate of membership>]
  659. * [<[...] implicit gather results if flag 0x01 is set>]
  660. *
  661. * OK flags (same bits as request flags):
  662. * 0x01 - OK includes certificate of network membership
  663. * 0x02 - OK includes implicit gather results
  664. *
  665. * ERROR response payload:
  666. * <[8] 64-bit network ID>
  667. * <[6] multicast group MAC>
  668. * <[4] 32-bit multicast group ADI>
  669. */
  670. VERB_MULTICAST_FRAME = 14
  671. };
  672. /**
  673. * Error codes for VERB_ERROR
  674. */
  675. enum ErrorCode
  676. {
  677. /* No error, not actually used in transit */
  678. ERROR_NONE = 0,
  679. /* Invalid request */
  680. ERROR_INVALID_REQUEST = 1,
  681. /* Bad/unsupported protocol version */
  682. ERROR_BAD_PROTOCOL_VERSION = 2,
  683. /* Unknown object queried (e.g. with WHOIS) */
  684. ERROR_OBJ_NOT_FOUND = 3,
  685. /* HELLO pushed an identity whose address is already claimed */
  686. ERROR_IDENTITY_COLLISION = 4,
  687. /* Verb or use case not supported/enabled by this node */
  688. ERROR_UNSUPPORTED_OPERATION = 5,
  689. /* Message to private network rejected -- no unexpired certificate on file */
  690. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  691. /* Tried to join network, but you're not a member */
  692. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  693. /* Multicasts to this group are not wanted */
  694. ERROR_UNWANTED_MULTICAST = 8
  695. };
  696. /**
  697. * @param v Verb
  698. * @return String representation (e.g. HELLO, OK)
  699. */
  700. static const char *verbString(Verb v)
  701. throw();
  702. /**
  703. * @param e Error code
  704. * @return String error name
  705. */
  706. static const char *errorString(ErrorCode e)
  707. throw();
  708. template<unsigned int C2>
  709. Packet(const Buffer<C2> &b)
  710. throw(std::out_of_range) :
  711. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  712. {
  713. }
  714. /**
  715. * Construct a new empty packet with a unique random packet ID
  716. *
  717. * Flags and hops will be zero. Other fields and data region are undefined.
  718. * Use the header access methods (setDestination() and friends) to fill out
  719. * the header. Payload should be appended; initial size is header size.
  720. */
  721. Packet() :
  722. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  723. {
  724. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  725. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  726. }
  727. /**
  728. * Make a copy of a packet with a new initialization vector and destination address
  729. *
  730. * This can be used to take one draft prototype packet and quickly make copies to
  731. * encrypt for different destinations.
  732. *
  733. * @param prototype Prototype packet
  734. * @param dest Destination ZeroTier address for new packet
  735. */
  736. Packet(const Packet &prototype,const Address &dest) :
  737. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  738. {
  739. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  740. setDestination(dest);
  741. }
  742. /**
  743. * Construct a new empty packet with a unique random packet ID
  744. *
  745. * @param dest Destination ZT address
  746. * @param source Source ZT address
  747. * @param v Verb
  748. */
  749. Packet(const Address &dest,const Address &source,const Verb v) :
  750. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  751. {
  752. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  753. setDestination(dest);
  754. setSource(source);
  755. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  756. setVerb(v);
  757. }
  758. /**
  759. * Reset this packet structure for reuse in place
  760. *
  761. * @param dest Destination ZT address
  762. * @param source Source ZT address
  763. * @param v Verb
  764. */
  765. inline void reset(const Address &dest,const Address &source,const Verb v)
  766. {
  767. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  768. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  769. setDestination(dest);
  770. setSource(source);
  771. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  772. setVerb(v);
  773. }
  774. /**
  775. * Generate a new IV / packet ID in place
  776. *
  777. * This can be used to re-use a packet buffer multiple times to send
  778. * technically different but otherwise identical copies of the same
  779. * packet.
  780. */
  781. inline void newInitializationVector()
  782. {
  783. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  784. }
  785. /**
  786. * Set this packet's destination
  787. *
  788. * @param dest ZeroTier address of destination
  789. */
  790. inline void setDestination(const Address &dest)
  791. {
  792. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  793. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  794. d[i] = dest[i];
  795. }
  796. /**
  797. * Set this packet's source
  798. *
  799. * @param source ZeroTier address of source
  800. */
  801. inline void setSource(const Address &source)
  802. {
  803. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  804. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  805. s[i] = source[i];
  806. }
  807. /**
  808. * Get this packet's destination
  809. *
  810. * @return Destination ZT address
  811. */
  812. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  813. /**
  814. * Get this packet's source
  815. *
  816. * @return Source ZT address
  817. */
  818. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  819. /**
  820. * @return True if packet is of valid length
  821. */
  822. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  823. /**
  824. * @return True if packet is fragmented (expect fragments)
  825. */
  826. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  827. /**
  828. * Set this packet's fragmented flag
  829. *
  830. * @param f Fragmented flag value
  831. */
  832. inline void setFragmented(bool f)
  833. {
  834. if (f)
  835. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  836. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  837. }
  838. /**
  839. * @return True if compressed (result only valid if unencrypted)
  840. */
  841. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  842. /**
  843. * @return ZeroTier forwarding hops (0 to 7)
  844. */
  845. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  846. /**
  847. * Increment this packet's hop count
  848. */
  849. inline void incrementHops()
  850. {
  851. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  852. b = (b & 0xf8) | ((b + 1) & 0x07);
  853. }
  854. /**
  855. * @return Cipher suite selector: 0 - 7 (see #defines)
  856. */
  857. inline unsigned int cipher() const
  858. {
  859. //return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  860. // Use DEPRECATED 0x80 "encrypted" flag -- this will go away once there are no more <1.0.0 peers on the net
  861. return (((*this)[ZT_PACKET_IDX_FLAGS] & 0x80) == 0) ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012;
  862. }
  863. /**
  864. * Set this packet's cipher suite
  865. *
  866. * This normally shouldn't be called directly as armor() will set it after
  867. * encrypting and MACing the packet.
  868. */
  869. inline void setCipher(unsigned int c)
  870. {
  871. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  872. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38);
  873. // Set both the new cipher suite spec field and the old DEPRECATED "encrypted" flag as long as there's <1.0.0 peers online
  874. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  875. b |= 0x80;
  876. else b &= 0x7f;
  877. }
  878. /**
  879. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  880. *
  881. * @return Packet ID
  882. */
  883. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  884. /**
  885. * Set packet verb
  886. *
  887. * This also has the side-effect of clearing any verb flags, such as
  888. * compressed, and so must only be done during packet composition.
  889. *
  890. * @param v New packet verb
  891. */
  892. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  893. /**
  894. * @return Packet verb (not including flag bits)
  895. */
  896. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  897. /**
  898. * @return Length of packet payload
  899. */
  900. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  901. /**
  902. * @return Raw packet payload
  903. */
  904. inline const unsigned char *payload() const
  905. {
  906. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  907. }
  908. /**
  909. * Armor packet for transport
  910. *
  911. * @param key 32-byte key
  912. * @param encryptPayload If true, encrypt packet payload, else just MAC
  913. */
  914. inline void armor(const void *key,bool encryptPayload)
  915. {
  916. unsigned char mangledKey[32];
  917. unsigned char macKey[32];
  918. unsigned char mac[16];
  919. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  920. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  921. // Set flag now, since it affects key mangle function
  922. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  923. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  924. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  925. // MAC key is always the first 32 bytes of the Salsa20 key stream
  926. // This is the same construction DJB's NaCl library uses
  927. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  928. if (encryptPayload)
  929. s20.encrypt(payload,payload,payloadLen);
  930. Poly1305::compute(mac,payload,payloadLen,macKey);
  931. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  932. }
  933. /**
  934. * Verify and (if encrypted) decrypt packet
  935. *
  936. * @param key 32-byte key
  937. * @return False if packet is invalid or failed MAC authenticity check
  938. */
  939. inline bool dearmor(const void *key)
  940. {
  941. unsigned char mangledKey[32];
  942. unsigned char macKey[32];
  943. unsigned char mac[16];
  944. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  945. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  946. unsigned int cs = cipher();
  947. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  948. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  949. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  950. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  951. Poly1305::compute(mac,payload,payloadLen,macKey);
  952. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  953. return false;
  954. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  955. s20.decrypt(payload,payload,payloadLen);
  956. return true;
  957. } else if (cs == ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM) {
  958. return false; // not implemented yet
  959. } else return false; // unrecognized cipher suite
  960. }
  961. /**
  962. * Attempt to compress payload if not already (must be unencrypted)
  963. *
  964. * This requires that the payload at least contain the verb byte already
  965. * set. The compressed flag in the verb is set if compression successfully
  966. * results in a size reduction. If no size reduction occurs, compression
  967. * is not done and the flag is left cleared.
  968. *
  969. * @return True if compression occurred
  970. */
  971. inline bool compress()
  972. {
  973. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  974. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  975. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  976. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  977. if ((cl > 0)&&(cl < pl)) {
  978. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  979. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  980. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  981. return true;
  982. }
  983. }
  984. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  985. return false;
  986. }
  987. /**
  988. * Attempt to decompress payload if it is compressed (must be unencrypted)
  989. *
  990. * If payload is compressed, it is decompressed and the compressed verb
  991. * flag is cleared. Otherwise nothing is done and true is returned.
  992. *
  993. * @return True if data is now decompressed and valid, false on error
  994. */
  995. inline bool uncompress()
  996. {
  997. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  998. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  999. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1000. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1001. int ucl = LZ4_decompress_safe((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  1002. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1003. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1004. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  1005. } else return false;
  1006. }
  1007. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1008. }
  1009. return true;
  1010. }
  1011. private:
  1012. static const unsigned char ZERO_KEY[32];
  1013. /**
  1014. * Deterministically mangle a 256-bit crypto key based on packet
  1015. *
  1016. * This uses extra data from the packet to mangle the secret, giving us an
  1017. * effective IV that is somewhat more than 64 bits. This is "free" for
  1018. * Salsa20 since it has negligible key setup time so using a different
  1019. * key each time is fine.
  1020. *
  1021. * @param in Input key (32 bytes)
  1022. * @param out Output buffer (32 bytes)
  1023. */
  1024. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1025. {
  1026. const unsigned char *d = (const unsigned char *)data();
  1027. // IV and source/destination addresses. Using the addresses divides the
  1028. // key space into two halves-- A->B and B->A (since order will change).
  1029. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1030. out[i] = in[i] ^ d[i];
  1031. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1032. // nodes. It's one of the only parts of a packet modifiable by people
  1033. // without the key.
  1034. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1035. // Raw packet size in bytes -- thus each packet size defines a new
  1036. // key space.
  1037. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1038. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1039. // Rest of raw key is used unchanged
  1040. for(unsigned int i=21;i<32;++i)
  1041. out[i] = in[i];
  1042. }
  1043. };
  1044. } // namespace ZeroTier
  1045. #endif