session.go 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  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. var peerID ID
  1397. if s.handshake != nil {
  1398. return peerID, errors.TraceNew("not established")
  1399. }
  1400. if len(s.peerPublicKey) != len(peerID) {
  1401. return peerID, errors.TraceNew("invalid peer public key")
  1402. }
  1403. copy(peerID[:], s.peerPublicKey)
  1404. return peerID, nil
  1405. }
  1406. // hasUnexpectedInitiatorPublicKey indicates whether the session is
  1407. // established (and so has obtained a peer public key),
  1408. // expectedInitiatorPublicKeys is configured, and the session initiator's
  1409. // public key is not in/no longer in expectedInitiatorPublicKeys.
  1410. func (s *session) hasUnexpectedInitiatorPublicKey() bool {
  1411. s.mutex.Lock()
  1412. defer s.mutex.Unlock()
  1413. if s.expectedInitiatorPublicKeys == nil {
  1414. // Not expecting specific initiator public keys
  1415. return false
  1416. }
  1417. if s.handshake != nil {
  1418. // Peer public key not known yet
  1419. return false
  1420. }
  1421. var k SessionPublicKeyCurve25519
  1422. copy(k[:], s.peerPublicKey)
  1423. return !s.expectedInitiatorPublicKeys.lookup(k)
  1424. }
  1425. // sendPacket prepares a session packet to be sent to the peer, containing the
  1426. // specified round trip payload. The packet is secured by the established
  1427. // session.
  1428. func (s *session) sendPacket(payload []byte) ([]byte, error) {
  1429. s.mutex.Lock()
  1430. defer s.mutex.Unlock()
  1431. if s.handshake != nil {
  1432. return nil, errors.TraceNew("not established")
  1433. }
  1434. if s.send == nil {
  1435. return nil, errors.Trace(s.unexpectedStateError())
  1436. }
  1437. nonce := s.send.Nonce()
  1438. // Unlike tunnels, for example, sessions are not for bulk data transfer
  1439. // and we don't aim for zero allocation or extensive buffer reuse.
  1440. encryptedPayload, err := s.send.Encrypt(nil, nil, payload)
  1441. if err != nil {
  1442. return nil, errors.Trace(err)
  1443. }
  1444. sessionPacket, err := s.wrapPacket(
  1445. &SessionPacket{
  1446. SessionID: s.sessionID,
  1447. Nonce: nonce,
  1448. Payload: encryptedPayload,
  1449. })
  1450. if err != nil {
  1451. return nil, errors.Trace(err)
  1452. }
  1453. return sessionPacket, nil
  1454. }
  1455. // receivePacket opens a session packet received from the peer, using the
  1456. // established session, and returns the round trip payload.
  1457. //
  1458. // As responders need to inspect the packet and use its session ID to route
  1459. // packets to the correct session, responders will call
  1460. // receiveUnmarshaledPacket instead.
  1461. func (s *session) receivePacket(packet []byte) ([]byte, error) {
  1462. sessionPacket, err := s.unwrapPacket(packet)
  1463. if err != nil {
  1464. return nil, errors.Trace(err)
  1465. }
  1466. payload, err := s.receiveUnmarshaledPacket(sessionPacket)
  1467. if err != nil {
  1468. return nil, errors.Trace(err)
  1469. }
  1470. return payload, nil
  1471. }
  1472. func (s *session) receiveUnmarshaledPacket(
  1473. sessionPacket *SessionPacket) ([]byte, error) {
  1474. s.mutex.Lock()
  1475. defer s.mutex.Unlock()
  1476. if s.receive == nil {
  1477. return nil, errors.Trace(s.unexpectedStateError())
  1478. }
  1479. if sessionPacket.SessionID != s.sessionID {
  1480. return nil, errors.Tracef("unexpected sessionID")
  1481. }
  1482. s.receive.SetNonce(sessionPacket.Nonce)
  1483. payload, err := s.receive.Decrypt(nil, nil, sessionPacket.Payload)
  1484. if err != nil {
  1485. return nil, errors.Trace(err)
  1486. }
  1487. if !s.nonceReplay.ValidateCounter(sessionPacket.Nonce, math.MaxUint64) {
  1488. return nil, errors.TraceNew("replay detected")
  1489. }
  1490. // The session is ready to share once it's received a post-handshake
  1491. // response from the peer.
  1492. s.readyToShare()
  1493. return payload, nil
  1494. }
  1495. // nextHandshakePacket advances the session handshake. nextHandshakePacket
  1496. // takes the next handshake packet received from the peer and returns the
  1497. // next handshake packet to send to the peer. Start by passing nil for
  1498. // inPacket. The handshake is complete when outPacket is nil.
  1499. //
  1500. // XK bundles the first initiator request payload along with a handshake
  1501. // message, and nextHandshakePacket output that payload to the responder when
  1502. // the handshake is complete.
  1503. //
  1504. // Once the handshake is complete, further round trips are exchanged using
  1505. // sendPacket and receivePacket.
  1506. //
  1507. // As responders need to inspect the packet and use its session ID to route
  1508. // packets to the correct session, responders will call
  1509. // nextUnmarshaledHandshakePacket instead.
  1510. func (s *session) nextHandshakePacket(inPacket []byte) (
  1511. isEstablished bool, outPacket []byte, payload []byte, err error) {
  1512. var sessionPacket *SessionPacket
  1513. if inPacket != nil {
  1514. sessionPacket, err = s.unwrapPacket(inPacket)
  1515. if err != nil {
  1516. return false, nil, nil, errors.Trace(err)
  1517. }
  1518. }
  1519. isEstablished, outPacket, payload, err =
  1520. s.nextUnmarshaledHandshakePacket(sessionPacket)
  1521. if err != nil {
  1522. return false, nil, nil, errors.Trace(err)
  1523. }
  1524. return isEstablished, outPacket, payload, nil
  1525. }
  1526. // potentialExpiredSessionError is packet error that indicates a potential
  1527. // expired session condition which should be handled with a reset session
  1528. // token. This includes the responder expecting a handshake packet for a new
  1529. // session, but receiving a non-handshake packet.
  1530. // Non-potentialExpiredSessionError errors include
  1531. // "unexpected initiator public key".
  1532. type potentialExpiredSessionError struct {
  1533. error
  1534. }
  1535. func (s *session) nextUnmarshaledHandshakePacket(sessionPacket *SessionPacket) (
  1536. isEstablished bool, outPacket []byte, payload []byte, err error) {
  1537. s.mutex.Lock()
  1538. defer s.mutex.Unlock()
  1539. var in []byte
  1540. if sessionPacket != nil {
  1541. if sessionPacket.SessionID != s.sessionID {
  1542. return false, nil, nil, errors.Tracef("unexpected sessionID")
  1543. }
  1544. if sessionPacket.Nonce != 0 {
  1545. // A handshake message was expected, but this packet contains a
  1546. // post-handshake nonce, Flag this as a potential expired session
  1547. // case. See comment below for limitation.
  1548. return false, nil, nil,
  1549. potentialExpiredSessionError{errors.TraceNew("unexpected nonce")}
  1550. }
  1551. in = sessionPacket.Payload
  1552. }
  1553. // Handle handshake state transitions.
  1554. switch s.state {
  1555. // Initiator
  1556. case sessionStateInitiator_XK_send_e_es:
  1557. out, _, _, err := s.handshake.WriteMessage(nil, nil)
  1558. if err != nil {
  1559. return false, nil, nil, errors.Trace(err)
  1560. }
  1561. outPacket, err := s.wrapPacket(
  1562. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1563. if err != nil {
  1564. return false, nil, nil, errors.Trace(err)
  1565. }
  1566. s.state = sessionStateInitiator_XK_recv_e_ee_send_s_se_payload
  1567. return false, outPacket, nil, nil
  1568. case sessionStateInitiator_XK_recv_e_ee_send_s_se_payload:
  1569. _, _, _, err := s.handshake.ReadMessage(nil, in)
  1570. if err != nil {
  1571. return false, nil, nil, errors.Trace(err)
  1572. }
  1573. out, send, receive, err := s.handshake.WriteMessage(nil, s.firstPayload)
  1574. if err != nil {
  1575. return false, nil, nil, errors.Trace(err)
  1576. }
  1577. outPacket, err := s.wrapPacket(
  1578. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1579. if err != nil {
  1580. return false, nil, nil, errors.Trace(err)
  1581. }
  1582. s.state = sessionStateInitiator_XK_established
  1583. s.established(send, receive)
  1584. return true, outPacket, nil, nil
  1585. // Responder
  1586. case sessionStateResponder_XK_recv_e_es_send_e_ee:
  1587. _, _, _, err := s.handshake.ReadMessage(nil, in)
  1588. if err != nil {
  1589. // A handshake message was expected, but and invalid message type
  1590. // was received. Flag this as a potential expired session case, a
  1591. // candidate for a reset session token. Limitation: there's no
  1592. // check that the invalid message was, in fact, a valid message
  1593. // for an expired session; this may not be possible given the
  1594. // established-session Noise protocol message is encrypted/random.
  1595. return false, nil, nil, potentialExpiredSessionError{errors.Trace(err)}
  1596. }
  1597. out, _, _, err := s.handshake.WriteMessage(nil, nil)
  1598. if err != nil {
  1599. return false, nil, nil, errors.Trace(err)
  1600. }
  1601. outPacket, err := s.wrapPacket(
  1602. &SessionPacket{SessionID: s.sessionID, Payload: out})
  1603. if err != nil {
  1604. return false, nil, nil, errors.Trace(err)
  1605. }
  1606. s.state = sessionStateResponder_XK_recv_s_se_payload
  1607. return false, outPacket, nil, nil
  1608. case sessionStateResponder_XK_recv_s_se_payload:
  1609. firstPayload, receive, send, err := s.handshake.ReadMessage(nil, in)
  1610. if err != nil {
  1611. return false, nil, nil, errors.Trace(err)
  1612. }
  1613. // Check if the initiator's public key in on the allow list.
  1614. //
  1615. // Limitation: unlike with the KK pattern, the handshake completes and
  1616. // the initial payload is decrypted even when the initiator public
  1617. // key is not on the allow list.
  1618. err = s.checkExpectedInitiatorPublicKeys(s.handshake.PeerStatic())
  1619. if err != nil {
  1620. return false, nil, nil, errors.Trace(err)
  1621. }
  1622. s.state = sessionStateResponder_XK_established
  1623. s.established(send, receive)
  1624. return true, nil, firstPayload, nil
  1625. }
  1626. return false, nil, nil, errors.Trace(s.unexpectedStateError())
  1627. }
  1628. func (s *session) checkExpectedInitiatorPublicKeys(peerPublicKey []byte) error {
  1629. if s.expectedInitiatorPublicKeys == nil {
  1630. return nil
  1631. }
  1632. var k SessionPublicKeyCurve25519
  1633. copy(k[:], peerPublicKey)
  1634. ok := s.expectedInitiatorPublicKeys.lookup(k)
  1635. if !ok {
  1636. return errors.TraceNew("unexpected initiator public key")
  1637. }
  1638. return nil
  1639. }
  1640. // Set the session as established.
  1641. func (s *session) established(
  1642. send *noise.CipherState,
  1643. receive *noise.CipherState) {
  1644. // Assumes s.mutex lock is held.
  1645. s.peerPublicKey = s.handshake.PeerStatic()
  1646. s.handshake = nil
  1647. s.firstPayload = nil
  1648. s.send = send
  1649. s.receive = receive
  1650. }
  1651. // Set the session as ready to share.
  1652. func (s *session) readyToShare() {
  1653. // Assumes s.mutex lock is held.
  1654. if !s.isInitiator {
  1655. return
  1656. }
  1657. if s.signalAwaitingReady == nil {
  1658. return
  1659. }
  1660. for _, signal := range s.signalAwaitingReady {
  1661. close(signal)
  1662. }
  1663. s.signalAwaitingReady = nil
  1664. }
  1665. // Marshal and obfuscate a SessionPacket.
  1666. func (s *session) wrapPacket(sessionPacket *SessionPacket) ([]byte, error) {
  1667. // No lock. References only static session fields.
  1668. obfuscatedPacket, err := wrapSessionPacket(
  1669. s.sendObfuscationSecret,
  1670. s.isInitiator,
  1671. sessionPacket)
  1672. if err != nil {
  1673. return nil, errors.Trace(err)
  1674. }
  1675. return obfuscatedPacket, nil
  1676. }
  1677. // Marshal and obfuscated a SessionPacket. wrapSessionPacket is used by
  1678. // responders to wrap reset session token packets.
  1679. func wrapSessionPacket(
  1680. sendObfuscationSecret ObfuscationSecret,
  1681. isInitiator bool,
  1682. sessionPacket *SessionPacket) ([]byte, error) {
  1683. marshaledPacket, err := marshalRecord(
  1684. sessionPacket, recordTypeSessionPacket)
  1685. if err != nil {
  1686. return nil, errors.Trace(err)
  1687. }
  1688. obfuscatedPacket, err := obfuscateSessionPacket(
  1689. sendObfuscationSecret,
  1690. isInitiator,
  1691. marshaledPacket,
  1692. sessionObfuscationPaddingMinSize,
  1693. sessionObfuscationPaddingMaxSize)
  1694. if err != nil {
  1695. return nil, errors.Trace(err)
  1696. }
  1697. return obfuscatedPacket, nil
  1698. }
  1699. // Deobfuscate and unmarshal a SessionPacket.
  1700. func (s *session) unwrapPacket(obfuscatedPacket []byte) (*SessionPacket, error) {
  1701. // No lock. References only static session fields.
  1702. sessionPacket, err := unwrapSessionPacket(
  1703. s.receiveObfuscationSecret,
  1704. s.isInitiator,
  1705. s.replayHistory,
  1706. obfuscatedPacket)
  1707. if err != nil {
  1708. return nil, errors.Trace(err)
  1709. }
  1710. return sessionPacket, nil
  1711. }
  1712. // Deobfuscate and unmarshal SessionPacket. unwrapSessionPacket is used by
  1713. // responders, which must peak at the SessionPacket and get the session ID to
  1714. // route packets to the correct session.
  1715. func unwrapSessionPacket(
  1716. receiveObfuscationSecret ObfuscationSecret,
  1717. isInitiator bool,
  1718. replayHistory *obfuscationReplayHistory,
  1719. obfuscatedPacket []byte) (*SessionPacket, error) {
  1720. packet, err := deobfuscateSessionPacket(
  1721. receiveObfuscationSecret,
  1722. isInitiator,
  1723. replayHistory,
  1724. obfuscatedPacket)
  1725. if err != nil {
  1726. return nil, errors.Trace(err)
  1727. }
  1728. var sessionPacket *SessionPacket
  1729. err = unmarshalRecord(recordTypeSessionPacket, packet, &sessionPacket)
  1730. if err != nil {
  1731. return nil, errors.Trace(err)
  1732. }
  1733. return sessionPacket, nil
  1734. }
  1735. // Create an error that includes the current handshake state.
  1736. func (s *session) unexpectedStateError() error {
  1737. s.mutex.Lock()
  1738. defer s.mutex.Unlock()
  1739. return errors.Tracef("unexpected state: %v", s.state)
  1740. }