utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "crypto/x509"
  22. "encoding/base64"
  23. std_errors "errors"
  24. "fmt"
  25. "net"
  26. "net/url"
  27. "os"
  28. "path/filepath"
  29. "regexp"
  30. "runtime"
  31. "runtime/debug"
  32. "strings"
  33. "syscall"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/refraction"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  42. )
  43. // MakePsiphonUserAgent constructs a User-Agent value to use for web service
  44. // requests made by the tunnel-core client. The User-Agent includes useful stats
  45. // information; it is to be used only for HTTPS requests, where the header
  46. // cannot be seen by an adversary.
  47. func MakePsiphonUserAgent(config *Config) string {
  48. userAgent := "psiphon-tunnel-core"
  49. if config.ClientVersion != "" {
  50. userAgent += fmt.Sprintf("/%s", config.ClientVersion)
  51. }
  52. if config.ClientPlatform != "" {
  53. userAgent += fmt.Sprintf(" (%s)", config.ClientPlatform)
  54. }
  55. return userAgent
  56. }
  57. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  58. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  59. if err != nil {
  60. return nil, errors.Trace(err)
  61. }
  62. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  63. if err != nil {
  64. return nil, errors.Trace(err)
  65. }
  66. return certificate, nil
  67. }
  68. // FilterUrlError transforms an error, when it is a url.Error, removing
  69. // the URL value. This is to avoid logging private user data in cases
  70. // where the URL may be a user input value.
  71. // This function is used with errors returned by net/http and net/url,
  72. // which are (currently) of type url.Error. In particular, the round trip
  73. // function used by our HttpProxy, http.Client.Do, returns errors of type
  74. // url.Error, with the URL being the url sent from the user's tunneled
  75. // applications:
  76. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  77. func FilterUrlError(err error) error {
  78. if urlErr, ok := err.(*url.Error); ok {
  79. err = &url.Error{
  80. Op: urlErr.Op,
  81. URL: "",
  82. Err: urlErr.Err,
  83. }
  84. }
  85. return err
  86. }
  87. // TrimError removes the middle of over-long error message strings
  88. func TrimError(err error) error {
  89. const MAX_LEN = 100
  90. message := fmt.Sprintf("%s", err)
  91. if len(message) > MAX_LEN {
  92. return std_errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  93. }
  94. return err
  95. }
  96. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  97. func IsAddressInUseError(err error) bool {
  98. if err, ok := err.(*net.OpError); ok {
  99. if err, ok := err.Err.(*os.SyscallError); ok {
  100. if err.Err == syscall.EADDRINUSE {
  101. return true
  102. }
  103. // Special case for Windows (WSAEADDRINUSE = 10048)
  104. if errno, ok := err.Err.(syscall.Errno); ok {
  105. if int(errno) == 10048 {
  106. return true
  107. }
  108. }
  109. }
  110. }
  111. return false
  112. }
  113. var stripIPAddressAndPortRegex = regexp.MustCompile(
  114. // IP address
  115. `(` +
  116. // IPv4
  117. //
  118. // An IPv4 address can also be represented as an unsigned integer, or with
  119. // octal or with hex octet values, but we do not check for any of these
  120. // uncommon representations as some may match non-IP values and we don't
  121. // expect the "net" package, etc., to emit them.)
  122. `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|` +
  123. // IPv6
  124. //
  125. // Optional brackets for IPv6 with port
  126. `\[?` +
  127. `(` +
  128. // Uncompressed IPv6; ensure there are 8 segments to avoid matching, e.g., a
  129. // timestamp
  130. `(([a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4})|` +
  131. // Compressed IPv6
  132. `([a-fA-F0-9:]*::[a-fA-F0-9:]+)|([a-fA-F0-9:]+::[a-fA-F0-9:]*)` +
  133. `)` +
  134. // Optional mapped/translated/embeded IPv4 suffix
  135. `(.\d{1,3}\.\d{1,3}\.\d{1,3})?` +
  136. `\]?` +
  137. `)` +
  138. // Optional port number
  139. `(:\d+)?`)
  140. // StripIPAddresses returns a copy of the input with all IP addresses (and
  141. // optional ports) replaced by "[redacted]". This is intended to be used to
  142. // strip addresses from "net" package I/O error messages and otherwise avoid
  143. // inadvertently recording direct server IPs via error message logs; and, in
  144. // metrics, to reduce the error space due to superfluous source port data.
  145. //
  146. // StripIPAddresses uses a simple regex match which liberally matches IP
  147. // address-like patterns and will match invalid addresses; for example, it
  148. // will match port numbers greater than 65535. We err on the side of redaction
  149. // and are not as concerned, in this context, with false positive matches. If
  150. // a user configures an upstream proxy address with an invalid IP or port
  151. // value, we prefer to redact it.
  152. //
  153. // See the stripIPAddressAndPortRegex comment for some uncommon IP address
  154. // representations that are not matched.
  155. func StripIPAddresses(b []byte) []byte {
  156. return stripIPAddressAndPortRegex.ReplaceAll(b, []byte("[redacted]"))
  157. }
  158. // StripIPAddressesString is StripIPAddresses for strings.
  159. func StripIPAddressesString(s string) string {
  160. return stripIPAddressAndPortRegex.ReplaceAllString(s, "[redacted]")
  161. }
  162. var stripFilePathRegex = regexp.MustCompile(
  163. // File path
  164. `(` +
  165. // Leading characters
  166. `[^ ]*` +
  167. // At least one path separator
  168. `/` +
  169. // Path component; take until next space
  170. `[^ ]*` +
  171. `)+`)
  172. // StripFilePaths returns a copy of the input with all file paths
  173. // replaced by "[redacted]". First any occurrences of the provided file paths
  174. // are replaced and then an attempt is made to replace any other file paths by
  175. // searching with a heuristic. The latter is a best effort attempt it is not
  176. // guaranteed that it will catch every file path.
  177. func StripFilePaths(s string, filePaths ...string) string {
  178. for _, filePath := range filePaths {
  179. s = strings.ReplaceAll(s, filePath, "[redacted]")
  180. }
  181. return stripFilePathRegex.ReplaceAllLiteralString(filepath.ToSlash(s), "[redacted]")
  182. }
  183. // StripFilePathsError is StripFilePaths for errors.
  184. func StripFilePathsError(err error, filePaths ...string) error {
  185. return std_errors.New(StripFilePaths(err.Error(), filePaths...))
  186. }
  187. // RedactNetError removes network address information from a "net" package
  188. // error message. Addresses may be domains or IP addresses.
  189. //
  190. // Limitations: some non-address error context can be lost; this function
  191. // makes assumptions about how the Go "net" package error messages are
  192. // formatted and will fail to redact network addresses if this assumptions
  193. // become untrue.
  194. func RedactNetError(err error) error {
  195. // Example "net" package error messages:
  196. //
  197. // - lookup <domain>: no such host
  198. // - lookup <domain>: No address associated with hostname
  199. // - dial tcp <address>: connectex: No connection could be made because the target machine actively refused it
  200. // - write tcp <address>-><address>: write: connection refused
  201. if err == nil {
  202. return err
  203. }
  204. errstr := err.Error()
  205. index := strings.Index(errstr, ": ")
  206. if index == -1 {
  207. return err
  208. }
  209. return std_errors.New("[redacted]" + errstr[index:])
  210. }
  211. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  212. // steps, the file is synced (flushed to disk) while writing.
  213. type SyncFileWriter struct {
  214. file *os.File
  215. step int
  216. count int
  217. }
  218. // NewSyncFileWriter creates a SyncFileWriter.
  219. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  220. return &SyncFileWriter{
  221. file: file,
  222. step: 2 << 16,
  223. count: 0}
  224. }
  225. // Write implements io.Writer with periodic file syncing.
  226. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  227. n, err = writer.file.Write(p)
  228. if err != nil {
  229. return
  230. }
  231. writer.count += n
  232. if writer.count >= writer.step {
  233. err = writer.file.Sync()
  234. writer.count = 0
  235. }
  236. return
  237. }
  238. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  239. // used as a stub, when a net.Addr is required but not used.
  240. type emptyAddr struct {
  241. }
  242. func (e *emptyAddr) String() string {
  243. return ""
  244. }
  245. func (e *emptyAddr) Network() string {
  246. return ""
  247. }
  248. // channelConn implements the net.Conn interface. channelConn allows use of
  249. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  250. // are implemented and the remaining functions are stubs and expected to not
  251. // be used.
  252. type channelConn struct {
  253. ssh.Channel
  254. }
  255. func newChannelConn(channel ssh.Channel) *channelConn {
  256. return &channelConn{
  257. Channel: channel,
  258. }
  259. }
  260. func (conn *channelConn) LocalAddr() net.Addr {
  261. return new(emptyAddr)
  262. }
  263. func (conn *channelConn) RemoteAddr() net.Addr {
  264. return new(emptyAddr)
  265. }
  266. func (conn *channelConn) SetDeadline(_ time.Time) error {
  267. return errors.TraceNew("unsupported")
  268. }
  269. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  270. return errors.TraceNew("unsupported")
  271. }
  272. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  273. return errors.TraceNew("unsupported")
  274. }
  275. func emitMemoryMetrics() {
  276. var memStats runtime.MemStats
  277. runtime.ReadMemStats(&memStats)
  278. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  279. stacktrace.GetParentFunctionName(),
  280. runtime.NumGoroutine(),
  281. memStats.HeapObjects,
  282. common.FormatByteCount(memStats.HeapAlloc),
  283. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  284. common.FormatByteCount(memStats.Sys),
  285. memStats.Mallocs,
  286. common.FormatByteCount(memStats.TotalAlloc))
  287. }
  288. func DoGarbageCollection() {
  289. debug.SetGCPercent(5)
  290. debug.FreeOSMemory()
  291. }
  292. // conditionallyEnabledComponents implements the
  293. // protocol.ConditionallyEnabledComponents interface.
  294. type conditionallyEnabledComponents struct {
  295. }
  296. func (c conditionallyEnabledComponents) QUICEnabled() bool {
  297. return quic.Enabled()
  298. }
  299. func (c conditionallyEnabledComponents) MarionetteEnabled() bool {
  300. return marionette.Enabled()
  301. }
  302. func (c conditionallyEnabledComponents) RefractionNetworkingEnabled() bool {
  303. return refraction.Enabled()
  304. }
  305. // FileMigration represents the action of moving a file, or directory, to a new
  306. // location.
  307. type FileMigration struct {
  308. // Name is the name of the migration for logging because file paths are not
  309. // logged as they may contain sensitive information.
  310. Name string
  311. // OldPath is the current location of the file.
  312. OldPath string
  313. // NewPath is the location that the file should be moved to.
  314. NewPath string
  315. // IsDir should be set to true if the file is a directory.
  316. IsDir bool
  317. }
  318. // DoFileMigration performs the specified file move operation. An error will be
  319. // returned and the operation will not performed if: a file is expected, but a
  320. // directory is found; a directory is expected, but a file is found; or a file,
  321. // or directory, already exists at the target path of the move operation.
  322. // Note: an attempt is made to redact any file paths from the returned error.
  323. func DoFileMigration(migration FileMigration) error {
  324. // Prefix string added to any errors for debug purposes.
  325. errPrefix := ""
  326. if len(migration.Name) > 0 {
  327. errPrefix = fmt.Sprintf("(%s) ", migration.Name)
  328. }
  329. if !common.FileExists(migration.OldPath) {
  330. return errors.TraceNew(errPrefix + "old path does not exist")
  331. }
  332. info, err := os.Stat(migration.OldPath)
  333. if err != nil {
  334. return errors.Tracef(errPrefix+"error getting file info: %s", StripFilePathsError(err, migration.OldPath))
  335. }
  336. if info.IsDir() != migration.IsDir {
  337. if migration.IsDir {
  338. return errors.TraceNew(errPrefix + "expected directory but found file")
  339. }
  340. return errors.TraceNew(errPrefix + "expected but found directory")
  341. }
  342. if common.FileExists(migration.NewPath) {
  343. return errors.TraceNew(errPrefix + "file already exists, will not overwrite")
  344. }
  345. err = os.Rename(migration.OldPath, migration.NewPath)
  346. if err != nil {
  347. return errors.Tracef(errPrefix+"renaming file failed with error %s", StripFilePathsError(err, migration.OldPath, migration.NewPath))
  348. }
  349. return nil
  350. }