statefile.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. * Copyright (c) 2014, Yawning Angel <yawning at torproject dot org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. *
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  19. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  25. * POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package obfs4
  28. import (
  29. "encoding/base64"
  30. "encoding/json"
  31. "fmt"
  32. "io/ioutil"
  33. "os"
  34. "path"
  35. "strconv"
  36. "strings"
  37. "git.torproject.org/pluggable-transports/goptlib.git"
  38. "gitlab.com/yawning/obfs4.git/common/csrand"
  39. "gitlab.com/yawning/obfs4.git/common/drbg"
  40. "gitlab.com/yawning/obfs4.git/common/ntor"
  41. )
  42. const (
  43. stateFile = "obfs4_state.json"
  44. bridgeFile = "obfs4_bridgeline.txt"
  45. certSuffix = "=="
  46. certLength = ntor.NodeIDLength + ntor.PublicKeyLength
  47. )
  48. type jsonServerState struct {
  49. NodeID string `json:"node-id"`
  50. PrivateKey string `json:"private-key"`
  51. PublicKey string `json:"public-key"`
  52. DrbgSeed string `json:"drbg-seed"`
  53. IATMode int `json:"iat-mode"`
  54. }
  55. type obfs4ServerCert struct {
  56. raw []byte
  57. }
  58. func (cert *obfs4ServerCert) String() string {
  59. return strings.TrimSuffix(base64.StdEncoding.EncodeToString(cert.raw), certSuffix)
  60. }
  61. func (cert *obfs4ServerCert) unpack() (*ntor.NodeID, *ntor.PublicKey) {
  62. if len(cert.raw) != certLength {
  63. panic(fmt.Sprintf("cert length %d is invalid", len(cert.raw)))
  64. }
  65. nodeID, _ := ntor.NewNodeID(cert.raw[:ntor.NodeIDLength])
  66. pubKey, _ := ntor.NewPublicKey(cert.raw[ntor.NodeIDLength:])
  67. return nodeID, pubKey
  68. }
  69. func serverCertFromString(encoded string) (*obfs4ServerCert, error) {
  70. decoded, err := base64.StdEncoding.DecodeString(encoded + certSuffix)
  71. if err != nil {
  72. return nil, fmt.Errorf("failed to decode cert: %s", err)
  73. }
  74. if len(decoded) != certLength {
  75. return nil, fmt.Errorf("cert length %d is invalid", len(decoded))
  76. }
  77. return &obfs4ServerCert{raw: decoded}, nil
  78. }
  79. func serverCertFromState(st *obfs4ServerState) *obfs4ServerCert {
  80. cert := new(obfs4ServerCert)
  81. cert.raw = append(st.nodeID.Bytes()[:], st.identityKey.Public().Bytes()[:]...)
  82. return cert
  83. }
  84. type obfs4ServerState struct {
  85. nodeID *ntor.NodeID
  86. identityKey *ntor.Keypair
  87. drbgSeed *drbg.Seed
  88. iatMode int
  89. cert *obfs4ServerCert
  90. }
  91. func (st *obfs4ServerState) clientString() string {
  92. return fmt.Sprintf("%s=%s %s=%d", certArg, st.cert, iatArg, st.iatMode)
  93. }
  94. func serverStateFromArgs(stateDir string, args *pt.Args) (*obfs4ServerState, error) {
  95. var js jsonServerState
  96. var nodeIDOk, privKeyOk, seedOk bool
  97. js.NodeID, nodeIDOk = args.Get(nodeIDArg)
  98. js.PrivateKey, privKeyOk = args.Get(privateKeyArg)
  99. js.DrbgSeed, seedOk = args.Get(seedArg)
  100. iatStr, iatOk := args.Get(iatArg)
  101. // Either a private key, node id, and seed are ALL specified, or
  102. // they should be loaded from the state file.
  103. if !privKeyOk && !nodeIDOk && !seedOk {
  104. if err := jsonServerStateFromFile(stateDir, &js); err != nil {
  105. return nil, err
  106. }
  107. } else if !privKeyOk {
  108. return nil, fmt.Errorf("missing argument '%s'", privateKeyArg)
  109. } else if !nodeIDOk {
  110. return nil, fmt.Errorf("missing argument '%s'", nodeIDArg)
  111. } else if !seedOk {
  112. return nil, fmt.Errorf("missing argument '%s'", seedArg)
  113. }
  114. // The IAT mode should be independently configurable.
  115. if iatOk {
  116. // If the IAT mode is specified, attempt to parse and apply it
  117. // as an override.
  118. iatMode, err := strconv.Atoi(iatStr)
  119. if err != nil {
  120. return nil, fmt.Errorf("malformed iat-mode '%s'", iatStr)
  121. }
  122. js.IATMode = iatMode
  123. }
  124. return serverStateFromJSONServerState(stateDir, &js)
  125. }
  126. func serverStateFromJSONServerState(stateDir string, js *jsonServerState) (*obfs4ServerState, error) {
  127. var err error
  128. st := new(obfs4ServerState)
  129. if st.nodeID, err = ntor.NodeIDFromHex(js.NodeID); err != nil {
  130. return nil, err
  131. }
  132. if st.identityKey, err = ntor.KeypairFromHex(js.PrivateKey); err != nil {
  133. return nil, err
  134. }
  135. if st.drbgSeed, err = drbg.SeedFromHex(js.DrbgSeed); err != nil {
  136. return nil, err
  137. }
  138. if js.IATMode < iatNone || js.IATMode > iatParanoid {
  139. return nil, fmt.Errorf("invalid iat-mode '%d'", js.IATMode)
  140. }
  141. st.iatMode = js.IATMode
  142. st.cert = serverCertFromState(st)
  143. // Generate a human readable summary of the configured endpoint.
  144. if err = newBridgeFile(stateDir, st); err != nil {
  145. return nil, err
  146. }
  147. // Write back the possibly updated server state.
  148. return st, writeJSONServerState(stateDir, js)
  149. }
  150. func jsonServerStateFromFile(stateDir string, js *jsonServerState) error {
  151. fPath := path.Join(stateDir, stateFile)
  152. f, err := ioutil.ReadFile(fPath)
  153. if err != nil {
  154. if os.IsNotExist(err) {
  155. if err = newJSONServerState(stateDir, js); err == nil {
  156. return nil
  157. }
  158. }
  159. return err
  160. }
  161. if err := json.Unmarshal(f, js); err != nil {
  162. return fmt.Errorf("failed to load statefile '%s': %s", fPath, err)
  163. }
  164. return nil
  165. }
  166. func newJSONServerState(stateDir string, js *jsonServerState) (err error) {
  167. // Generate everything a server needs, using the cryptographic PRNG.
  168. var st obfs4ServerState
  169. rawID := make([]byte, ntor.NodeIDLength)
  170. if err = csrand.Bytes(rawID); err != nil {
  171. return
  172. }
  173. if st.nodeID, err = ntor.NewNodeID(rawID); err != nil {
  174. return
  175. }
  176. if st.identityKey, err = ntor.NewKeypair(false); err != nil {
  177. return
  178. }
  179. if st.drbgSeed, err = drbg.NewSeed(); err != nil {
  180. return
  181. }
  182. st.iatMode = iatNone
  183. // Encode it into JSON format and write the state file.
  184. js.NodeID = st.nodeID.Hex()
  185. js.PrivateKey = st.identityKey.Private().Hex()
  186. js.PublicKey = st.identityKey.Public().Hex()
  187. js.DrbgSeed = st.drbgSeed.Hex()
  188. js.IATMode = st.iatMode
  189. return writeJSONServerState(stateDir, js)
  190. }
  191. func writeJSONServerState(stateDir string, js *jsonServerState) error {
  192. var err error
  193. var encoded []byte
  194. if encoded, err = json.Marshal(js); err != nil {
  195. return err
  196. }
  197. if err = ioutil.WriteFile(path.Join(stateDir, stateFile), encoded, 0600); err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. func newBridgeFile(stateDir string, st *obfs4ServerState) error {
  203. const prefix = "# obfs4 torrc client bridge line\n" +
  204. "#\n" +
  205. "# This file is an automatically generated bridge line based on\n" +
  206. "# the current obfs4proxy configuration. EDITING IT WILL HAVE\n" +
  207. "# NO EFFECT.\n" +
  208. "#\n" +
  209. "# Before distributing this Bridge, edit the placeholder fields\n" +
  210. "# to contain the actual values:\n" +
  211. "# <IP ADDRESS> - The public IP address of your obfs4 bridge.\n" +
  212. "# <PORT> - The TCP/IP port of your obfs4 bridge.\n" +
  213. "# <FINGERPRINT> - The bridge's fingerprint.\n\n"
  214. bridgeLine := fmt.Sprintf("Bridge obfs4 <IP ADDRESS>:<PORT> <FINGERPRINT> %s\n",
  215. st.clientString())
  216. tmp := []byte(prefix + bridgeLine)
  217. if err := ioutil.WriteFile(path.Join(stateDir, bridgeFile), tmp, 0600); err != nil {
  218. return err
  219. }
  220. return nil
  221. }