Packet.hpp 41 KB

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