session.go 68 KB

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