utils.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. "regexp"
  29. "runtime"
  30. "runtime/debug"
  31. "strings"
  32. "syscall"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  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. `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|` +
  117. // IPv6
  118. //
  119. // Optional brackets for IPv6 with port
  120. `\[?` +
  121. `(` +
  122. // Uncompressed IPv6; ensure there are 8 segments to avoid matching, e.g., a
  123. // timestamp
  124. `(([a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4})|` +
  125. // Compressed IPv6
  126. `([a-fA-F0-9:]*::[a-fA-F0-9:]+)|([a-fA-F0-9:]+::[a-fA-F0-9:]*)` +
  127. `)` +
  128. // Optional mapped/translated/embeded IPv4 suffix
  129. `(.\d{1,3}\.\d{1,3}\.\d{1,3})?` +
  130. `\]?` +
  131. `)` +
  132. // Optional port number
  133. `(:\d+)?`)
  134. // StripIPAddresses returns a copy of the input with all IP addresses (and
  135. // optional ports) replaced by "[redacted]". This is intended to be used to
  136. // strip addresses from "net" package I/O error messages and otherwise avoid
  137. // inadvertently recording direct server IPs via error message logs; and, in
  138. // metrics, to reduce the error space due to superfluous source port data.
  139. //
  140. // StripIPAddresses uses a simple regex match which liberally matches IP
  141. // address-like patterns and will match invalid addresses; for example, it
  142. // will match port numbers greater than 65535. We err on the side of redaction
  143. // and are not as concerned, in this context, with false positive matches. If
  144. // a user configures an upstream proxy address with an invalid IP or port
  145. // value, we prefer to redact it.
  146. func StripIPAddresses(b []byte) []byte {
  147. return stripIPAddressAndPortRegex.ReplaceAll(b, []byte("[redacted]"))
  148. }
  149. // StripIPAddressesString is StripIPAddresses for strings.
  150. func StripIPAddressesString(s string) string {
  151. return stripIPAddressAndPortRegex.ReplaceAllString(s, "[redacted]")
  152. }
  153. // RedactNetError removes network address information from a "net" package
  154. // error message. Addresses may be domains or IP addresses.
  155. //
  156. // Limitations: some non-address error context can be lost; this function
  157. // makes assumptions about how the Go "net" package error messages are
  158. // formatted and will fail to redact network addresses if this assumptions
  159. // become untrue.
  160. func RedactNetError(err error) error {
  161. // Example "net" package error messages:
  162. //
  163. // - lookup <domain>: no such host
  164. // - lookup <domain>: No address associated with hostname
  165. // - dial tcp <address>: connectex: No connection could be made because the target machine actively refused it
  166. // - write tcp <address>-><address>: write: connection refused
  167. if err == nil {
  168. return err
  169. }
  170. errstr := err.Error()
  171. index := strings.Index(errstr, ": ")
  172. if index == -1 {
  173. return err
  174. }
  175. return std_errors.New("[redacted]" + errstr[index:])
  176. }
  177. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  178. // steps, the file is synced (flushed to disk) while writing.
  179. type SyncFileWriter struct {
  180. file *os.File
  181. step int
  182. count int
  183. }
  184. // NewSyncFileWriter creates a SyncFileWriter.
  185. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  186. return &SyncFileWriter{
  187. file: file,
  188. step: 2 << 16,
  189. count: 0}
  190. }
  191. // Write implements io.Writer with periodic file syncing.
  192. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  193. n, err = writer.file.Write(p)
  194. if err != nil {
  195. return
  196. }
  197. writer.count += n
  198. if writer.count >= writer.step {
  199. err = writer.file.Sync()
  200. writer.count = 0
  201. }
  202. return
  203. }
  204. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  205. // used as a stub, when a net.Addr is required but not used.
  206. type emptyAddr struct {
  207. }
  208. func (e *emptyAddr) String() string {
  209. return ""
  210. }
  211. func (e *emptyAddr) Network() string {
  212. return ""
  213. }
  214. // channelConn implements the net.Conn interface. channelConn allows use of
  215. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  216. // are implemented and the remaining functions are stubs and expected to not
  217. // be used.
  218. type channelConn struct {
  219. ssh.Channel
  220. }
  221. func newChannelConn(channel ssh.Channel) *channelConn {
  222. return &channelConn{
  223. Channel: channel,
  224. }
  225. }
  226. func (conn *channelConn) LocalAddr() net.Addr {
  227. return new(emptyAddr)
  228. }
  229. func (conn *channelConn) RemoteAddr() net.Addr {
  230. return new(emptyAddr)
  231. }
  232. func (conn *channelConn) SetDeadline(_ time.Time) error {
  233. return errors.TraceNew("unsupported")
  234. }
  235. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  236. return errors.TraceNew("unsupported")
  237. }
  238. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  239. return errors.TraceNew("unsupported")
  240. }
  241. func emitMemoryMetrics() {
  242. var memStats runtime.MemStats
  243. runtime.ReadMemStats(&memStats)
  244. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  245. stacktrace.GetParentFunctionName(),
  246. runtime.NumGoroutine(),
  247. memStats.HeapObjects,
  248. common.FormatByteCount(memStats.HeapAlloc),
  249. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  250. common.FormatByteCount(memStats.Sys),
  251. memStats.Mallocs,
  252. common.FormatByteCount(memStats.TotalAlloc))
  253. }
  254. func DoGarbageCollection() {
  255. debug.SetGCPercent(5)
  256. debug.FreeOSMemory()
  257. }
  258. // conditionallyEnabledComponents implements the
  259. // protocol.ConditionallyEnabledComponents interface.
  260. type conditionallyEnabledComponents struct {
  261. }
  262. func (c conditionallyEnabledComponents) QUICEnabled() bool {
  263. return quic.Enabled()
  264. }
  265. func (c conditionallyEnabledComponents) MarionetteEnabled() bool {
  266. return marionette.Enabled()
  267. }
  268. func (c conditionallyEnabledComponents) RefractionNetworkingEnabled() bool {
  269. return refraction.Enabled()
  270. }