upgrade_supported.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:build !noupgrade && !ios
  7. // +build !noupgrade,!ios
  8. package upgrade
  9. import (
  10. "archive/tar"
  11. "archive/zip"
  12. "bytes"
  13. "compress/gzip"
  14. "crypto/tls"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "net/http"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "runtime"
  24. "sort"
  25. "strings"
  26. "time"
  27. "github.com/syncthing/syncthing/lib/dialer"
  28. "github.com/syncthing/syncthing/lib/signature"
  29. "golang.org/x/net/http2"
  30. )
  31. const DisabledByCompilation = false
  32. const (
  33. // Current binary size hovers around 10 MB. We give it some room to grow
  34. // and say that we never expect the binary to be larger than 64 MB.
  35. maxBinarySize = 64 << 20 // 64 MiB
  36. // The max expected size of the signature file.
  37. maxSignatureSize = 10 << 10 // 10 KiB
  38. // We set the same limit on the archive. The binary will compress and we
  39. // include some other stuff - currently the release archive size is
  40. // around 6 MB.
  41. maxArchiveSize = maxBinarySize
  42. // When looking through the archive for the binary and signature, stop
  43. // looking once we've searched this many files.
  44. maxArchiveMembers = 100
  45. // Archive reads, or metadata checks, that take longer than this will be
  46. // rejected.
  47. readTimeout = 30 * time.Minute
  48. // The limit on the size of metadata that we accept.
  49. maxMetadataSize = 10 << 20 // 10 MiB
  50. )
  51. // This is an HTTP/HTTPS client that does *not* perform certificate
  52. // validation. We do this because some systems where Syncthing runs have
  53. // issues with old or missing CA roots. It doesn't actually matter that we
  54. // load the upgrade insecurely as we verify an ECDSA signature of the actual
  55. // binary contents before accepting the upgrade.
  56. var insecureHTTP = &http.Client{
  57. Timeout: readTimeout,
  58. Transport: &http.Transport{
  59. DialContext: dialer.DialContext,
  60. Proxy: http.ProxyFromEnvironment,
  61. TLSClientConfig: &tls.Config{
  62. InsecureSkipVerify: true,
  63. },
  64. },
  65. }
  66. func init() {
  67. _ = http2.ConfigureTransport(insecureHTTP.Transport.(*http.Transport))
  68. }
  69. func insecureGet(url, version string) (*http.Response, error) {
  70. req, err := http.NewRequest(http.MethodGet, url, nil)
  71. if err != nil {
  72. return nil, err
  73. }
  74. req.Header.Set("User-Agent", fmt.Sprintf(`syncthing %s (%s %s-%s)`, version, runtime.Version(), runtime.GOOS, runtime.GOARCH))
  75. return insecureHTTP.Do(req)
  76. }
  77. // FetchLatestReleases returns the latest releases. The "current" parameter
  78. // is used for setting the User-Agent only.
  79. func FetchLatestReleases(releasesURL, current string) []Release {
  80. resp, err := insecureGet(releasesURL, current)
  81. if err != nil {
  82. l.Infoln("Couldn't fetch release information:", err)
  83. return nil
  84. }
  85. if resp.StatusCode > 299 {
  86. l.Infoln("API call returned HTTP error:", resp.Status)
  87. return nil
  88. }
  89. var rels []Release
  90. err = json.NewDecoder(io.LimitReader(resp.Body, maxMetadataSize)).Decode(&rels)
  91. if err != nil {
  92. l.Infoln("Fetching release information:", err)
  93. }
  94. resp.Body.Close()
  95. return rels
  96. }
  97. type SortByRelease []Release
  98. func (s SortByRelease) Len() int {
  99. return len(s)
  100. }
  101. func (s SortByRelease) Swap(i, j int) {
  102. s[i], s[j] = s[j], s[i]
  103. }
  104. func (s SortByRelease) Less(i, j int) bool {
  105. return CompareVersions(s[i].Tag, s[j].Tag) > 0
  106. }
  107. func LatestRelease(releasesURL, current string, upgradeToPreReleases bool) (Release, error) {
  108. rels := FetchLatestReleases(releasesURL, current)
  109. return SelectLatestRelease(rels, current, upgradeToPreReleases)
  110. }
  111. func SelectLatestRelease(rels []Release, current string, upgradeToPreReleases bool) (Release, error) {
  112. if len(rels) == 0 {
  113. return Release{}, ErrNoVersionToSelect
  114. }
  115. // Sort the releases, lowest version number first
  116. sort.Sort(sort.Reverse(SortByRelease(rels)))
  117. var selected Release
  118. for _, rel := range rels {
  119. if CompareVersions(rel.Tag, current) == MajorNewer {
  120. // We've found a new major version. That's fine, but if we've
  121. // already found a minor upgrade that is acceptable we should go
  122. // with that one first and then revisit in the future.
  123. if selected.Tag != "" && CompareVersions(selected.Tag, current) == Newer {
  124. return selected, nil
  125. }
  126. }
  127. if rel.Prerelease && !upgradeToPreReleases {
  128. l.Debugln("skipping pre-release", rel.Tag)
  129. continue
  130. }
  131. expectedReleases := releaseNames(rel.Tag)
  132. nextAsset:
  133. for _, asset := range rel.Assets {
  134. assetName := path.Base(asset.Name)
  135. // Check for the architecture
  136. for _, expRel := range expectedReleases {
  137. if strings.HasPrefix(assetName, expRel) {
  138. l.Debugln("selected", rel.Tag)
  139. selected = rel
  140. break nextAsset
  141. }
  142. }
  143. }
  144. }
  145. if selected.Tag == "" {
  146. return Release{}, ErrNoReleaseDownload
  147. }
  148. return selected, nil
  149. }
  150. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  151. func upgradeTo(binary string, rel Release) error {
  152. expectedReleases := releaseNames(rel.Tag)
  153. for _, asset := range rel.Assets {
  154. assetName := path.Base(asset.Name)
  155. l.Debugln("considering release", assetName)
  156. for _, expRel := range expectedReleases {
  157. if strings.HasPrefix(assetName, expRel) {
  158. return upgradeToURL(assetName, binary, asset.URL)
  159. }
  160. }
  161. }
  162. return ErrNoReleaseDownload
  163. }
  164. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  165. func upgradeToURL(archiveName, binary string, url string) error {
  166. fname, err := readRelease(archiveName, filepath.Dir(binary), url)
  167. if err != nil {
  168. return err
  169. }
  170. defer os.Remove(fname)
  171. old := binary + ".old"
  172. os.Remove(old)
  173. err = os.Rename(binary, old)
  174. if err != nil {
  175. return err
  176. }
  177. if err := os.Rename(fname, binary); err != nil {
  178. os.Rename(old, binary)
  179. return err
  180. }
  181. return nil
  182. }
  183. func readRelease(archiveName, dir, url string) (string, error) {
  184. l.Debugf("loading %q", url)
  185. req, err := http.NewRequest("GET", url, nil)
  186. if err != nil {
  187. return "", err
  188. }
  189. req.Header.Add("Accept", "application/octet-stream")
  190. resp, err := insecureHTTP.Do(req)
  191. if err != nil {
  192. return "", err
  193. }
  194. defer resp.Body.Close()
  195. switch path.Ext(archiveName) {
  196. case ".zip":
  197. return readZip(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  198. default:
  199. return readTarGz(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  200. }
  201. }
  202. func readTarGz(archiveName, dir string, r io.Reader) (string, error) {
  203. gr, err := gzip.NewReader(r)
  204. if err != nil {
  205. return "", err
  206. }
  207. tr := tar.NewReader(gr)
  208. var tempName string
  209. var sig []byte
  210. // Iterate through the files in the archive.
  211. i := 0
  212. for {
  213. if i >= maxArchiveMembers {
  214. break
  215. }
  216. i++
  217. hdr, err := tr.Next()
  218. if err == io.EOF {
  219. // end of tar archive
  220. break
  221. }
  222. if err != nil {
  223. return "", err
  224. }
  225. if hdr.Size > maxBinarySize {
  226. // We don't even want to try processing or skipping over files
  227. // that are too large.
  228. break
  229. }
  230. err = archiveFileVisitor(dir, &tempName, &sig, hdr.Name, tr)
  231. if err != nil {
  232. return "", err
  233. }
  234. if tempName != "" && sig != nil {
  235. break
  236. }
  237. }
  238. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  239. return "", err
  240. }
  241. return tempName, nil
  242. }
  243. func readZip(archiveName, dir string, r io.Reader) (string, error) {
  244. body, err := io.ReadAll(r)
  245. if err != nil {
  246. return "", err
  247. }
  248. archive, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
  249. if err != nil {
  250. return "", err
  251. }
  252. var tempName string
  253. var sig []byte
  254. // Iterate through the files in the archive.
  255. i := 0
  256. for _, file := range archive.File {
  257. if i >= maxArchiveMembers {
  258. break
  259. }
  260. i++
  261. if file.UncompressedSize64 > maxBinarySize {
  262. // We don't even want to try processing or skipping over files
  263. // that are too large.
  264. break
  265. }
  266. inFile, err := file.Open()
  267. if err != nil {
  268. return "", err
  269. }
  270. err = archiveFileVisitor(dir, &tempName, &sig, file.Name, inFile)
  271. inFile.Close()
  272. if err != nil {
  273. return "", err
  274. }
  275. if tempName != "" && sig != nil {
  276. break
  277. }
  278. }
  279. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  280. return "", err
  281. }
  282. return tempName, nil
  283. }
  284. // archiveFileVisitor is called for each file in an archive. It may set
  285. // tempFile and signature.
  286. func archiveFileVisitor(dir string, tempFile *string, signature *[]byte, archivePath string, filedata io.Reader) error {
  287. var err error
  288. filename := path.Base(archivePath)
  289. archiveDir := path.Dir(archivePath)
  290. l.Debugf("considering file %s", archivePath)
  291. switch filename {
  292. case "syncthing", "syncthing.exe":
  293. archiveDirs := strings.Split(archiveDir, "/")
  294. if len(archiveDirs) > 1 {
  295. // Don't consider "syncthing" files found too deeply, as they may be
  296. // other things.
  297. return nil
  298. }
  299. l.Debugf("found upgrade binary %s", archivePath)
  300. *tempFile, err = writeBinary(dir, io.LimitReader(filedata, maxBinarySize))
  301. if err != nil {
  302. return err
  303. }
  304. case "release.sig":
  305. l.Debugf("found signature %s", archivePath)
  306. *signature, err = io.ReadAll(io.LimitReader(filedata, maxSignatureSize))
  307. if err != nil {
  308. return err
  309. }
  310. }
  311. return nil
  312. }
  313. func verifyUpgrade(archiveName, tempName string, sig []byte) error {
  314. if tempName == "" {
  315. return errors.New("no upgrade found")
  316. }
  317. if sig == nil {
  318. return errors.New("no signature found")
  319. }
  320. l.Debugf("checking signature\n%s", sig)
  321. fd, err := os.Open(tempName)
  322. if err != nil {
  323. return err
  324. }
  325. // Create a new reader that will serve reads from, in order:
  326. //
  327. // - the archive name ("syncthing-linux-amd64-v0.13.0-beta.4.tar.gz")
  328. // followed by a newline
  329. //
  330. // - the temp file contents
  331. //
  332. // We then verify the release signature against the contents of this
  333. // multireader. This ensures that it is not only a bonafide syncthing
  334. // binary, but it is also of exactly the platform and version we expect.
  335. mr := io.MultiReader(strings.NewReader(archiveName+"\n"), fd)
  336. err = signature.Verify(SigningKey, sig, mr)
  337. fd.Close()
  338. if err != nil {
  339. os.Remove(tempName)
  340. return err
  341. }
  342. return nil
  343. }
  344. func writeBinary(dir string, inFile io.Reader) (filename string, err error) {
  345. // Write the binary to a temporary file.
  346. outFile, err := os.CreateTemp(dir, "syncthing")
  347. if err != nil {
  348. return "", err
  349. }
  350. _, err = io.Copy(outFile, inFile)
  351. if err != nil {
  352. os.Remove(outFile.Name())
  353. return "", err
  354. }
  355. err = outFile.Close()
  356. if err != nil {
  357. os.Remove(outFile.Name())
  358. return "", err
  359. }
  360. err = os.Chmod(outFile.Name(), os.FileMode(0755))
  361. if err != nil {
  362. os.Remove(outFile.Name())
  363. return "", err
  364. }
  365. return outFile.Name(), nil
  366. }