utils.go 12 KB

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