Packet.hpp 39 KB

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