upgrade_supported.go 8.9 KB

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