session.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  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. package inproxy
  20. import (
  21. "bytes"
  22. "context"
  23. "crypto/ed25519"
  24. "crypto/rand"
  25. "crypto/sha256"
  26. "crypto/sha512"
  27. "encoding/base64"
  28. "math"
  29. "sync"
  30. "time"
  31. "filippo.io/edwards25519"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  35. lrucache "github.com/cognusion/go-cache-lru"
  36. "github.com/flynn/noise"
  37. "golang.org/x/crypto/curve25519"
  38. "golang.zx2c4.com/wireguard/replay"
  39. )
  40. const (
  41. sessionsTTL = 24 * time.Hour
  42. sessionsMaxSize = 1000000
  43. sessionObfuscationPaddingMinSize = 0
  44. sessionObfuscationPaddingMaxSize = 256
  45. resetSessionTokenName = "psiphon-inproxy-session-reset-session-token"
  46. resetSessionTokenNonceSize = 32
  47. )
  48. const (
  49. SessionProtocolName = "psiphon-inproxy-session"
  50. SessionProtocolVersion1 = 1
  51. )
  52. // SessionPrologue is a Noise protocol prologue, which binds the session ID to
  53. // the session.
  54. type SessionPrologue struct {
  55. SessionProtocolName string `cbor:"1,keyasint,omitempty"`
  56. SessionProtocolVersion uint32 `cbor:"2,keyasint,omitempty"`
  57. SessionID ID `cbor:"3,keyasint,omitempty"`
  58. }
  59. // SessionPacket is a Noise protocol message, which may be a session handshake
  60. // message, or secured application data, a SessionRoundTrip.
  61. type SessionPacket struct {
  62. SessionID ID `cbor:"1,keyasint,omitempty"`
  63. Nonce uint64 `cbor:"2,keyasint,omitempty"`
  64. Payload []byte `cbor:"3,keyasint,omitempty"`
  65. ResetSessionToken []byte `cbor:"4,keyasint,omitempty"`
  66. }
  67. // SessionRoundTrip is an application data request or response, which is
  68. // secured by the Noise protocol session. Each request is assigned a unique
  69. // RoundTripID, and each corresponding response has the same RoundTripID.
  70. type SessionRoundTrip struct {
  71. RoundTripID ID `cbor:"1,keyasint,omitempty"`
  72. Payload []byte `cbor:"2,keyasint,omitempty"`
  73. }
  74. // SessionPrivateKey is a Noise protocol private key.
  75. type SessionPrivateKey [ed25519.PrivateKeySize]byte
  76. // GenerateSessionPrivateKey creates a new session private key using
  77. // crypto/rand.
  78. //
  79. // GenerateSessionPrivateKey generates an Ed25519 private key, which is used
  80. // directly for digital signatures and, when converted to Curve25519, as the
  81. // Noise protocol ECDH private key.
  82. //
  83. // The Ed25519 representation is the canonical representation since there's a
  84. // 1:1 conversion from Ed25519 to Curve25519, but not the other way.
  85. //
  86. // Digital signing use cases include signing a reset session token. In
  87. // addition, externally, digital signing can be used in a challenge/response
  88. // protocol that demonstrates ownership of a proxy private key corresponding
  89. // to a claimed proxy public key.
  90. func GenerateSessionPrivateKey() (SessionPrivateKey, error) {
  91. var k SessionPrivateKey
  92. _, privateKey, err := ed25519.GenerateKey(rand.Reader)
  93. if err != nil {
  94. return k, errors.Trace(err)
  95. }
  96. if len(privateKey) != len(k) {
  97. return k, errors.TraceNew("unexpected private key length")
  98. }
  99. copy(k[:], privateKey)
  100. return k, nil
  101. }
  102. // SessionPrivateKeyFromString returns a SessionPrivateKey given its base64
  103. // string encoding.
  104. func SessionPrivateKeyFromString(s string) (SessionPrivateKey, error) {
  105. var k SessionPrivateKey
  106. return k, errors.Trace(fromBase64String(s, k[:]))
  107. }
  108. // String emits SessionPrivateKey as base64.
  109. func (k SessionPrivateKey) String() string {
  110. return base64.RawStdEncoding.EncodeToString([]byte(k[:]))
  111. }
  112. // IsZero indicates if the private key is zero-value.
  113. func (k SessionPrivateKey) IsZero() bool {
  114. var zero SessionPrivateKey
  115. return bytes.Equal(k[:], zero[:])
  116. }
  117. // GetPublicKey returns the public key corresponding to the private key.
  118. func (k SessionPrivateKey) GetPublicKey() (SessionPublicKey, error) {
  119. var sessionPublicKey SessionPublicKey
  120. // See ed25519.PrivateKey.Public.
  121. copy(sessionPublicKey[:], k[32:])
  122. return sessionPublicKey, nil
  123. }
  124. // ToCurve25519 converts the Ed25519 SessionPrivateKey to the unique
  125. // corresponding Curve25519 private key for use in the Noise protocol.
  126. func (k SessionPrivateKey) ToCurve25519() []byte {
  127. h := sha512.New()
  128. h.Write(ed25519.PrivateKey(k[:]).Seed())
  129. return h.Sum(nil)[:curve25519.ScalarSize]
  130. }
  131. // SessionPublicKey is a Noise protocol public key.
  132. type SessionPublicKey [ed25519.PublicKeySize]byte
  133. // SessionPublicKeyFromString returns a SessionPublicKey given its base64
  134. // string encoding.
  135. func SessionPublicKeyFromString(s string) (SessionPublicKey, error) {
  136. var k SessionPublicKey
  137. return k, errors.Trace(fromBase64String(s, k[:]))
  138. }
  139. // SessionPublicKeysFromStrings returns a list of SessionPublicKeys given the
  140. // base64 string encodings.
  141. func SessionPublicKeysFromStrings(strs []string) ([]SessionPublicKey, error) {
  142. keys := make([]SessionPublicKey, len(strs))
  143. for i, s := range strs {
  144. err := fromBase64String(s, keys[i][:])
  145. if err != nil {
  146. return nil, errors.Trace(err)
  147. }
  148. }
  149. return keys, nil
  150. }
  151. // String emits SessionPublicKey as base64.
  152. func (k SessionPublicKey) String() string {
  153. return base64.RawStdEncoding.EncodeToString([]byte(k[:]))
  154. }
  155. // ToCurve25519 converts the Ed25519 SessionPublicKey to the unique
  156. // corresponding Curve25519 public key for use in the Noise protocol.
  157. func (k SessionPublicKey) ToCurve25519() (SessionPublicKeyCurve25519, error) {
  158. var c SessionPublicKeyCurve25519
  159. // Copyright 2019 The age Authors. All rights reserved.
  160. // Use of this source code is governed by a BSD-style
  161. // license that can be found in the LICENSE file.
  162. //
  163. // See https://blog.filippo.io/using-ed25519-keys-for-encryption and
  164. // https://pkg.go.dev/filippo.io/edwards25519#Point.BytesMontgomery.
  165. p, err := new(edwards25519.Point).SetBytes(k[:])
  166. if err != nil {
  167. return c, err
  168. }
  169. copy(c[:], p.BytesMontgomery())
  170. return c, nil
  171. }
  172. // SessionPublicKeyCurve25519 is a representation of a Curve25519 public key
  173. // as a fixed-size array that may be used as a map key.
  174. type SessionPublicKeyCurve25519 [curve25519.PointSize]byte
  175. // String emits SessionPublicKeyCurve25519 as base64.
  176. func (k SessionPublicKeyCurve25519) String() string {
  177. return base64.RawStdEncoding.EncodeToString([]byte(k[:]))
  178. }
  179. // InitiatorSessions is a set of secure Noise protocol sessions for an
  180. // initiator. For in-proxy, clients and proxies will initiate sessions with
  181. // one more brokers and brokers will initiate sessions with multiple Psiphon
  182. // servers.
  183. //
  184. // Secure sessions provide encryption, authentication of the responder,
  185. // identity hiding for the initiator, forward secrecy, and anti-replay for
  186. // application data.
  187. //
  188. // Maintaining a set of established sessions minimizes round trips and
  189. // overhead, as established sessions can be shared and reused for many client
  190. // requests to one broker or many broker requests to one server.
  191. //
  192. // Currently, InitiatorSessions doesn't not cap the number of sessions or use
  193. // an LRU cache since the number of peers is bounded in the in-proxy
  194. // architecture; clients will typically use one or no more than a handful of
  195. // brokers and brokers will exchange requests with a subset of Psiphon
  196. // servers bounded by the in-proxy capability.
  197. //
  198. // InitiatorSessions are used via the RoundTrip function or InitiatorRoundTrip
  199. // type. RoundTrip is a synchronous function which performs any necessary
  200. // session establishment handshake along with the request/response exchange.
  201. // InitiatorRoundTrip offers an iterator interface, with stepwise invocations
  202. // for each step of the handshake and round trip.
  203. //
  204. // All round trips attempt to share and reuse any existing, established
  205. // session to a given peer. For a given peer, the waitToShareSession option
  206. // determines whether round trips will block and wait if a session handshake
  207. // is already in progress, or proceed with a concurrent handshake. For
  208. // in-proxy, clients and proxies use waitToShareSession; as broker/server
  209. // round trips are relayed through clients, brokers do not use
  210. // waitToShareSession so as to not rely on any single client.
  211. //
  212. // Round trips can be performed concurrently and requests can arrive out-of-
  213. // order. The higher level transport for sessions is responsible for
  214. // multiplexing round trips and maintaining the association between a request
  215. // and it's corresponding response.
  216. type InitiatorSessions struct {
  217. privateKey SessionPrivateKey
  218. mutex sync.Mutex
  219. sessions map[SessionPublicKey]*session
  220. }
  221. // NewInitiatorSessions creates a new InitiatorSessions with the specified
  222. // initator private key.
  223. func NewInitiatorSessions(
  224. initiatorPrivateKey SessionPrivateKey) *InitiatorSessions {
  225. return &InitiatorSessions{
  226. privateKey: initiatorPrivateKey,
  227. sessions: make(map[SessionPublicKey]*session),
  228. }
  229. }
  230. // RoundTrip sends the request to the specified responder and returns the
  231. // response.
  232. //
  233. // RoundTrip will establish a session when required, or reuse an existing
  234. // session when available.
  235. //
  236. // When waitToShareSession is true, RoundTrip will block until an existing,
  237. // non-established session is available to be shared.
  238. //
  239. // When making initial network round trips to establish a session,
  240. // sessionHandshakeTimeout is applied as the round trip timeout.
  241. //
  242. // When making the application-level request round trip, requestDelay, when >
  243. // 0, is applied before the request network round trip begins; requestDelay
  244. // may be used to spread out many concurrent requests, such as batch proxy
  245. // announcements, to avoid CDN rate limits.
  246. //
  247. // requestTimeout is applied to the application-level request network round
  248. // trip, and excludes any requestDelay; the distinct requestTimeout may be
  249. // used to set a longer timeout for long-polling requests, such as proxy
  250. // announcements.
  251. //
  252. // Any time spent blocking on waitToShareSession is not included in
  253. // requestDelay or requestTimeout.
  254. //
  255. // RoundTrip returns immediately when ctx becomes done.
  256. func (s *InitiatorSessions) RoundTrip(
  257. ctx context.Context,
  258. roundTripper RoundTripper,
  259. responderPublicKey SessionPublicKey,
  260. responderRootObfuscationSecret ObfuscationSecret,
  261. waitToShareSession bool,
  262. sessionHandshakeTimeout time.Duration,
  263. requestDelay time.Duration,
  264. requestTimeout time.Duration,
  265. request []byte) ([]byte, error) {
  266. rt, err := s.NewRoundTrip(
  267. responderPublicKey,
  268. responderRootObfuscationSecret,
  269. waitToShareSession,
  270. request)
  271. if err != nil {
  272. return nil, errors.Trace(err)
  273. }
  274. var in []byte
  275. for {
  276. out, isRequestPacket, err := rt.Next(ctx, in)
  277. if err != nil {
  278. return nil, errors.Trace(err)
  279. }
  280. if out == nil {
  281. response, err := rt.Response()
  282. if err != nil {
  283. return nil, errors.Trace(err)
  284. }
  285. return response, nil
  286. }
  287. // At this point, if sharing a session, any blocking on
  288. // waitToShareSession is complete, and time elapsed in that blocking
  289. // will not collapse delays or reduce timeouts. If not sharing, and
  290. // establishing a new session, Noise session handshake round trips
  291. // are required before the request payload round trip.
  292. //
  293. // Select the delay and timeout. For Noise session handshake round
  294. // trips, use sessionHandshakeTimeout, which should be appropriate
  295. // for a fast turn-around from the broker, and no delay. When sending
  296. // the application-level request packet, use requestDelay and
  297. // requestTimeout, which allows for applying a delay -- to spread out
  298. // requests -- and a potentially longer timeout appropriate for a
  299. // long-polling, slower turn-around from the broker.
  300. //
  301. // Delays and timeouts are passed down into the round tripper
  302. // provider. Having the round tripper perform the delay sleep allows
  303. // all delays to be interruped by any round tripper close, due to an
  304. // overall broker client reset. Passing the timeout seperately, as
  305. // opposed to adding to ctx, explicitly ensures that the timeout is
  306. // applied only right before the network round trip and no sooner.
  307. var delay, timeout time.Duration
  308. if isRequestPacket {
  309. delay = requestDelay
  310. timeout = requestTimeout
  311. } else {
  312. // No delay for session handshake packet round trips.
  313. timeout = sessionHandshakeTimeout
  314. }
  315. in, err = roundTripper.RoundTrip(ctx, delay, timeout, out)
  316. if err != nil {
  317. // There are no explicit retries here. Retrying in the case where
  318. // the initiator attempts to use an expired session is covered by
  319. // the reset session token logic in InitiatorRoundTrip. Higher
  320. // levels implicitly provide additional retries to cover other
  321. // cases; Psiphon client tunnel establishment will retry in-proxy
  322. // dials; the proxy will retry its announce requests if they
  323. // fail.
  324. // If this round trip owns its session and there are any
  325. // waitToShareSession initiators awaiting the session, signal them
  326. // that the session will not become ready.
  327. rt.TransportFailed()
  328. return nil, errors.Trace(err)
  329. }
  330. }
  331. }
  332. // NewRoundTrip creates a new InitiatorRoundTrip which will perform a
  333. // request/response round trip with the specified responder, sending the
  334. // input request. The InitiatorRoundTrip will establish a session when
  335. // required, or reuse an existing session when available.
  336. //
  337. // When waitToShareSession is true, InitiatorRoundTrip.Next will block until
  338. // an existing, non-established session is available to be shared.
  339. //
  340. // Limitation with waitToShareSession: currently, any new session must
  341. // complete an _application-level_ round trip (e.g., ProxyAnnounce/ClientOffer
  342. // request _and_ response) before the session becomes ready to share since
  343. // the first application-level request is sent in the same packet as the last
  344. // handshake message and ready-to-share is only signalled after a subsequent
  345. // packet is received. This means that, for example, a long-polling
  346. // ProxyAnnounce will block any additional ProxyAnnounce requests attempting
  347. // to share the same InitiatorSessions. In practice, an initial
  348. // ProxyAnnounce/ClientOffer request is expected to block only as long as
  349. // there is no match, so the impact of blocking other concurrent requests is
  350. // limited. See comment in InitiatorRoundTrip.Next for a related future
  351. // enhancement.
  352. //
  353. // NewRoundTrip does not block or perform any session operations; the
  354. // operations begin on the first InitiatorRoundTrip.Next call. The content of
  355. // request should not be modified after calling NewRoundTrip.
  356. func (s *InitiatorSessions) NewRoundTrip(
  357. responderPublicKey SessionPublicKey,
  358. responderRootObfuscationSecret ObfuscationSecret,
  359. waitToShareSession bool,
  360. request []byte) (*InitiatorRoundTrip, error) {
  361. s.mutex.Lock()
  362. defer s.mutex.Unlock()
  363. // Generate a new round trip ID for the session round trip. The response
  364. // is expected to echo back the same round trip ID. This check detects
  365. // any potential misrouting of multiplexed round trip exchanges.
  366. roundTripID, err := MakeID()
  367. if err != nil {
  368. return nil, errors.Trace(err)
  369. }
  370. requestPayload, err := marshalRecord(
  371. SessionRoundTrip{RoundTripID: roundTripID, Payload: request},
  372. recordTypeSessionRoundTrip)
  373. if err != nil {
  374. return nil, errors.Trace(err)
  375. }
  376. return &InitiatorRoundTrip{
  377. initiatorSessions: s,
  378. responderPublicKey: responderPublicKey,
  379. responderRootObfuscationSecret: responderRootObfuscationSecret,
  380. waitToShareSession: waitToShareSession,
  381. roundTripID: roundTripID,
  382. requestPayload: requestPayload,
  383. }, nil
  384. }
  385. // getSession looks for an existing session for the peer specified by public
  386. // key. When none is found, newSession is called to create a new session, and
  387. // this is stored, associated with the key. If an existing session is found,
  388. // indicate if it is ready to be shared or not.
  389. func (s *InitiatorSessions) getSession(
  390. publicKey SessionPublicKey,
  391. newSession func() (*session, error)) (
  392. retSession *session, retIsNew bool, retIsReady bool, retErr error) {
  393. s.mutex.Lock()
  394. defer s.mutex.Unlock()
  395. session, ok := s.sessions[publicKey]
  396. if ok {
  397. return session, false, session.isReadyToShare(nil), nil
  398. }
  399. session, err := newSession()
  400. if err != nil {
  401. return nil, false, false, errors.Trace(err)
  402. }
  403. s.sessions[publicKey] = session
  404. return session, true, session.isReadyToShare(nil), nil
  405. }
  406. // setSession sets the session associated with the peer's public key.
  407. func (s *InitiatorSessions) setSession(publicKey SessionPublicKey, session *session) {
  408. s.mutex.Lock()
  409. defer s.mutex.Unlock()
  410. s.sessions[publicKey] = session
  411. }
  412. // removeIfSession removes the session associated with the peer's public key,
  413. // if it's the specified session.
  414. func (s *InitiatorSessions) removeIfSession(publicKey SessionPublicKey, session *session) {
  415. s.mutex.Lock()
  416. defer s.mutex.Unlock()
  417. currentSession, ok := s.sessions[publicKey]
  418. if !ok || session != currentSession {
  419. return
  420. }
  421. delete(s.sessions, publicKey)
  422. }
  423. // InitiatorRoundTrip represents the state of a session round trip, including
  424. // a session handshake if required. The session handshake and round trip is
  425. // advanced by calling InitiatorRoundTrip.Next.
  426. type InitiatorRoundTrip struct {
  427. initiatorSessions *InitiatorSessions
  428. responderPublicKey SessionPublicKey
  429. responderRootObfuscationSecret ObfuscationSecret
  430. waitToShareSession bool
  431. roundTripID ID
  432. requestPayload []byte
  433. mutex sync.Mutex
  434. sharingSession bool
  435. session *session
  436. lastSentPacket bytes.Buffer
  437. response []byte
  438. }
  439. // Next advances a round trip, as well as any session handshake that may be
  440. // first required. Next takes the next packet received from the responder and
  441. // returns the next packet to send to the responder. To begin, pass a nil
  442. // receivedPacket. The round trip is complete when Next returns nil for the
  443. // next packet to send; the response can be fetched from
  444. // InitiatorRoundTrip.Response.
  445. //
  446. // When waitToShareSession is set, Next will block until an existing,
  447. // non-established session is available to be shared.
  448. //
  449. // Multiple concurrent round trips are supported and requests from different
  450. // round trips can arrive at the responder out-of-order. The provided
  451. // transport is responsible for multiplexing round trips and maintaining an
  452. // association between sent and received packets for a given round trip.
  453. //
  454. // Next returns immediately when ctx becomes done.
  455. func (r *InitiatorRoundTrip) Next(
  456. ctx context.Context,
  457. receivedPacket []byte) (retSendPacket []byte, retIsRequestPacket bool, retErr error) {
  458. // Note: don't clear or reset a session in the event of a bad/rejected
  459. // packet as that would allow a malicious relay client to interrupt a
  460. // valid broker/server session with a malformed packet. Just drop the
  461. // packet and return an error.
  462. // beginOrShareSession returns the next packet to send.
  463. beginOrShareSession := func() ([]byte, bool, error) {
  464. // Check for an existing session, or create a new one if there's no
  465. // existing session.
  466. //
  467. // To ensure the concurrent waitToShareSession cases don't start
  468. // multiple handshakes, getSession populates the initiatorSessions
  469. // session map with a new, unestablished session.
  470. newSession := func() (*session, error) {
  471. sendObfuscationSecret, receiveObfuscationSecret, err :=
  472. deriveSessionPacketObfuscationSecrets(r.responderRootObfuscationSecret, false)
  473. if err != nil {
  474. return nil, errors.Trace(err)
  475. }
  476. session, err := newSession(
  477. true, // isInitiator
  478. r.initiatorSessions.privateKey,
  479. sendObfuscationSecret,
  480. receiveObfuscationSecret,
  481. nil, // No obfuscation replay history
  482. &r.responderPublicKey,
  483. r.requestPayload,
  484. nil,
  485. nil)
  486. if err != nil {
  487. return nil, errors.Trace(err)
  488. }
  489. return session, nil
  490. }
  491. session, isNew, isReady, err := r.initiatorSessions.getSession(
  492. r.responderPublicKey, newSession)
  493. if err != nil {
  494. return nil, false, errors.Trace(err)
  495. }
  496. if isNew {
  497. // When isNew is true, this InitiatorRoundTrip owns the session
  498. // and will perform the handshake.
  499. r.session = session
  500. r.sharingSession = false
  501. } else {
  502. if isReady {
  503. // When isReady is true, this shared session is fully
  504. // established and ready for immediate use.
  505. r.session = session
  506. r.sharingSession = true
  507. } else {
  508. // The existing session is not yet ready for use.
  509. if r.waitToShareSession {
  510. // Wait for the owning InitiatorRoundTrip to complete the
  511. // session handshake and then share the session.
  512. // Limitation with waitToShareSession: isReadyToShare
  513. // becomes true only once the session completes
  514. // an _application-level_ round trip
  515. // (e.g., ProxyAnnounce/ClientOffer request _and_
  516. // response) since the first application-level request is
  517. // bundled with the last handshake message and
  518. // ready-to-share is true only after a subsequent packet
  519. // is received, guaranteeing that the handshake is completed.
  520. //
  521. // Future enhancement: for shared sessions, don't bundle
  522. // the request payload with the handshake. This implies
  523. // one extra round trip for the initial requester, but
  524. // allows all sharers to proceed at once.
  525. signal := make(chan struct{})
  526. if !session.isReadyToShare(signal) {
  527. select {
  528. case <-signal:
  529. if !session.isReadyToShare(nil) {
  530. // The session failed to become ready to share due to a transport
  531. // failure during the handshake. Fail this round trip. Don't
  532. // create a new, unshared session since waitToShareSession was
  533. // specified. It's expected that there will be retries by the
  534. // RoundTrip caller.
  535. return nil, false, errors.TraceNew("waitToShareSession failed")
  536. }
  537. // else, use the session
  538. case <-ctx.Done():
  539. return nil, false, errors.Trace(ctx.Err())
  540. }
  541. }
  542. r.session = session
  543. r.sharingSession = true
  544. } else {
  545. // Don't wait: create a new, unshared session.
  546. r.session, err = newSession()
  547. if err != nil {
  548. return nil, false, errors.Trace(err)
  549. }
  550. r.sharingSession = false
  551. }
  552. }
  553. }
  554. if r.sharingSession {
  555. // The shared session was either ready for immediate use, or we
  556. // waited. Send the round trip request payload.
  557. sendPacket, err := r.session.sendPacket(r.requestPayload)
  558. if err != nil {
  559. return nil, false, errors.Trace(err)
  560. }
  561. return sendPacket, true, nil
  562. }
  563. // Begin the handshake for a new session.
  564. _, sendPacket, _, err := r.session.nextHandshakePacket(nil)
  565. if err != nil {
  566. return nil, false, errors.Trace(err)
  567. }
  568. return sendPacket, false, nil
  569. }
  570. // Return immediately if the context is already done.
  571. if ctx != nil {
  572. err := ctx.Err()
  573. if err != nil {
  574. return nil, false, errors.Trace(err)
  575. }
  576. }
  577. r.mutex.Lock()
  578. defer r.mutex.Unlock()
  579. // Store the output send packet, which is used to verify that any
  580. // subsequent ResetSessionToken isn't replayed.
  581. defer func() {
  582. if retSendPacket != nil {
  583. r.lastSentPacket.Reset()
  584. r.lastSentPacket.Write(retSendPacket)
  585. }
  586. }()
  587. if r.session == nil {
  588. // If the session is nil, this is the first call to Next, and no
  589. // packet from the peer is expected.
  590. if receivedPacket != nil {
  591. return nil, false, errors.TraceNew("unexpected received packet")
  592. }
  593. sendPacket, isRequestPacket, err := beginOrShareSession()
  594. if err != nil {
  595. return nil, false, errors.Trace(err)
  596. }
  597. return sendPacket, isRequestPacket, nil
  598. }
  599. // Not the first Next call, so a packet from the peer is expected.
  600. if receivedPacket == nil {
  601. return nil, false, errors.TraceNew("missing received packet")
  602. }
  603. if r.sharingSession || r.session.isEstablished() {
  604. // When sharing an established and ready session, or once an owned
  605. // session is established, the next packet is post-handshake and
  606. // should be the round trip request response.
  607. // Pre-unwrap here to check for a ResetSessionToken packet.
  608. sessionPacket, err := unwrapSessionPacket(
  609. r.session.receiveObfuscationSecret, true, nil, receivedPacket)
  610. if err != nil {
  611. return nil, false, errors.Trace(err)
  612. }
  613. // Reset the session when the packet is a valid ResetSessionToken. The
  614. // responder sends a ResetSessionToken when this initiator attempts
  615. // to use an expired session. A ResetSessionToken is valid when it's
  616. // signed by the responder's public key and is bound to the last
  617. // packet sent from this initiator (which protects against replay).
  618. if sessionPacket.ResetSessionToken != nil &&
  619. isValidResetSessionToken(
  620. r.responderPublicKey,
  621. r.lastSentPacket.Bytes(),
  622. sessionPacket.ResetSessionToken) {
  623. // removeIfSession won't clobber any other, concurrently
  624. // established session for the same responder.
  625. r.initiatorSessions.removeIfSession(r.responderPublicKey, r.session)
  626. r.session = nil
  627. sendPacket, isRequestPacket, err := beginOrShareSession()
  628. if err != nil {
  629. return nil, false, errors.Trace(err)
  630. }
  631. return sendPacket, isRequestPacket, nil
  632. }
  633. responsePayload, err := r.session.receiveUnmarshaledPacket(sessionPacket)
  634. if err != nil {
  635. return nil, false, errors.Trace(err)
  636. }
  637. var sessionRoundTrip SessionRoundTrip
  638. err = unmarshalRecord(recordTypeSessionRoundTrip, responsePayload, &sessionRoundTrip)
  639. if err != nil {
  640. return nil, false, errors.Trace(err)
  641. }
  642. // Check that the response RoundTripID matches the request RoundTripID.
  643. if sessionRoundTrip.RoundTripID != r.roundTripID {
  644. return nil, false, errors.TraceNew("unexpected round trip ID")
  645. }
  646. // Store the response so it can be retrieved later.
  647. r.response = sessionRoundTrip.Payload
  648. return nil, false, nil
  649. }
  650. // Continue the handshake. Since the first payload is sent to the
  651. // responder along with the initiator's last handshake message, there's
  652. // no sendPacket call in the owned session case. The last
  653. // nextHandshakePacket will bundle it. Also, the payload output of
  654. // nextHandshakePacket is ignored, as only a responder will receive a
  655. // payload in a handshake message.
  656. isEstablished, sendPacket, _, err := r.session.nextHandshakePacket(receivedPacket)
  657. if err != nil {
  658. return nil, false, errors.Trace(err)
  659. }
  660. if isEstablished {
  661. // Retain the most recently established session as the cached session
  662. // for reuse. This should be a no-op in the isNew case and only have
  663. // an effect for !inNew and !waitToShareSession. Modifying the
  664. // initiatorSessions map entry should not impact any concurrent
  665. // handshakes, as each InitiatorRoundTrip maintains its own reference
  666. // to its session.
  667. r.initiatorSessions.setSession(r.responderPublicKey, r.session)
  668. }
  669. return sendPacket, isEstablished, nil
  670. }
  671. // TransportFailed marks any owned, not yet ready-to-share session as failed
  672. // and signals any other initiators waiting to share the session.
  673. //
  674. // TransportFailed should be called when using waitToShareSession and when
  675. // there is a transport level failure to relay a session packet.
  676. func (r *InitiatorRoundTrip) TransportFailed() {
  677. r.mutex.Lock()
  678. defer r.mutex.Unlock()
  679. if !r.sharingSession && !r.session.isReadyToShare(nil) {
  680. r.session.transportFailed()
  681. r.initiatorSessions.removeIfSession(r.responderPublicKey, r.session)
  682. }
  683. }
  684. // Response returns the round trip response. Call Response after Next returns
  685. // nil for the next packet to send, indicating that the round trip is
  686. // complete.
  687. func (r *InitiatorRoundTrip) Response() ([]byte, error) {
  688. r.mutex.Lock()
  689. defer r.mutex.Unlock()
  690. if r.response == nil {
  691. return nil, errors.TraceNew("no response")
  692. }
  693. return r.response, nil
  694. }
  695. // ResponderSessions is a set of secure Noise protocol sessions for an
  696. // responder. For in-proxy, brokers respond to clients and proxies and
  697. // servers respond to brokers.
  698. //
  699. // Secure sessions provide encryption, authentication of the responder,
  700. // identity hiding for the initiator, forward secrecy, and anti-replay for
  701. // application data.
  702. //
  703. // ResponderSessions maintains a cache of established sessions to minimizes
  704. // round trips and overhead as initiators are expected to make multiple round
  705. // trips. The cache has a TTL and maximum size with LRU to cap overall memory
  706. // usage. A broker may receive requests from millions of clients and proxies
  707. // and so only more recent sessions will be retained. Servers will receive
  708. // requests from only a handful of brokers, and so the TTL is not applied.
  709. //
  710. // Multiple, concurrent sessions for a single initiator public key are
  711. // supported.
  712. type ResponderSessions struct {
  713. privateKey SessionPrivateKey
  714. sendObfuscationSecret ObfuscationSecret
  715. receiveObfuscationSecret ObfuscationSecret
  716. applyTTL bool
  717. obfuscationReplayHistory *obfuscationReplayHistory
  718. expectedInitiatorPublicKeys *sessionPublicKeyLookup
  719. mutex sync.Mutex
  720. sessions *lrucache.Cache
  721. }
  722. // NewResponderSessions creates a new ResponderSessions which allows any
  723. // initiators to establish a session. A TTL is applied to cached sessions.
  724. func NewResponderSessions(
  725. responderPrivateKey SessionPrivateKey,
  726. responderRootObfuscationSecret ObfuscationSecret) (*ResponderSessions, error) {
  727. sendObfuscationSecret, receiveObfuscationSecret, err :=
  728. deriveSessionPacketObfuscationSecrets(responderRootObfuscationSecret, true)
  729. if err != nil {
  730. return nil, errors.Trace(err)
  731. }
  732. return &ResponderSessions{
  733. privateKey: responderPrivateKey,
  734. sendObfuscationSecret: sendObfuscationSecret,
  735. receiveObfuscationSecret: receiveObfuscationSecret,
  736. applyTTL: true,
  737. obfuscationReplayHistory: newObfuscationReplayHistory(),
  738. sessions: lrucache.NewWithLRU(sessionsTTL, 1*time.Minute, sessionsMaxSize),
  739. }, nil
  740. }
  741. // NewResponderSessionsForKnownInitiators creates a new ResponderSessions
  742. // which allows only allow-listed initiators to establish a session. No TTL
  743. // is applied to cached sessions.
  744. //
  745. // The NewResponderSessionsForKnownInitiators configuration is for Psiphon
  746. // servers responding to brokers. Only a handful of brokers are expected to
  747. // be deployed. A relatively small allow list of expected broker public keys
  748. // is easy to manage, deploy, and update. No TTL is applied to keep the
  749. // sessions established as much as possible and avoid extra client-relayed
  750. // round trips for BrokerServerRequests.
  751. func NewResponderSessionsForKnownInitiators(
  752. responderPrivateKey SessionPrivateKey,
  753. responderRootObfuscationKey ObfuscationSecret,
  754. initiatorPublicKeys []SessionPublicKey) (*ResponderSessions, error) {
  755. s, err := NewResponderSessions(responderPrivateKey, responderRootObfuscationKey)
  756. if err != nil {
  757. return nil, errors.Trace(err)
  758. }
  759. s.expectedInitiatorPublicKeys, err = newSessionPublicKeyLookup(initiatorPublicKeys)
  760. if err != nil {
  761. return nil, errors.Trace(err)
  762. }
  763. return s, nil
  764. }
  765. // SetKnownInitiatorPublicKeys updates the set of initiator public keys which
  766. // are allowed to establish sessions with the responder. Any existing
  767. // sessions with keys not in the new list are deleted. Existing sessions with
  768. // keys which remain in the list are retained.
  769. func (s *ResponderSessions) SetKnownInitiatorPublicKeys(
  770. initiatorPublicKeys []SessionPublicKey) error {
  771. s.mutex.Lock()
  772. defer s.mutex.Unlock()
  773. changed, err := s.expectedInitiatorPublicKeys.set(initiatorPublicKeys)
  774. if err != nil {
  775. return errors.Trace(err)
  776. }
  777. if !changed {
  778. // With an identical public key set there are no sessions to be reset
  779. return nil
  780. }
  781. // Delete sessions for removed keys; retain established sessions for
  782. // still-valid keys.
  783. //
  784. // Limitations:
  785. // - Doesn't interrupt a concurrent request in progress which has already
  786. // called getSession
  787. // - lrucache doesn't have iterator; Items creates a full copy of the
  788. // cache state
  789. for sessionIDStr, entry := range s.sessions.Items() {
  790. // Each session.hasUnexpectedInitiatorPublicKey indirectly references
  791. // s.expectedInitiatorPublicKeys, which was updated above with the
  792. // new set of valid public keys.
  793. if entry.Object.(*session).hasUnexpectedInitiatorPublicKey() {
  794. s.sessions.Delete(sessionIDStr)
  795. }
  796. }
  797. return nil
  798. }
  799. // RequestHandler is an application-level handler that receives the decrypted
  800. // request payload and returns a response payload to be encrypted and sent to
  801. // the initiator. The initiatorID is the authenticated identifier of the
  802. // initiator: client, proxy, or broker.
  803. //
  804. // In cases where a request is a one-way message, with no response, such as a
  805. // BrokerServerReport, RequestHandler should return a nil packet.
  806. type RequestHandler func(initiatorID ID, request []byte) ([]byte, error)
  807. // HandlePacket takes a session packet, as received at the transport level,
  808. // and handles session handshake and request decryption. While a session
  809. // handshakes, HandlePacket returns the next handshake message to be relayed
  810. // back to the initiator over the transport.
  811. //
  812. // Once a session is fully established and a request is decrypted, the inner
  813. // request payload is passed to the RequestHandler for application-level
  814. // processing. The response received from the RequestHandler will be
  815. // encrypted with the session and returned from HandlePacket as the next
  816. // packet to send back over the transport. If there is no response to
  817. // be returned, HandlePacket returns a nil packet.
  818. //
  819. // The session packet contains a session ID that is used to route packets from
  820. // many initiators to the correct session state.
  821. //
  822. // Above the Noise protocol security layer, session packets have an
  823. // obfuscation layer. If a packet doesn't authenticate with the expected
  824. // obfuscation secret, or if a packet is replayed, HandlePacket returns an
  825. // error. The obfuscation anti-replay layer covers replays of Noise handshake
  826. // messages which aren't covered by the Noise nonce anti-replay. When
  827. // HandlePacket returns an error, the caller should invoke anti-probing
  828. // behavior, such as returning a generic 404 error from an HTTP server for
  829. // HTTPS transports.
  830. //
  831. // There is one expected error case with legitimate initiators: when an
  832. // initiator reuses a session that is expired or no longer in the responder
  833. // cache. In this case HandlePacket will return a reset session token in
  834. // outPacket along with an error, and the caller should log the error and
  835. // also send the packet to the initiator.
  836. //
  837. // The HandlePacket caller should implement initiator rate limiting in its
  838. // transport level.
  839. func (s *ResponderSessions) HandlePacket(
  840. inPacket []byte,
  841. requestHandler RequestHandler) (retOutPacket []byte, retErr error) {
  842. // Concurrency: no locks are held for this function, only in specific
  843. // helper functions.
  844. // unwrapSessionPacket deobfuscates the session packet, and unmarshals a
  845. // SessionPacket. The SessionPacket.SessionID is used to route the
  846. // session packet to an existing session or to create a new one. The
  847. // SessionPacket.Payload is a Noise handshake message or an encrypted
  848. // request and that will be handled below.
  849. sessionPacket, err := unwrapSessionPacket(
  850. s.receiveObfuscationSecret, false, s.obfuscationReplayHistory, inPacket)
  851. if err != nil {
  852. return nil, errors.Trace(err)
  853. }
  854. sessionID := sessionPacket.SessionID
  855. // Check for an existing session with this session ID, or create a new one
  856. // if not found. If the session _was_ in the cache but is now expired, a
  857. // new session is created, but subsequent Noise operations will fail.
  858. session, err := s.getSession(sessionID)
  859. if err != nil {
  860. return nil, errors.Trace(err)
  861. }
  862. retainSession := false
  863. defer func() {
  864. if retErr != nil && !retainSession {
  865. // If an error is returned, the session has failed, so don't
  866. // retain it in the cache as it could be more recently used than
  867. // an older but still valid session.
  868. //
  869. // TODO: should we retain the session if it has completed the
  870. // handshake? As with initiator error signals, and depending on
  871. // the transport security level, a SessionPacket with a
  872. // legitimate session ID but corrupt Noise payload could be
  873. // forged, terminating a legitimate session.
  874. s.removeSession(sessionID)
  875. }
  876. }()
  877. var requestPayload []byte
  878. if session.isEstablished() {
  879. // When the session is already established, decrypt the packet to get
  880. // the request.
  881. payload, err := session.receiveUnmarshaledPacket(sessionPacket)
  882. if err != nil {
  883. return nil, errors.Trace(err)
  884. }
  885. requestPayload = payload
  886. } else {
  887. // When the session is not established, the packet is the next
  888. // handshake message. The initiator appends the request payload to
  889. // the end of its last XK handshake message, and in that case payload
  890. // will contain the request.
  891. isEstablished, outPacket, payload, err :=
  892. session.nextUnmarshaledHandshakePacket(sessionPacket)
  893. if err != nil {
  894. if _, ok := err.(potentialExpiredSessionError); !ok {
  895. return nil, errors.Trace(err)
  896. }
  897. // The initiator may be trying to use a previously valid session
  898. // which is now expired or flushed, due to a full cache or a
  899. // server reboot. Craft and send a secure reset session token,
  900. // signed with the responder public key (the Ed25519
  901. // representation), bound to the packet just received from the
  902. // initiator (to defend against replay).
  903. outPacket, wrapErr := wrapSessionPacket(
  904. s.sendObfuscationSecret,
  905. false,
  906. &SessionPacket{
  907. SessionID: sessionPacket.SessionID,
  908. ResetSessionToken: makeResetSessionToken(s.privateKey, inPacket),
  909. })
  910. if wrapErr != nil {
  911. return nil, errors.Trace(wrapErr)
  912. }
  913. return outPacket, errors.Trace(err)
  914. }
  915. if outPacket != nil {
  916. // The handshake is not complete until outPacket is nil; send the
  917. // next handshake packet.
  918. if payload != nil {
  919. // A payload is not expected unless the handshake is complete.
  920. return nil, errors.TraceNew("unexpected handshake payload")
  921. }
  922. // The session TTL is not extended here. Initiators, including
  923. // clients and proxies, are given sessionsTTL to complete the
  924. // entire handshake.
  925. return outPacket, nil
  926. }
  927. if !isEstablished || payload == nil {
  928. // When outPacket is nil, the handshake should be complete --
  929. // isEstablished -- and, by convention, the first request payload
  930. // should be available.
  931. return nil, errors.TraceNew("unexpected established state")
  932. }
  933. requestPayload = payload
  934. }
  935. // Extend the session TTL.
  936. s.touchSession(sessionID, session)
  937. initiatorID, err := session.getPeerID()
  938. if err != nil {
  939. return nil, errors.Trace(err)
  940. }
  941. var sessionRoundTrip SessionRoundTrip
  942. err = unmarshalRecord(recordTypeSessionRoundTrip, requestPayload, &sessionRoundTrip)
  943. if err != nil {
  944. return nil, errors.Trace(err)
  945. }
  946. request := sessionRoundTrip.Payload
  947. response, err := requestHandler(initiatorID, request)
  948. if err != nil {
  949. // Don't delete the session if the application-level request handler
  950. // returns an error, as there is no problem with the Noise session.
  951. // Non-failure application-level errors can include cases like a
  952. // fronting CDN aborting a request due to timeout misalignment.
  953. retainSession = true
  954. return nil, errors.Trace(err)
  955. }
  956. if response == nil {
  957. // There is no response.
  958. return nil, nil
  959. }
  960. // The response is assigned the same RoundTripID as the request.
  961. sessionRoundTrip = SessionRoundTrip{
  962. RoundTripID: sessionRoundTrip.RoundTripID,
  963. Payload: response,
  964. }
  965. responsePayload, err := marshalRecord(
  966. sessionRoundTrip, recordTypeSessionRoundTrip)
  967. if err != nil {
  968. return nil, errors.Trace(err)
  969. }
  970. responsePacket, err := session.sendPacket(responsePayload)
  971. if err != nil {
  972. return nil, errors.Trace(err)
  973. }
  974. return responsePacket, nil
  975. }
  976. // touchSession sets a cached session for the specified session ID; if the
  977. // session is already in the cache, its TTL is extended. The LRU session
  978. // cache entry may be discarded once the cache is full.
  979. func (s *ResponderSessions) touchSession(sessionID ID, session *session) {
  980. s.mutex.Lock()
  981. defer s.mutex.Unlock()
  982. if !session.hasUnexpectedInitiatorPublicKey() {
  983. // In this case, SetKnownInitiatorPublicKeys was called concurrent to
  984. // HandlePacket, after HandlePacket's getSession, and now the known
  985. // initiator public key for this session is no longer valid; don't
  986. // cache or extend the session, as that could revert a session flush
  987. // performed in SetKnownInitiatorPublicKeys.
  988. //
  989. // Limitation: this won't interrupt a handshake in progress, which may
  990. // complete, but then ultimately fail.
  991. return
  992. }
  993. TTL := lrucache.DefaultExpiration
  994. if !s.applyTTL {
  995. TTL = lrucache.NoExpiration
  996. }
  997. s.sessions.Set(string(sessionID[:]), session, TTL)
  998. }
  999. // getSession returns an existing session for the specified session ID, or
  1000. // creates a new session, and places it in the cache, if not found.
  1001. func (s *ResponderSessions) getSession(sessionID ID) (*session, error) {
  1002. s.mutex.Lock()
  1003. defer s.mutex.Unlock()
  1004. strSessionID := string(sessionID[:])
  1005. entry, ok := s.sessions.Get(strSessionID)
  1006. if ok {
  1007. return entry.(*session), nil
  1008. }
  1009. session, err := newSession(
  1010. false, // !isInitiator
  1011. s.privateKey,
  1012. s.sendObfuscationSecret,
  1013. s.receiveObfuscationSecret,
  1014. s.obfuscationReplayHistory,
  1015. nil,
  1016. nil,
  1017. &sessionID,
  1018. s.expectedInitiatorPublicKeys)
  1019. if err != nil {
  1020. return nil, errors.Trace(err)
  1021. }
  1022. s.sessions.Set(
  1023. strSessionID, session, lrucache.DefaultExpiration)
  1024. return session, nil
  1025. }
  1026. // removeSession removes any existing session for the specified session ID.
  1027. func (s *ResponderSessions) removeSession(sessionID ID) {
  1028. s.mutex.Lock()
  1029. defer s.mutex.Unlock()
  1030. s.sessions.Delete(string(sessionID[:]))
  1031. }
  1032. // makeResetSessionToken creates a secure reset session token.
  1033. //
  1034. // This token is used for a responder to signal to an initiator that a session
  1035. // has expired, or is no longer valid and that a new session should be
  1036. // established. Securing this signal is particularly important for the
  1037. // broker/server sessions relayed by untrusted clients, as it prevents a
  1038. // malicious client from injecting invalid reset tokens and
  1039. // interrupting/degrading session performance.
  1040. //
  1041. // A reset token is signed by the responder's Ed25519 public key. The signature covers:
  1042. // - The last packet received from the initiator, mitigating replay attacks
  1043. // - A context name, resetSessionTokenName, and nonce which mitigates against
  1044. // directly signing arbitrary data in the untrusted last packet received
  1045. // from the initiator
  1046. //
  1047. // Reset session tokens are not part of the Noise protocol, but are sent as
  1048. // session packets.
  1049. func makeResetSessionToken(
  1050. privateKey SessionPrivateKey,
  1051. receivedPacket []byte) []byte {
  1052. var token bytes.Buffer
  1053. token.Write(prng.Bytes(resetSessionTokenNonceSize))
  1054. h := sha256.New()
  1055. h.Write([]byte(resetSessionTokenName))
  1056. h.Write(token.Bytes()[:resetSessionTokenNonceSize])
  1057. h.Write(receivedPacket)
  1058. token.Write(ed25519.Sign(privateKey[:], h.Sum(nil)))
  1059. return token.Bytes()
  1060. }
  1061. // isValidResetSessionToken checks if a reset session token is valid, given
  1062. // the specified responder public key and last packet sent to the responder.
  1063. func isValidResetSessionToken(
  1064. publicKey SessionPublicKey,
  1065. lastSentPacket []byte,
  1066. token []byte) bool {
  1067. if len(token) <= resetSessionTokenNonceSize {
  1068. return false
  1069. }
  1070. h := sha256.New()
  1071. h.Write([]byte(resetSessionTokenName))
  1072. h.Write(token[:resetSessionTokenNonceSize])
  1073. h.Write(lastSentPacket)
  1074. return ed25519.Verify(publicKey[:], h.Sum(nil), token[resetSessionTokenNonceSize:])
  1075. }
  1076. // sessionPublicKeyLookup implements set membership lookup for session public
  1077. // keys, and is used to lookup expected public keys for optional responder
  1078. // access control. The sessionPublicKeyLookup is initialized with a list of
  1079. // Ed25519 session public keys, the canonical representation, while the
  1080. // lookup is done with Curve25519 public keys, the representation that is
  1081. // received via the Noise protocol.
  1082. type sessionPublicKeyLookup struct {
  1083. mutex sync.Mutex
  1084. lookupMap map[SessionPublicKeyCurve25519]struct{}
  1085. }
  1086. func newSessionPublicKeyLookup(publicKeys []SessionPublicKey) (*sessionPublicKeyLookup, error) {
  1087. s := &sessionPublicKeyLookup{
  1088. lookupMap: make(map[SessionPublicKeyCurve25519]struct{}),
  1089. }
  1090. _, err := s.set(publicKeys)
  1091. if err != nil {
  1092. return nil, errors.Trace(err)
  1093. }
  1094. return s, nil
  1095. }
  1096. // set modifies the lookup set of session public keys and returns true if the
  1097. // set has changed.
  1098. func (s *sessionPublicKeyLookup) set(publicKeys []SessionPublicKey) (bool, error) {
  1099. s.mutex.Lock()
  1100. defer s.mutex.Unlock()
  1101. // Convert the Ed25519 public key to its Curve25519 representation, which
  1102. // is what's looked up. SessionPublicKeyCurve25519 is a fixed-size array
  1103. // which can be used as a map key.
  1104. var curve25519PublicKeys []SessionPublicKeyCurve25519
  1105. for _, publicKey := range publicKeys {
  1106. k, err := publicKey.ToCurve25519()
  1107. if err != nil {
  1108. return false, errors.Trace(err)
  1109. }
  1110. curve25519PublicKeys = append(curve25519PublicKeys, k)
  1111. }
  1112. // Check if the set of public keys has changed. This check and return
  1113. // value is used by ResponderSessions.SetKnownInitiatorPublicKeys to skip
  1114. // checking for sessions to be revoked in the case of an overall tactics
  1115. // reload in which configured expected public keys did not change.
  1116. if len(curve25519PublicKeys) == len(s.lookupMap) {
  1117. allFound := true
  1118. for _, k := range curve25519PublicKeys {
  1119. if _, ok := s.lookupMap[k]; !ok {
  1120. allFound = false
  1121. break
  1122. }
  1123. }
  1124. if allFound {
  1125. return false, nil
  1126. }
  1127. }
  1128. lookupMap := make(map[SessionPublicKeyCurve25519]struct{})
  1129. for _, k := range curve25519PublicKeys {
  1130. lookupMap[k] = struct{}{}
  1131. }
  1132. s.lookupMap = lookupMap
  1133. return true, nil
  1134. }
  1135. func (s *sessionPublicKeyLookup) lookup(k SessionPublicKeyCurve25519) bool {
  1136. s.mutex.Lock()
  1137. defer s.mutex.Unlock()
  1138. _, ok := s.lookupMap[k]
  1139. return ok
  1140. }
  1141. type sessionState int
  1142. const (
  1143. /*
  1144. XK:
  1145. <- s
  1146. ...
  1147. -> e, es
  1148. <- e, ee
  1149. -> s, se [+ first payload]
  1150. */
  1151. sessionStateInitiator_XK_send_e_es = iota
  1152. sessionStateInitiator_XK_recv_e_ee_send_s_se_payload
  1153. sessionStateInitiator_XK_established
  1154. sessionStateInitiator_failed
  1155. sessionStateResponder_XK_recv_e_es_send_e_ee
  1156. sessionStateResponder_XK_recv_s_se_payload
  1157. sessionStateResponder_XK_established
  1158. )
  1159. // session represents a Noise protocol session, including its initial
  1160. // handshake state.
  1161. //
  1162. // The XK pattern is used:
  1163. // - Initiators may have short-lived static keys (clients), or long-lived
  1164. // static keys (proxies and brokers). The initiator key is securely
  1165. // transmitted to the responder while hiding its value.
  1166. // - The responder static key is always known (K) and exchanged out of
  1167. // band.
  1168. // - Provides forward secrecy.
  1169. // - The round trip request can be appended to the initiators final
  1170. // handshake message, eliminating an extra round trip.
  1171. //
  1172. // For in-proxy, any client or proxy can connect to a broker. Only allowed
  1173. // brokers can connect to a server.
  1174. //
  1175. // To limit access to allowed brokers, expectedInitiatorPublicKeys is an allow
  1176. // list of broker public keys. XK is still used for this case, instead of
  1177. // KK:
  1178. // - With KK, the broker identity would have to be known before the Noise
  1179. // handshake begins
  1180. // - With XK, the broker proves possession of a private key corresponding to
  1181. // a broker public key on the allow list.
  1182. // - While KK will abort sooner than XK when an invalid broker key is used,
  1183. // completing the handshake and decrypting the first payload does not
  1184. // leak any information.
  1185. //
  1186. // The is no "close" operation for sessions. Responders will maintain a cache
  1187. // of established sessions and discard the state for expired sessions or in
  1188. // an LRU fashion. Initiators will reuse sessions until they are rejected by
  1189. // a responder.
  1190. //
  1191. // There is no state for the obfuscation layer; each packet is obfuscated
  1192. // independently since session packets may arrive at a peer out-of-order.
  1193. //
  1194. // There are independent replay defenses at both the obfuscation layer
  1195. // (to mitigate active probing replays) and at the Noise protocol layer
  1196. // (to defend against replay of Noise protocol packets). The obfuscation
  1197. // anti-replay covers all obfuscated packet nonce values, and the Noise
  1198. // anti-replay filter covers post-handshake packet message sequence number
  1199. // nonces. The Noise layer anti-replay filter uses a sliding window of size
  1200. // ~8000, allowing for approximately that degree of out-of-order packets as
  1201. // could happen with concurrent requests in a shared session.
  1202. //
  1203. // Future enhancement: use a single anti-replay mechanism for both use cases?
  1204. type session struct {
  1205. isInitiator bool
  1206. sessionID ID
  1207. sendObfuscationSecret ObfuscationSecret
  1208. receiveObfuscationSecret ObfuscationSecret
  1209. replayHistory *obfuscationReplayHistory
  1210. expectedInitiatorPublicKeys *sessionPublicKeyLookup
  1211. mutex sync.Mutex
  1212. state sessionState
  1213. signalAwaitingReady []chan struct{}
  1214. handshake *noise.HandshakeState
  1215. firstPayload []byte
  1216. peerPublicKey []byte
  1217. send *noise.CipherState
  1218. receive *noise.CipherState
  1219. nonceReplay replay.Filter
  1220. }
  1221. func newSession(
  1222. isInitiator bool,
  1223. privateKey SessionPrivateKey,
  1224. sendObfuscationSecret ObfuscationSecret,
  1225. receiveObfuscationSecret ObfuscationSecret,
  1226. replayHistory *obfuscationReplayHistory,
  1227. // Initiator
  1228. expectedResponderPublicKey *SessionPublicKey,
  1229. firstPayload []byte,
  1230. // Responder
  1231. peerSessionID *ID,
  1232. expectedInitiatorPublicKeys *sessionPublicKeyLookup) (*session, error) {
  1233. if isInitiator {
  1234. if peerSessionID != nil ||
  1235. expectedResponderPublicKey == nil ||
  1236. expectedInitiatorPublicKeys != nil ||
  1237. firstPayload == nil {
  1238. return nil, errors.TraceNew("unexpected initiator parameters")
  1239. }
  1240. } else {
  1241. if peerSessionID == nil ||
  1242. expectedResponderPublicKey != nil ||
  1243. firstPayload != nil {
  1244. return nil, errors.TraceNew("unexpected responder parameters")
  1245. }
  1246. }
  1247. sessionID := peerSessionID
  1248. if sessionID == nil {
  1249. ID, err := MakeID()
  1250. if err != nil {
  1251. return nil, errors.Trace(err)
  1252. }
  1253. sessionID = &ID
  1254. }
  1255. // The prologue binds the session ID and other meta data to the session.
  1256. prologue, err := protocol.CBOREncoding.Marshal(SessionPrologue{
  1257. SessionProtocolName: SessionProtocolName,
  1258. SessionProtocolVersion: SessionProtocolVersion1,
  1259. SessionID: *sessionID,
  1260. })
  1261. if err != nil {
  1262. return nil, errors.Trace(err)
  1263. }
  1264. publicKey, err := privateKey.GetPublicKey()
  1265. if err != nil {
  1266. return nil, errors.Trace(err)
  1267. }
  1268. privateKeyCurve25519 := privateKey.ToCurve25519()
  1269. publicKeyCurve25519, err := publicKey.ToCurve25519()
  1270. if err != nil {
  1271. return nil, errors.Trace(err)
  1272. }
  1273. // SessionProtocolVersion1 implies this ciphersuite
  1274. config := noise.Config{
  1275. CipherSuite: noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashBLAKE2b),
  1276. Pattern: noise.HandshakeXK,
  1277. Initiator: isInitiator,
  1278. Prologue: prologue,
  1279. StaticKeypair: noise.DHKey{
  1280. Public: publicKeyCurve25519[:],
  1281. Private: privateKeyCurve25519},
  1282. }
  1283. if expectedResponderPublicKey != nil {
  1284. k, err := (*expectedResponderPublicKey).ToCurve25519()
  1285. if err != nil {
  1286. return nil, errors.Trace(err)
  1287. }
  1288. config.PeerStatic = k[:]
  1289. }
  1290. handshake, err := noise.NewHandshakeState(config)
  1291. if err != nil {
  1292. return nil, errors.Trace(err)
  1293. }
  1294. var state sessionState
  1295. if isInitiator {
  1296. state = sessionStateInitiator_XK_send_e_es
  1297. } else {
  1298. state = sessionStateResponder_XK_recv_e_es_send_e_ee
  1299. }
  1300. return &session{
  1301. isInitiator: isInitiator,
  1302. sessionID: *sessionID,
  1303. sendObfuscationSecret: sendObfuscationSecret,
  1304. receiveObfuscationSecret: receiveObfuscationSecret,
  1305. replayHistory: replayHistory,
  1306. expectedInitiatorPublicKeys: expectedInitiatorPublicKeys,
  1307. state: state,
  1308. signalAwaitingReady: make([]chan struct{}, 0), // must be non-nil
  1309. handshake: handshake,
  1310. firstPayload: firstPayload,
  1311. }, nil
  1312. }
  1313. // isEstablished indicates that the session handshake is complete.
  1314. //
  1315. // A session may not be ready to share when isEstablished is true.
  1316. func (s *session) isEstablished() bool {
  1317. s.mutex.Lock()
  1318. defer s.mutex.Unlock()
  1319. return s.handshake == nil
  1320. }
  1321. // isReadyToShare indicates that the session handshake is complete _and_ that
  1322. // the peer is known to have received and processed the final handshake
  1323. // message.
  1324. //
  1325. // When isReadyToShare is true, multiple round trips can use a session
  1326. // concurrently. Requests from different round trips can arrive at the peer
  1327. // out-of-order.
  1328. //
  1329. // Session sharing is performed by initiators, and in the XK handshake the
  1330. // last step is the initiator sends a final message to the responder. While
  1331. // the initiator session becomes "established" after that last message is
  1332. // output, we need to delay other round trips from sharing the session and
  1333. // sending session-encrypted packets to the responder before the responder
  1334. // actually receives that final handshake message.
  1335. //
  1336. // isReadyToShare becomes true once the round trip performing the handshake
  1337. // receives its round trip response, which demonstrates that the responder
  1338. // received the final message.
  1339. //
  1340. // When a signal channel is specified, it is registered and signaled once the
  1341. // session becomes ready to share _or_ the session fails to become ready due
  1342. // to a transport failure. When signaled, the caller must call isReadyToShare
  1343. // once again to distinguish between these two outcomes.
  1344. func (s *session) isReadyToShare(signal chan struct{}) bool {
  1345. s.mutex.Lock()
  1346. defer s.mutex.Unlock()
  1347. if !s.isInitiator || s.state == sessionStateInitiator_failed {
  1348. // Signal immediately if transportFailed was already called.
  1349. if signal != nil {
  1350. close(signal)
  1351. }
  1352. return false
  1353. }
  1354. if s.handshake == nil && s.signalAwaitingReady == nil {
  1355. return true
  1356. }
  1357. if signal != nil {
  1358. s.signalAwaitingReady = append(
  1359. s.signalAwaitingReady, signal)
  1360. }
  1361. return false
  1362. }
  1363. // transportFailed marks the session as failed and signals any initiators
  1364. // waiting to share the session.
  1365. //
  1366. // transportFailed is ignored if the session is already ready to share, as any
  1367. // transport failures past that point affect only one application-level round
  1368. // trip and not the session.
  1369. func (s *session) transportFailed() {
  1370. s.mutex.Lock()
  1371. defer s.mutex.Unlock()
  1372. if !s.isInitiator {
  1373. return
  1374. }
  1375. // Already ready to share, so ignore the transport failure.
  1376. if s.handshake == nil && s.signalAwaitingReady == nil {
  1377. return
  1378. }
  1379. if s.state == sessionStateInitiator_failed {
  1380. return
  1381. }
  1382. // In the sessionStateInitiator_failed state, nextHandshakePacket will
  1383. // always fail.
  1384. s.state = sessionStateInitiator_failed
  1385. for _, signal := range s.signalAwaitingReady {
  1386. close(signal)
  1387. }
  1388. s.signalAwaitingReady = nil
  1389. }
  1390. // getPeerID returns the peer's public key, in the form of an ID. A given peer
  1391. // identifier can only be provided by the peer with the corresponding private
  1392. // key.
  1393. func (s *session) getPeerID() (ID, error) {
  1394. s.mutex.Lock()
  1395. defer s.mutex.Unlock()
  1396. if s.handshake != nil {
  1397. return ID{}, errors.TraceNew("not established")
  1398. }
  1399. return ID(s.peerPublicKey), nil
  1400. }
  1401. // hasUnexpectedInitiatorPublicKey indicates whether the session is
  1402. // established (and so has obtained a peer public key),
  1403. // expectedInitiatorPublicKeys is configured, and the session initiator's
  1404. // public key is not in/no longer in expectedInitiatorPublicKeys.
  1405. func (s *session) hasUnexpectedInitiatorPublicKey() bool {
  1406. s.mutex.Lock()
  1407. defer s.mutex.Unlock()
  1408. if s.expectedInitiatorPublicKeys == nil {
  1409. // Not expecting specific initiator public keys
  1410. return false
  1411. }
  1412. if s.handshake != nil {
  1413. // Peer public key not known yet
  1414. return false
  1415. }
  1416. var k SessionPublicKeyCurve25519
  1417. copy(k[:], s.peerPublicKey)
  1418. return !s.expectedInitiatorPublicKeys.lookup(k)
  1419. }
  1420. // sendPacket prepares a session packet to be sent to the peer, containing the
  1421. // specified round trip payload. The packet is secured by the established
  1422. // session.
  1423. func (s *session) sendPacket(payload []byte) ([]byte, error) {
  1424. s.mutex.Lock()
  1425. defer s.mutex.Unlock()
  1426. if s.handshake != nil {
  1427. return nil, errors.TraceNew("not established")
  1428. }
  1429. if s.send == nil {
  1430. return nil, errors.Trace(s.unexpectedStateError())
  1431. }
  1432. nonce := s.send.Nonce()
  1433. // Unlike tunnels, for example, sessions are not for bulk data transfer
  1434. // and we don't aim for zero allocation or extensive buffer reuse.
  1435. encryptedPayload, err := s.send.Encrypt(nil, nil, payload)
  1436. if err != nil {
  1437. return nil, errors.Trace(err)
  1438. }
  1439. sessionPacket, err := s.wrapPacket(
  1440. &SessionPacket{
  1441. SessionID: s.sessionID,
  1442. Nonce: nonce,
  1443. Payload: encryptedPayload,
  1444. })
  1445. if err != nil {
  1446. return nil, errors.Trace(err)
  1447. }
  1448. return sessionPacket, nil
  1449. }
  1450. // receivePacket opens a session packet received from the peer, using the
  1451. // established session, and returns the round trip payload.
  1452. //
  1453. // As responders need to inspect the packet and use its session ID to route
  1454. // packets to the correct session, responders will call
  1455. // receiveUnmarshaledPacket instead.
  1456. func (s *session) receivePacket(packet []byte) ([]byte, error) {
  1457. sessionPacket, err := s.unwrapPacket(packet)
  1458. if err != nil {
  1459. return nil, errors.Trace(err)
  1460. }
  1461. payload, err := s.receiveUnmarshaledPacket(sessionPacket)
  1462. if err != nil {
  1463. return nil, errors.Trace(err)
  1464. }
  1465. return payload, nil
  1466. }
  1467. func (s *session) receiveUnmarshaledPacket(
  1468. sessionPacket *SessionPacket) ([]byte, error) {
  1469. s.mutex.Lock()
  1470. defer s.mutex.Unlock()
  1471. if s.receive == nil {
  1472. return nil, errors.Trace(s.unexpectedStateError())
  1473. }
  1474. if sessionPacket.SessionID != s.sessionID {
  1475. return nil, errors.Tracef("unexpected sessionID")
  1476. }
  1477. s.receive.SetNonce(sessionPacket.Nonce)
  1478. payload, err := s.receive.Decrypt(nil, nil, sessionPacket.Payload)
  1479. if err != nil {
  1480. return nil, errors.Trace(err)
  1481. }
  1482. if !s.nonceReplay.ValidateCounter(sessionPacket.Nonce, math.MaxUint64) {
  1483. return nil, errors.TraceNew("replay detected")
  1484. }
  1485. // The session is ready to share once it's received a post-handshake
  1486. // response from the peer.
  1487. s.readyToShare()
  1488. return payload, nil
  1489. }
  1490. // nextHandshakePacket advances the session handshake. nextHandshakePacket
  1491. // takes the next handshake packet received from the peer and returns the
  1492. // next handshake packet to send to the peer. Start by passing nil for
  1493. // inPacket. The handshake is complete when outPacket is nil.
  1494. //
  1495. // XK bundles the first initiator request payload along with a handshake
  1496. // message, and nextHandshakePacket output that payload to the responder when
  1497. // the handshake is complete.
  1498. //
  1499. // Once the handshake is complete, further round trips are exchanged using
  1500. // sendPacket and receivePacket.
  1501. //
  1502. // As responders need to inspect the packet and use its session ID to route
  1503. // packets to the correct session, responders will call
  1504. // nextUnmarshaledHandshakePacket instead.
  1505. func (s *session) nextHandshakePacket(inPacket []byte) (
  1506. isEstablished bool, outPacket []byte, payload []byte, err error) {
  1507. var sessionPacket *SessionPacket
  1508. if inPacket != nil {
  1509. sessionPacket, err = s.unwrapPacket(inPacket)
  1510. if err != nil {
  1511. return false, nil, nil, errors.Trace(err)
  1512. }
  1513. }
  1514. isEstablished, outPacket, payload, err =
  1515. s.nextUnmarshaledHandshakePacket(sessionPacket)
  1516. if err != nil {
  1517. return false, nil, nil, errors.Trace(err)
  1518. }
  1519. return isEstablished, outPacket, payload, nil
  1520. }
  1521. // potentialExpiredSessionError is packet error that indicates a potential
  1522. // expired session condition which should be handled with a reset session
  1523. // token. This includes the responder expecting a handshake packet for a new
  1524. // session, but receiving a non-handshake packet.
  1525. // Non-potentialExpiredSessionError errors include
  1526. // "unexpected initiator public key".
  1527. type potentialExpiredSessionError struct {
  1528. error
  1529. }
  1530. func (s *session) nextUnmarshaledHandshakePacket(sessionPacket *SessionPacket) (
  1531. isEstablished bool, outPacket []byte, payload []byte, err error) {
  1532. s.mutex.Lock()
  1533. defer s.mutex.Unlock()
  1534. var in []byte
  1535. if sessionPacket != nil {
  1536. if sessionPacket.SessionID != s.sessionID {
  1537. return false, nil, nil, errors.Tracef("unexpected sessionID")
  1538. }
  1539. if sessionPacket.Nonce != 0 {
  1540. // A handshake message was expected, but this packet contains a
  1541. // post-handshake nonce, Flag this as a potential expired session
  1542. // case. See comment below for limitation.
  1543. return false, nil, nil,
  1544. potentialExpiredSessionError{errors.TraceNew("unexpected nonce")}
  1545. }
  1546. in = sessionPacket.Payload
  1547. }
  1548. // Handle handshake state transitions.
  1549. switch s.state {
  1550. // Initiator
  1551. case sessionStateInitiator_XK_send_e_es:
  1552. out, _, _, err := s.handshake.WriteMessage(nil, nil)
  1553. if err != nil {
  1554. return false, nil, nil, errors.Trace(err)
  1555. }
  1556. outPacket, err := s.wrapPacket(
  1557. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1558. if err != nil {
  1559. return false, nil, nil, errors.Trace(err)
  1560. }
  1561. s.state = sessionStateInitiator_XK_recv_e_ee_send_s_se_payload
  1562. return false, outPacket, nil, nil
  1563. case sessionStateInitiator_XK_recv_e_ee_send_s_se_payload:
  1564. _, _, _, err := s.handshake.ReadMessage(nil, in)
  1565. if err != nil {
  1566. return false, nil, nil, errors.Trace(err)
  1567. }
  1568. out, send, receive, err := s.handshake.WriteMessage(nil, s.firstPayload)
  1569. if err != nil {
  1570. return false, nil, nil, errors.Trace(err)
  1571. }
  1572. outPacket, err := s.wrapPacket(
  1573. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1574. if err != nil {
  1575. return false, nil, nil, errors.Trace(err)
  1576. }
  1577. s.state = sessionStateInitiator_XK_established
  1578. s.established(send, receive)
  1579. return true, outPacket, nil, nil
  1580. // Responder
  1581. case sessionStateResponder_XK_recv_e_es_send_e_ee:
  1582. _, _, _, err := s.handshake.ReadMessage(nil, in)
  1583. if err != nil {
  1584. // A handshake message was expected, but and invalid message type
  1585. // was received. Flag this as a potential expired session case, a
  1586. // candidate for a reset session token. Limitation: there's no
  1587. // check that the invalid message was, in fact, a valid message
  1588. // for an expired session; this may not be possible given the
  1589. // established-session Noise protocol message is encrypted/random.
  1590. return false, nil, nil, potentialExpiredSessionError{errors.Trace(err)}
  1591. }
  1592. out, _, _, err := s.handshake.WriteMessage(nil, nil)
  1593. if err != nil {
  1594. return false, nil, nil, errors.Trace(err)
  1595. }
  1596. outPacket, err := s.wrapPacket(
  1597. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1598. if err != nil {
  1599. return false, nil, nil, errors.Trace(err)
  1600. }
  1601. s.state = sessionStateResponder_XK_recv_s_se_payload
  1602. return false, outPacket, nil, nil
  1603. case sessionStateResponder_XK_recv_s_se_payload:
  1604. firstPayload, receive, send, err := s.handshake.ReadMessage(nil, in)
  1605. if err != nil {
  1606. return false, nil, nil, errors.Trace(err)
  1607. }
  1608. // Check if the initiator's public key in on the allow list.
  1609. //
  1610. // Limitation: unlike with the KK pattern, the handshake completes and
  1611. // the initial payload is decrypted even when the initiator public
  1612. // key is not on the allow list.
  1613. err = s.checkExpectedInitiatorPublicKeys(s.handshake.PeerStatic())
  1614. if err != nil {
  1615. return false, nil, nil, errors.Trace(err)
  1616. }
  1617. s.state = sessionStateResponder_XK_established
  1618. s.established(send, receive)
  1619. return true, nil, firstPayload, nil
  1620. }
  1621. return false, nil, nil, errors.Trace(s.unexpectedStateError())
  1622. }
  1623. func (s *session) checkExpectedInitiatorPublicKeys(peerPublicKey []byte) error {
  1624. if s.expectedInitiatorPublicKeys == nil {
  1625. return nil
  1626. }
  1627. var k SessionPublicKeyCurve25519
  1628. copy(k[:], peerPublicKey)
  1629. ok := s.expectedInitiatorPublicKeys.lookup(k)
  1630. if !ok {
  1631. return errors.TraceNew("unexpected initiator public key")
  1632. }
  1633. return nil
  1634. }
  1635. // Set the session as established.
  1636. func (s *session) established(
  1637. send *noise.CipherState,
  1638. receive *noise.CipherState) {
  1639. // Assumes s.mutex lock is held.
  1640. s.peerPublicKey = s.handshake.PeerStatic()
  1641. s.handshake = nil
  1642. s.firstPayload = nil
  1643. s.send = send
  1644. s.receive = receive
  1645. }
  1646. // Set the session as ready to share.
  1647. func (s *session) readyToShare() {
  1648. // Assumes s.mutex lock is held.
  1649. if !s.isInitiator {
  1650. return
  1651. }
  1652. if s.signalAwaitingReady == nil {
  1653. return
  1654. }
  1655. for _, signal := range s.signalAwaitingReady {
  1656. close(signal)
  1657. }
  1658. s.signalAwaitingReady = nil
  1659. }
  1660. // Marshal and obfuscate a SessionPacket.
  1661. func (s *session) wrapPacket(sessionPacket *SessionPacket) ([]byte, error) {
  1662. // No lock. References only static session fields.
  1663. obfuscatedPacket, err := wrapSessionPacket(
  1664. s.sendObfuscationSecret,
  1665. s.isInitiator,
  1666. sessionPacket)
  1667. if err != nil {
  1668. return nil, errors.Trace(err)
  1669. }
  1670. return obfuscatedPacket, nil
  1671. }
  1672. // Marshal and obfuscated a SessionPacket. wrapSessionPacket is used by
  1673. // responders to wrap reset session token packets.
  1674. func wrapSessionPacket(
  1675. sendObfuscationSecret ObfuscationSecret,
  1676. isInitiator bool,
  1677. sessionPacket *SessionPacket) ([]byte, error) {
  1678. marshaledPacket, err := marshalRecord(
  1679. sessionPacket, recordTypeSessionPacket)
  1680. if err != nil {
  1681. return nil, errors.Trace(err)
  1682. }
  1683. obfuscatedPacket, err := obfuscateSessionPacket(
  1684. sendObfuscationSecret,
  1685. isInitiator,
  1686. marshaledPacket,
  1687. sessionObfuscationPaddingMinSize,
  1688. sessionObfuscationPaddingMaxSize)
  1689. if err != nil {
  1690. return nil, errors.Trace(err)
  1691. }
  1692. return obfuscatedPacket, nil
  1693. }
  1694. // Deobfuscate and unmarshal a SessionPacket.
  1695. func (s *session) unwrapPacket(obfuscatedPacket []byte) (*SessionPacket, error) {
  1696. // No lock. References only static session fields.
  1697. sessionPacket, err := unwrapSessionPacket(
  1698. s.receiveObfuscationSecret,
  1699. s.isInitiator,
  1700. s.replayHistory,
  1701. obfuscatedPacket)
  1702. if err != nil {
  1703. return nil, errors.Trace(err)
  1704. }
  1705. return sessionPacket, nil
  1706. }
  1707. // Deobfuscate and unmarshal SessionPacket. unwrapSessionPacket is used by
  1708. // responders, which must peak at the SessionPacket and get the session ID to
  1709. // route packets to the correct session.
  1710. func unwrapSessionPacket(
  1711. receiveObfuscationSecret ObfuscationSecret,
  1712. isInitiator bool,
  1713. replayHistory *obfuscationReplayHistory,
  1714. obfuscatedPacket []byte) (*SessionPacket, error) {
  1715. packet, err := deobfuscateSessionPacket(
  1716. receiveObfuscationSecret,
  1717. isInitiator,
  1718. replayHistory,
  1719. obfuscatedPacket)
  1720. if err != nil {
  1721. return nil, errors.Trace(err)
  1722. }
  1723. var sessionPacket *SessionPacket
  1724. err = unmarshalRecord(recordTypeSessionPacket, packet, &sessionPacket)
  1725. if err != nil {
  1726. return nil, errors.Trace(err)
  1727. }
  1728. return sessionPacket, nil
  1729. }
  1730. // Create an error that includes the current handshake state.
  1731. func (s *session) unexpectedStateError() error {
  1732. s.mutex.Lock()
  1733. defer s.mutex.Unlock()
  1734. return errors.Tracef("unexpected state: %v", s.state)
  1735. }