upgrade_supported.go 10 KB

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