utils.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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/stacktrace"
  38. )
  39. // MakePsiphonUserAgent constructs a User-Agent value to use for web service
  40. // requests made by the tunnel-core client. The User-Agent includes useful stats
  41. // information; it is to be used only for HTTPS requests, where the header
  42. // cannot be seen by an adversary.
  43. func MakePsiphonUserAgent(config *Config) string {
  44. userAgent := "psiphon-tunnel-core"
  45. if config.ClientVersion != "" {
  46. userAgent += fmt.Sprintf("/%s", config.ClientVersion)
  47. }
  48. if config.ClientPlatform != "" {
  49. userAgent += fmt.Sprintf(" (%s)", config.ClientPlatform)
  50. }
  51. return userAgent
  52. }
  53. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  54. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  55. if err != nil {
  56. return nil, errors.Trace(err)
  57. }
  58. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  59. if err != nil {
  60. return nil, errors.Trace(err)
  61. }
  62. return certificate, nil
  63. }
  64. // FilterUrlError transforms an error, when it is a url.Error, removing
  65. // the URL value. This is to avoid logging private user data in cases
  66. // where the URL may be a user input value.
  67. // This function is used with errors returned by net/http and net/url,
  68. // which are (currently) of type url.Error. In particular, the round trip
  69. // function used by our HttpProxy, http.Client.Do, returns errors of type
  70. // url.Error, with the URL being the url sent from the user's tunneled
  71. // applications:
  72. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  73. func FilterUrlError(err error) error {
  74. if urlErr, ok := err.(*url.Error); ok {
  75. err = &url.Error{
  76. Op: urlErr.Op,
  77. URL: "",
  78. Err: urlErr.Err,
  79. }
  80. }
  81. return err
  82. }
  83. // TrimError removes the middle of over-long error message strings
  84. func TrimError(err error) error {
  85. const MAX_LEN = 100
  86. message := fmt.Sprintf("%s", err)
  87. if len(message) > MAX_LEN {
  88. return std_errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  89. }
  90. return err
  91. }
  92. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  93. func IsAddressInUseError(err error) bool {
  94. if err, ok := err.(*net.OpError); ok {
  95. if err, ok := err.Err.(*os.SyscallError); ok {
  96. if err.Err == syscall.EADDRINUSE {
  97. return true
  98. }
  99. // Special case for Windows (WSAEADDRINUSE = 10048)
  100. if errno, ok := err.Err.(syscall.Errno); ok {
  101. if int(errno) == 10048 {
  102. return true
  103. }
  104. }
  105. }
  106. }
  107. return false
  108. }
  109. var stripIPv4AddressRegex = regexp.MustCompile(
  110. `(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}))?`)
  111. // StripIPAddresses returns a copy of the input with all IP addresses [and
  112. // optional ports] replaced by "[address]". This is intended to be used to
  113. // strip addresses from "net" package I/O error messages and otherwise avoid
  114. // inadvertently recording direct server IPs via error message logs; and, in
  115. // metrics, to reduce the error space due to superfluous source port data.
  116. //
  117. // Limitation: only strips IPv4 addresses.
  118. func StripIPAddresses(b []byte) []byte {
  119. // TODO: IPv6 support
  120. return stripIPv4AddressRegex.ReplaceAll(b, []byte("[redacted]"))
  121. }
  122. // StripIPAddressesString is StripIPAddresses for strings.
  123. func StripIPAddressesString(s string) string {
  124. // TODO: IPv6 support
  125. return stripIPv4AddressRegex.ReplaceAllString(s, "[redacted]")
  126. }
  127. // RedactNetError removes network address information from a "net" package
  128. // error message. Addresses may be domains or IP addresses.
  129. //
  130. // Limitations: some non-address error context can be lost; this function
  131. // makes assumptions about how the Go "net" package error messages are
  132. // formatted and will fail to redact network addresses if this assumptions
  133. // become untrue.
  134. func RedactNetError(err error) error {
  135. // Example "net" package error messages:
  136. //
  137. // - lookup <domain>: no such host
  138. // - lookup <domain>: No address associated with hostname
  139. // - dial tcp <address>: connectex: No connection could be made because the target machine actively refused it
  140. // - write tcp <address>-><address>: write: connection refused
  141. if err == nil {
  142. return err
  143. }
  144. errstr := err.Error()
  145. index := strings.Index(errstr, ": ")
  146. if index == -1 {
  147. return err
  148. }
  149. return std_errors.New("[redacted]" + errstr[index:])
  150. }
  151. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  152. // steps, the file is synced (flushed to disk) while writing.
  153. type SyncFileWriter struct {
  154. file *os.File
  155. step int
  156. count int
  157. }
  158. // NewSyncFileWriter creates a SyncFileWriter.
  159. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  160. return &SyncFileWriter{
  161. file: file,
  162. step: 2 << 16,
  163. count: 0}
  164. }
  165. // Write implements io.Writer with periodic file syncing.
  166. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  167. n, err = writer.file.Write(p)
  168. if err != nil {
  169. return
  170. }
  171. writer.count += n
  172. if writer.count >= writer.step {
  173. err = writer.file.Sync()
  174. writer.count = 0
  175. }
  176. return
  177. }
  178. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  179. // used as a stub, when a net.Addr is required but not used.
  180. type emptyAddr struct {
  181. }
  182. func (e *emptyAddr) String() string {
  183. return ""
  184. }
  185. func (e *emptyAddr) Network() string {
  186. return ""
  187. }
  188. // channelConn implements the net.Conn interface. channelConn allows use of
  189. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  190. // are implemented and the remaining functions are stubs and expected to not
  191. // be used.
  192. type channelConn struct {
  193. ssh.Channel
  194. }
  195. func newChannelConn(channel ssh.Channel) *channelConn {
  196. return &channelConn{
  197. Channel: channel,
  198. }
  199. }
  200. func (conn *channelConn) LocalAddr() net.Addr {
  201. return new(emptyAddr)
  202. }
  203. func (conn *channelConn) RemoteAddr() net.Addr {
  204. return new(emptyAddr)
  205. }
  206. func (conn *channelConn) SetDeadline(_ time.Time) error {
  207. return errors.TraceNew("unsupported")
  208. }
  209. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  210. return errors.TraceNew("unsupported")
  211. }
  212. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  213. return errors.TraceNew("unsupported")
  214. }
  215. func emitMemoryMetrics() {
  216. var memStats runtime.MemStats
  217. runtime.ReadMemStats(&memStats)
  218. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  219. stacktrace.GetParentFunctionName(),
  220. runtime.NumGoroutine(),
  221. memStats.HeapObjects,
  222. common.FormatByteCount(memStats.HeapAlloc),
  223. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  224. common.FormatByteCount(memStats.Sys),
  225. memStats.Mallocs,
  226. common.FormatByteCount(memStats.TotalAlloc))
  227. }
  228. func DoGarbageCollection() {
  229. debug.SetGCPercent(5)
  230. debug.FreeOSMemory()
  231. }