session.go 63 KB

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