// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ipnlocal import ( "context" "encoding/base64" "encoding/json" "errors" "fmt" "hash/crc32" "html" "io" "io/fs" "net" "net/http" "net/netip" "net/url" "os" "path" "path/filepath" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "unicode" "unicode/utf8" "github.com/kortschak/wol" "golang.org/x/net/dns/dnsmessage" "tailscale.com/client/tailscale/apitype" "tailscale.com/envknob" "tailscale.com/health" "tailscale.com/hostinfo" "tailscale.com/ipn" "tailscale.com/logtail/backoff" "tailscale.com/net/dns/resolver" "tailscale.com/net/interfaces" "tailscale.com/net/netaddr" "tailscale.com/net/netutil" "tailscale.com/tailcfg" "tailscale.com/util/clientmetric" "tailscale.com/util/strs" "tailscale.com/wgengine" "tailscale.com/wgengine/filter" ) var initListenConfig func(*net.ListenConfig, netip.Addr, *interfaces.State, string) error // addH2C is non-nil on platforms where we want to add H2C // ("cleartext" HTTP/2) support to the peerAPI. var addH2C func(*http.Server) type peerAPIServer struct { b *LocalBackend rootDir string // empty means file receiving unavailable selfNode *tailcfg.Node knownEmpty atomic.Bool resolver *resolver.Resolver // directFileMode is whether we're writing files directly to a // download directory (as *.partial files), rather than making // the frontend retrieve it over localapi HTTP and write it // somewhere itself. This is used on the GUI macOS versions // and on Synology. // In directFileMode, the peerapi doesn't do the final rename // from "foo.jpg.partial" to "foo.jpg" unless // directFileDoFinalRename is set. directFileMode bool // directFileDoFinalRename is whether in directFileMode we // additionally move the *.direct file to its final name after // it's received. directFileDoFinalRename bool } const ( // partialSuffix is the suffix appended to files while they're // still in the process of being transferred. partialSuffix = ".partial" // deletedSuffix is the suffix for a deleted marker file // that's placed next to a file (without the suffix) that we // tried to delete, but Windows wouldn't let us. These are // only written on Windows (and in tests), but they're not // permitted to be uploaded directly on any platform, like // partial files. deletedSuffix = ".deleted" ) func (s *peerAPIServer) canReceiveFiles() bool { return s != nil && s.rootDir != "" } func validFilenameRune(r rune) bool { switch r { case '/': return false case '\\', ':', '*', '"', '<', '>', '|': // Invalid stuff on Windows, but we reject them everywhere // for now. // TODO(bradfitz): figure out a better plan. We initially just // wrote things to disk URL path-escaped, but that's gross // when debugging, and just moves the problem to callers. // So now we put the UTF-8 filenames on disk directly as // sent. return false } return unicode.IsPrint(r) } func (s *peerAPIServer) diskPath(baseName string) (fullPath string, ok bool) { if !utf8.ValidString(baseName) { return "", false } if strings.TrimSpace(baseName) != baseName { return "", false } if len(baseName) > 255 { return "", false } // TODO: validate unicode normalization form too? Varies by platform. clean := path.Clean(baseName) if clean != baseName || clean == "." || clean == ".." || strings.HasSuffix(clean, deletedSuffix) || strings.HasSuffix(clean, partialSuffix) { return "", false } for _, r := range baseName { if !validFilenameRune(r) { return "", false } } return filepath.Join(s.rootDir, baseName), true } // hasFilesWaiting reports whether any files are buffered in the // tailscaled daemon storage. func (s *peerAPIServer) hasFilesWaiting() bool { if s == nil || s.rootDir == "" || s.directFileMode { return false } if s.knownEmpty.Load() { // Optimization: this is usually empty, so avoid opening // the directory and checking. We can't cache the actual // has-files-or-not values as the macOS/iOS client might // in the future use+delete the files directly. So only // keep this negative cache. return false } f, err := os.Open(s.rootDir) if err != nil { return false } defer f.Close() for { des, err := f.ReadDir(10) for _, de := range des { name := de.Name() if strings.HasSuffix(name, partialSuffix) { continue } if strings.HasSuffix(name, deletedSuffix) { // for Windows + tests // After we're done looping over files, then try // to delete this file. Don't do it proactively, // as the OS may return "foo.jpg.deleted" before "foo.jpg" // and we don't want to delete the ".deleted" file before // enumerating to the "foo.jpg" file. defer tryDeleteAgain(filepath.Join(s.rootDir, strings.TrimSuffix(name, deletedSuffix))) continue } if de.Type().IsRegular() { _, err := os.Stat(filepath.Join(s.rootDir, name+deletedSuffix)) if os.IsNotExist(err) { return true } if err == nil { tryDeleteAgain(filepath.Join(s.rootDir, name)) continue } } } if err == io.EOF { s.knownEmpty.Store(true) } if err != nil { break } } return false } // WaitingFiles returns the list of files that have been sent by a // peer that are waiting in the buffered "pick up" directory owned by // the Tailscale daemon. // // As a side effect, it also does any lazy deletion of files as // required by Windows. func (s *peerAPIServer) WaitingFiles() (ret []apitype.WaitingFile, err error) { if s == nil { return nil, errNilPeerAPIServer } if s.rootDir == "" { return nil, errNoTaildrop } if s.directFileMode { return nil, nil } f, err := os.Open(s.rootDir) if err != nil { return nil, err } defer f.Close() var deleted map[string]bool // "foo.jpg" => true (if "foo.jpg.deleted" exists) for { des, err := f.ReadDir(10) for _, de := range des { name := de.Name() if strings.HasSuffix(name, partialSuffix) { continue } if strings.HasSuffix(name, deletedSuffix) { // for Windows + tests if deleted == nil { deleted = map[string]bool{} } deleted[strings.TrimSuffix(name, deletedSuffix)] = true continue } if de.Type().IsRegular() { fi, err := de.Info() if err != nil { continue } ret = append(ret, apitype.WaitingFile{ Name: filepath.Base(name), Size: fi.Size(), }) } } if err == io.EOF { break } if err != nil { return nil, err } } if len(deleted) > 0 { // Filter out any return values "foo.jpg" where a // "foo.jpg.deleted" marker file exists on disk. all := ret ret = ret[:0] for _, wf := range all { if !deleted[wf.Name] { ret = append(ret, wf) } } // And do some opportunistic deleting while we're here. // Maybe Windows is done virus scanning the file we tried // to delete a long time ago and will let us delete it now. for name := range deleted { tryDeleteAgain(filepath.Join(s.rootDir, name)) } } sort.Slice(ret, func(i, j int) bool { return ret[i].Name < ret[j].Name }) return ret, nil } var ( errNilPeerAPIServer = errors.New("peerapi unavailable; not listening") errNoTaildrop = errors.New("Taildrop disabled; no storage directory") ) // tryDeleteAgain tries to delete path (and path+deletedSuffix) after // it failed earlier. This happens on Windows when various anti-virus // tools hook into filesystem operations and have the file open still // while we're trying to delete it. In that case we instead mark it as // deleted (writing a "foo.jpg.deleted" marker file), but then we // later try to clean them up. // // fullPath is the full path to the file without the deleted suffix. func tryDeleteAgain(fullPath string) { if err := os.Remove(fullPath); err == nil || os.IsNotExist(err) { os.Remove(fullPath + deletedSuffix) } } func (s *peerAPIServer) DeleteFile(baseName string) error { if s == nil { return errNilPeerAPIServer } if s.rootDir == "" { return errNoTaildrop } if s.directFileMode { return errors.New("deletes not allowed in direct mode") } path, ok := s.diskPath(baseName) if !ok { return errors.New("bad filename") } var bo *backoff.Backoff logf := s.b.logf t0 := time.Now() for { err := os.Remove(path) if err != nil && !os.IsNotExist(err) { err = redactErr(err) // Put a retry loop around deletes on Windows. Windows // file descriptor closes are effectively asynchronous, // as a bunch of hooks run on/after close, and we can't // necessarily delete the file for a while after close, // as we need to wait for everybody to be done with // it. (on Windows, unlike Unix, a file can't be deleted // if it's open anywhere) // So try a few times but ultimately just leave a // "foo.jpg.deleted" marker file to note that it's // deleted and we clean it up later. if runtime.GOOS == "windows" { if bo == nil { bo = backoff.NewBackoff("delete-retry", logf, 1*time.Second) } if time.Since(t0) < 5*time.Second { bo.BackOff(context.Background(), err) continue } if err := touchFile(path + deletedSuffix); err != nil { logf("peerapi: failed to leave deleted marker: %v", err) } } logf("peerapi: failed to DeleteFile: %v", err) return err } return nil } } // redacted is a fake path name we use in errors, to avoid // accidentally logging actual filenames anywhere. const redacted = "redacted" func redactErr(err error) error { if pe, ok := err.(*os.PathError); ok { pe.Path = redacted } return err } func touchFile(path string) error { f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666) if err != nil { return redactErr(err) } return f.Close() } func (s *peerAPIServer) OpenFile(baseName string) (rc io.ReadCloser, size int64, err error) { if s == nil { return nil, 0, errNilPeerAPIServer } if s.rootDir == "" { return nil, 0, errNoTaildrop } if s.directFileMode { return nil, 0, errors.New("opens not allowed in direct mode") } path, ok := s.diskPath(baseName) if !ok { return nil, 0, errors.New("bad filename") } if fi, err := os.Stat(path + deletedSuffix); err == nil && fi.Mode().IsRegular() { tryDeleteAgain(path) return nil, 0, &fs.PathError{Op: "open", Path: redacted, Err: fs.ErrNotExist} } f, err := os.Open(path) if err != nil { return nil, 0, redactErr(err) } fi, err := f.Stat() if err != nil { f.Close() return nil, 0, redactErr(err) } return f, fi.Size(), nil } func (s *peerAPIServer) listen(ip netip.Addr, ifState *interfaces.State) (ln net.Listener, err error) { // Android for whatever reason often has problems creating the peerapi listener. // But since we started intercepting it with netstack, it's not even important that // we have a real kernel-level listener. So just create a dummy listener on Android // and let netstack intercept it. if runtime.GOOS == "android" { return newFakePeerAPIListener(ip), nil } ipStr := ip.String() var lc net.ListenConfig if initListenConfig != nil { // On iOS/macOS, this sets the lc.Control hook to // setsockopt the interface index to bind to, to get // out of the network sandbox. if err := initListenConfig(&lc, ip, ifState, s.b.dialer.TUNName()); err != nil { return nil, err } if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { ipStr = "" } } if wgengine.IsNetstack(s.b.e) { ipStr = "" } tcp4or6 := "tcp4" if ip.Is6() { tcp4or6 = "tcp6" } // Make a best effort to pick a deterministic port number for // the ip. The lower three bytes are the same for IPv4 and IPv6 // Tailscale addresses (at least currently), so we'll usually // get the same port number on both address families for // dev/debugging purposes, which is nice. But it's not so // deterministic that people will bake this into clients. // We try a few times just in case something's already // listening on that port (on all interfaces, probably). for try := uint8(0); try < 5; try++ { a16 := ip.As16() hashData := a16[len(a16)-3:] hashData[0] += try tryPort := (32 << 10) | uint16(crc32.ChecksumIEEE(hashData)) ln, err = lc.Listen(context.Background(), tcp4or6, net.JoinHostPort(ipStr, strconv.Itoa(int(tryPort)))) if err == nil { return ln, nil } } // Fall back to some random ephemeral port. ln, err = lc.Listen(context.Background(), tcp4or6, net.JoinHostPort(ipStr, "0")) // And if we're on a platform with netstack (anything but iOS), then just fallback to netstack. if err != nil && runtime.GOOS != "ios" { s.b.logf("peerapi: failed to do peerAPI listen, harmless (netstack available) but error was: %v", err) return newFakePeerAPIListener(ip), nil } return ln, err } type peerAPIListener struct { ps *peerAPIServer ip netip.Addr lb *LocalBackend // ln is the Listener. It can be nil in netstack mode if there are more than // 1 local addresses (e.g. both an IPv4 and IPv6). When it's nil, port // and urlStr are still populated. ln net.Listener // urlStr is the base URL to access the peer API (http://ip:port/). urlStr string // port is just the port of urlStr. port int } func (pln *peerAPIListener) Close() error { if pln.ln != nil { return pln.ln.Close() } return nil } func (pln *peerAPIListener) serve() { if pln.ln == nil { return } defer pln.ln.Close() logf := pln.lb.logf for { c, err := pln.ln.Accept() if errors.Is(err, net.ErrClosed) { return } if err != nil { logf("peerapi.Accept: %v", err) return } ta, ok := c.RemoteAddr().(*net.TCPAddr) if !ok { c.Close() logf("peerapi: unexpected RemoteAddr %#v", c.RemoteAddr()) continue } ipp := netaddr.Unmap(ta.AddrPort()) if !ipp.IsValid() { logf("peerapi: bogus TCPAddr %#v", ta) c.Close() continue } pln.ServeConn(ipp, c) } } func (pln *peerAPIListener) ServeConn(src netip.AddrPort, c net.Conn) { logf := pln.lb.logf peerNode, peerUser, ok := pln.lb.WhoIs(src) if !ok { logf("peerapi: unknown peer %v", src) c.Close() return } h := &peerAPIHandler{ ps: pln.ps, isSelf: pln.ps.selfNode.User == peerNode.User, remoteAddr: src, peerNode: peerNode, peerUser: peerUser, } httpServer := &http.Server{ Handler: h, } if addH2C != nil { addH2C(httpServer) } go httpServer.Serve(netutil.NewOneConnListener(c, pln.ln.Addr())) } // peerAPIHandler serves the Peer API for a source specific client. type peerAPIHandler struct { ps *peerAPIServer remoteAddr netip.AddrPort isSelf bool // whether peerNode is owned by same user as this node peerNode *tailcfg.Node // peerNode is who's making the request peerUser tailcfg.UserProfile // profile of peerNode } func (h *peerAPIHandler) logf(format string, a ...any) { h.ps.b.logf("peerapi: "+format, a...) } func (h *peerAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/v0/put/") { h.handlePeerPut(w, r) return } if strings.HasPrefix(r.URL.Path, "/dns-query") { h.handleDNSQuery(w, r) return } switch r.URL.Path { case "/v0/goroutines": h.handleServeGoroutines(w, r) return case "/v0/env": h.handleServeEnv(w, r) return case "/v0/metrics": h.handleServeMetrics(w, r) return case "/v0/magicsock": h.handleServeMagicsock(w, r) return case "/v0/dnsfwd": h.handleServeDNSFwd(w, r) return case "/v0/wol": h.handleWakeOnLAN(w, r) return case "/v0/interfaces": h.handleServeInterfaces(w, r) return case "/v0/ingress": h.handleServeIngress(w, r) return } who := h.peerUser.DisplayName fmt.Fprintf(w, `
You are the owner of this node.\n") } } func (h *peerAPIHandler) handleServeIngress(w http.ResponseWriter, r *http.Request) { // http.Errors only useful if hitting endpoint manually // otherwise rely on log lines when debugging ingress connections // as connection is hijacked for bidi and is encrypted tls if !h.canIngress() { h.logf("ingress: denied; no ingress cap from %v", h.remoteAddr) http.Error(w, "denied; no ingress cap", http.StatusForbidden) return } logAndError := func(code int, publicMsg string) { h.logf("ingress: bad request from %v: %s", h.remoteAddr, publicMsg) http.Error(w, publicMsg, http.StatusMethodNotAllowed) } bad := func(publicMsg string) { logAndError(http.StatusBadRequest, publicMsg) } if r.Method != "POST" { logAndError(http.StatusMethodNotAllowed, "only POST allowed") return } srcAddrStr := r.Header.Get("Tailscale-Ingress-Src") if srcAddrStr == "" { bad("Tailscale-Ingress-Src header not set") return } srcAddr, err := netip.ParseAddrPort(srcAddrStr) if err != nil { bad("Tailscale-Ingress-Src header invalid; want ip:port") return } target := r.Header.Get("Tailscale-Ingress-Target") if target == "" { bad("Tailscale-Target-Target header not set") return } if _, _, err := net.SplitHostPort(target); err != nil { bad("Tailscale-Target-Target header invalid; want host:port") return } getConn := func() (net.Conn, bool) { conn, _, err := w.(http.Hijacker).Hijack() if err != nil { h.logf("ingress: failed hijacking conn") http.Error(w, "failed hijacking conn", http.StatusInternalServerError) return nil, false } io.WriteString(conn, "HTTP/1.1 101 Switching Protocols\r\n\r\n") return conn, true } sendRST := func() { http.Error(w, "denied", http.StatusForbidden) } h.ps.b.HandleIngressTCPConn(h.peerNode, ipn.HostPort(target), srcAddr, getConn, sendRST) } func (h *peerAPIHandler) handleServeInterfaces(w http.ResponseWriter, r *http.Request) { if !h.canDebug() { http.Error(w, "denied; no debug access", http.StatusForbidden) return } i, err := interfaces.GetList() if err != nil { http.Error(w, err.Error(), 500) } dr, err := interfaces.DefaultRoute() if err != nil { http.Error(w, err.Error(), 500) } w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprintln(w, "
%v | ", v) } fmt.Fprint(w, "
---|
%v | ", v) } fmt.Fprint(w, "