utils.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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/stacktrace"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tapdance"
  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 stripIPv4AddressRegex = regexp.MustCompile(
  113. `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}(:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3}))?`)
  114. // StripIPAddresses returns a copy of the input with all IP addresses [and
  115. // optional ports] replaced by "[address]". This is intended to be used to
  116. // strip addresses from "net" package I/O error messages and otherwise avoid
  117. // inadvertently recording direct server IPs via error message logs; and, in
  118. // metrics, to reduce the error space due to superfluous source port data.
  119. //
  120. // Limitation: only strips IPv4 addresses.
  121. func StripIPAddresses(b []byte) []byte {
  122. // TODO: IPv6 support
  123. return stripIPv4AddressRegex.ReplaceAll(b, []byte("[redacted]"))
  124. }
  125. // StripIPAddressesString is StripIPAddresses for strings.
  126. func StripIPAddressesString(s string) string {
  127. // TODO: IPv6 support
  128. return stripIPv4AddressRegex.ReplaceAllString(s, "[redacted]")
  129. }
  130. // RedactNetError removes network address information from a "net" package
  131. // error message. Addresses may be domains or IP addresses.
  132. //
  133. // Limitations: some non-address error context can be lost; this function
  134. // makes assumptions about how the Go "net" package error messages are
  135. // formatted and will fail to redact network addresses if this assumptions
  136. // become untrue.
  137. func RedactNetError(err error) error {
  138. // Example "net" package error messages:
  139. //
  140. // - lookup <domain>: no such host
  141. // - lookup <domain>: No address associated with hostname
  142. // - dial tcp <address>: connectex: No connection could be made because the target machine actively refused it
  143. // - write tcp <address>-><address>: write: connection refused
  144. if err == nil {
  145. return err
  146. }
  147. errstr := err.Error()
  148. index := strings.Index(errstr, ": ")
  149. if index == -1 {
  150. return err
  151. }
  152. return std_errors.New("[redacted]" + errstr[index:])
  153. }
  154. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  155. // steps, the file is synced (flushed to disk) while writing.
  156. type SyncFileWriter struct {
  157. file *os.File
  158. step int
  159. count int
  160. }
  161. // NewSyncFileWriter creates a SyncFileWriter.
  162. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  163. return &SyncFileWriter{
  164. file: file,
  165. step: 2 << 16,
  166. count: 0}
  167. }
  168. // Write implements io.Writer with periodic file syncing.
  169. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  170. n, err = writer.file.Write(p)
  171. if err != nil {
  172. return
  173. }
  174. writer.count += n
  175. if writer.count >= writer.step {
  176. err = writer.file.Sync()
  177. writer.count = 0
  178. }
  179. return
  180. }
  181. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  182. // used as a stub, when a net.Addr is required but not used.
  183. type emptyAddr struct {
  184. }
  185. func (e *emptyAddr) String() string {
  186. return ""
  187. }
  188. func (e *emptyAddr) Network() string {
  189. return ""
  190. }
  191. // channelConn implements the net.Conn interface. channelConn allows use of
  192. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  193. // are implemented and the remaining functions are stubs and expected to not
  194. // be used.
  195. type channelConn struct {
  196. ssh.Channel
  197. }
  198. func newChannelConn(channel ssh.Channel) *channelConn {
  199. return &channelConn{
  200. Channel: channel,
  201. }
  202. }
  203. func (conn *channelConn) LocalAddr() net.Addr {
  204. return new(emptyAddr)
  205. }
  206. func (conn *channelConn) RemoteAddr() net.Addr {
  207. return new(emptyAddr)
  208. }
  209. func (conn *channelConn) SetDeadline(_ time.Time) error {
  210. return errors.TraceNew("unsupported")
  211. }
  212. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  213. return errors.TraceNew("unsupported")
  214. }
  215. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  216. return errors.TraceNew("unsupported")
  217. }
  218. func emitMemoryMetrics() {
  219. var memStats runtime.MemStats
  220. runtime.ReadMemStats(&memStats)
  221. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  222. stacktrace.GetParentFunctionName(),
  223. runtime.NumGoroutine(),
  224. memStats.HeapObjects,
  225. common.FormatByteCount(memStats.HeapAlloc),
  226. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  227. common.FormatByteCount(memStats.Sys),
  228. memStats.Mallocs,
  229. common.FormatByteCount(memStats.TotalAlloc))
  230. }
  231. func DoGarbageCollection() {
  232. debug.SetGCPercent(5)
  233. debug.FreeOSMemory()
  234. }
  235. // conditionallyEnabledComponents implements the
  236. // protocol.ConditionallyEnabledComponents interface.
  237. type conditionallyEnabledComponents struct {
  238. }
  239. func (c conditionallyEnabledComponents) QUICEnabled() bool {
  240. return quic.Enabled()
  241. }
  242. func (c conditionallyEnabledComponents) MarionetteEnabled() bool {
  243. return marionette.Enabled()
  244. }
  245. func (c conditionallyEnabledComponents) TapdanceEnabled() bool {
  246. return tapdance.Enabled()
  247. }