upgrade_supported.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 = 10 << 10 // 10 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 = 10 << 20 // 10 MiB
  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. func insecureGet(url, version string) (*http.Response, error) {
  65. req, err := http.NewRequest("GET", url, nil)
  66. if err != nil {
  67. return nil, err
  68. }
  69. req.Header.Set("User-Agent", fmt.Sprintf(`syncthing %s (%s %s-%s)`, version, runtime.Version(), runtime.GOOS, runtime.GOARCH))
  70. return insecureHTTP.Do(req)
  71. }
  72. // FetchLatestReleases returns the latest releases. The "current" parameter
  73. // is used for setting the User-Agent only.
  74. func FetchLatestReleases(releasesURL, current string) []Release {
  75. resp, err := insecureGet(releasesURL, current)
  76. if err != nil {
  77. l.Infoln("Couldn't fetch release information:", err)
  78. return nil
  79. }
  80. if resp.StatusCode > 299 {
  81. l.Infoln("API call returned HTTP error:", resp.Status)
  82. return nil
  83. }
  84. var rels []Release
  85. err = json.NewDecoder(io.LimitReader(resp.Body, maxMetadataSize)).Decode(&rels)
  86. if err != nil {
  87. l.Infoln("Fetching release information:", err)
  88. }
  89. resp.Body.Close()
  90. return rels
  91. }
  92. type SortByRelease []Release
  93. func (s SortByRelease) Len() int {
  94. return len(s)
  95. }
  96. func (s SortByRelease) Swap(i, j int) {
  97. s[i], s[j] = s[j], s[i]
  98. }
  99. func (s SortByRelease) Less(i, j int) bool {
  100. return CompareVersions(s[i].Tag, s[j].Tag) > 0
  101. }
  102. func LatestRelease(releasesURL, current string, upgradeToPreReleases bool) (Release, error) {
  103. rels := FetchLatestReleases(releasesURL, current)
  104. return SelectLatestRelease(rels, current, upgradeToPreReleases)
  105. }
  106. func SelectLatestRelease(rels []Release, current string, upgradeToPreReleases bool) (Release, error) {
  107. if len(rels) == 0 {
  108. return Release{}, ErrNoVersionToSelect
  109. }
  110. // Sort the releases, lowest version number first
  111. sort.Sort(sort.Reverse(SortByRelease(rels)))
  112. var selected Release
  113. for _, rel := range rels {
  114. switch CompareVersions(rel.Tag, current) {
  115. case Older, MajorOlder:
  116. // This is older than what we're already running
  117. continue
  118. case MajorNewer:
  119. // We've found a new major version. That's fine, but if we've
  120. // already found a minor upgrade that is acceptable we should go
  121. // with that one first and then revisit in the future.
  122. if selected.Tag != "" && CompareVersions(selected.Tag, current) == Newer {
  123. return selected, nil
  124. }
  125. // else it may be viable, do the needful below
  126. default:
  127. // New minor release, do the usual processing
  128. }
  129. if rel.Prerelease && !upgradeToPreReleases {
  130. continue
  131. }
  132. for _, asset := range rel.Assets {
  133. assetName := path.Base(asset.Name)
  134. // Check for the architecture
  135. expectedRelease := releaseName(rel.Tag)
  136. l.Debugf("expected release asset %q", expectedRelease)
  137. l.Debugln("considering release", assetName)
  138. if strings.HasPrefix(assetName, expectedRelease) {
  139. selected = rel
  140. }
  141. }
  142. }
  143. if selected.Tag == "" {
  144. return Release{}, ErrNoReleaseDownload
  145. }
  146. return selected, nil
  147. }
  148. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  149. func upgradeTo(binary string, rel Release) error {
  150. expectedRelease := releaseName(rel.Tag)
  151. l.Debugf("expected release asset %q", expectedRelease)
  152. for _, asset := range rel.Assets {
  153. assetName := path.Base(asset.Name)
  154. l.Debugln("considering release", assetName)
  155. if strings.HasPrefix(assetName, expectedRelease) {
  156. return upgradeToURL(assetName, binary, asset.URL)
  157. }
  158. }
  159. return ErrNoReleaseDownload
  160. }
  161. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  162. func upgradeToURL(archiveName, binary string, url string) error {
  163. fname, err := readRelease(archiveName, filepath.Dir(binary), url)
  164. if err != nil {
  165. return err
  166. }
  167. defer os.Remove(fname)
  168. old := binary + ".old"
  169. os.Remove(old)
  170. err = os.Rename(binary, old)
  171. if err != nil {
  172. return err
  173. }
  174. if os.Rename(fname, binary); err != nil {
  175. os.Rename(old, binary)
  176. return err
  177. }
  178. return nil
  179. }
  180. func readRelease(archiveName, dir, url string) (string, error) {
  181. l.Debugf("loading %q", url)
  182. req, err := http.NewRequest("GET", url, nil)
  183. if err != nil {
  184. return "", err
  185. }
  186. req.Header.Add("Accept", "application/octet-stream")
  187. resp, err := insecureHTTP.Do(req)
  188. if err != nil {
  189. return "", err
  190. }
  191. defer resp.Body.Close()
  192. switch runtime.GOOS {
  193. case "windows":
  194. return readZip(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  195. default:
  196. return readTarGz(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  197. }
  198. }
  199. func readTarGz(archiveName, dir string, r io.Reader) (string, error) {
  200. gr, err := gzip.NewReader(r)
  201. if err != nil {
  202. return "", err
  203. }
  204. tr := tar.NewReader(gr)
  205. var tempName string
  206. var sig []byte
  207. // Iterate through the files in the archive.
  208. i := 0
  209. for {
  210. if i >= maxArchiveMembers {
  211. break
  212. }
  213. i++
  214. hdr, err := tr.Next()
  215. if err == io.EOF {
  216. // end of tar archive
  217. break
  218. }
  219. if err != nil {
  220. return "", err
  221. }
  222. if hdr.Size > maxBinarySize {
  223. // We don't even want to try processing or skipping over files
  224. // that are too large.
  225. break
  226. }
  227. err = archiveFileVisitor(dir, &tempName, &sig, hdr.Name, tr)
  228. if err != nil {
  229. return "", err
  230. }
  231. if tempName != "" && sig != nil {
  232. break
  233. }
  234. }
  235. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  236. return "", err
  237. }
  238. return tempName, nil
  239. }
  240. func readZip(archiveName, dir string, r io.Reader) (string, error) {
  241. body, err := ioutil.ReadAll(r)
  242. if err != nil {
  243. return "", err
  244. }
  245. archive, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
  246. if err != nil {
  247. return "", err
  248. }
  249. var tempName string
  250. var sig []byte
  251. // Iterate through the files in the archive.
  252. i := 0
  253. for _, file := range archive.File {
  254. if i >= maxArchiveMembers {
  255. break
  256. }
  257. i++
  258. if file.UncompressedSize64 > maxBinarySize {
  259. // We don't even want to try processing or skipping over files
  260. // that are too large.
  261. break
  262. }
  263. inFile, err := file.Open()
  264. if err != nil {
  265. return "", err
  266. }
  267. err = archiveFileVisitor(dir, &tempName, &sig, file.Name, inFile)
  268. inFile.Close()
  269. if err != nil {
  270. return "", err
  271. }
  272. if tempName != "" && sig != nil {
  273. break
  274. }
  275. }
  276. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  277. return "", err
  278. }
  279. return tempName, nil
  280. }
  281. // archiveFileVisitor is called for each file in an archive. It may set
  282. // tempFile and signature.
  283. func archiveFileVisitor(dir string, tempFile *string, signature *[]byte, archivePath string, filedata io.Reader) error {
  284. var err error
  285. filename := path.Base(archivePath)
  286. archiveDir := path.Dir(archivePath)
  287. l.Debugf("considering file %s", archivePath)
  288. switch filename {
  289. case "syncthing", "syncthing.exe":
  290. archiveDirs := strings.Split(archiveDir, "/")
  291. if len(archiveDirs) > 1 {
  292. // Don't consider "syncthing" files found too deeply, as they may be
  293. // other things.
  294. return nil
  295. }
  296. l.Debugf("found upgrade binary %s", archivePath)
  297. *tempFile, err = writeBinary(dir, io.LimitReader(filedata, maxBinarySize))
  298. if err != nil {
  299. return err
  300. }
  301. case "release.sig":
  302. l.Debugf("found signature %s", archivePath)
  303. *signature, err = ioutil.ReadAll(io.LimitReader(filedata, maxSignatureSize))
  304. if err != nil {
  305. return err
  306. }
  307. }
  308. return nil
  309. }
  310. func verifyUpgrade(archiveName, tempName string, sig []byte) error {
  311. if tempName == "" {
  312. return fmt.Errorf("no upgrade found")
  313. }
  314. if sig == nil {
  315. return fmt.Errorf("no signature found")
  316. }
  317. l.Debugf("checking signature\n%s", sig)
  318. fd, err := os.Open(tempName)
  319. if err != nil {
  320. return err
  321. }
  322. // Create a new reader that will serve reads from, in order:
  323. //
  324. // - the archive name ("syncthing-linux-amd64-v0.13.0-beta.4.tar.gz")
  325. // followed by a newline
  326. //
  327. // - the temp file contents
  328. //
  329. // We then verify the release signature against the contents of this
  330. // multireader. This ensures that it is not only a bonafide syncthing
  331. // binary, but it it also of exactly the platform and version we expect.
  332. mr := io.MultiReader(bytes.NewBufferString(archiveName+"\n"), fd)
  333. err = signature.Verify(SigningKey, sig, mr)
  334. fd.Close()
  335. if err != nil {
  336. os.Remove(tempName)
  337. return err
  338. }
  339. return nil
  340. }
  341. func writeBinary(dir string, inFile io.Reader) (filename string, err error) {
  342. // Write the binary to a temporary file.
  343. outFile, err := ioutil.TempFile(dir, "syncthing")
  344. if err != nil {
  345. return "", err
  346. }
  347. _, err = io.Copy(outFile, inFile)
  348. if err != nil {
  349. os.Remove(outFile.Name())
  350. return "", err
  351. }
  352. err = outFile.Close()
  353. if err != nil {
  354. os.Remove(outFile.Name())
  355. return "", err
  356. }
  357. err = os.Chmod(outFile.Name(), os.FileMode(0755))
  358. if err != nil {
  359. os.Remove(outFile.Name())
  360. return "", err
  361. }
  362. return outFile.Name(), nil
  363. }