utils.go 7.7 KB

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