utils.go 12 KB

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