Packet.hpp 41 KB

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