upgrade_supported.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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("X-Syncthing-Version", version)
  70. return insecureHTTP.Do(req)
  71. }
  72. // FetchLatestReleases returns the latest releases, including prereleases or
  73. // not depending on the argument
  74. func FetchLatestReleases(releasesURL, version string) []Release {
  75. resp, err := insecureGet(releasesURL, version)
  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, version string) (Release, error) {
  103. rels := FetchLatestReleases(releasesURL, version)
  104. return SelectLatestRelease(version, rels)
  105. }
  106. func SelectLatestRelease(version string, rels []Release) (Release, error) {
  107. if len(rels) == 0 {
  108. return Release{}, ErrNoVersionToSelect
  109. }
  110. sort.Sort(SortByRelease(rels))
  111. // Check for a beta build
  112. beta := strings.Contains(version, "-")
  113. for _, rel := range rels {
  114. if rel.Prerelease && !beta {
  115. continue
  116. }
  117. for _, asset := range rel.Assets {
  118. assetName := path.Base(asset.Name)
  119. // Check for the architecture
  120. expectedRelease := releaseName(rel.Tag)
  121. l.Debugf("expected release asset %q", expectedRelease)
  122. l.Debugln("considering release", assetName)
  123. if strings.HasPrefix(assetName, expectedRelease) {
  124. return rel, nil
  125. }
  126. }
  127. }
  128. return Release{}, ErrNoReleaseDownload
  129. }
  130. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  131. func upgradeTo(binary string, rel Release) error {
  132. expectedRelease := releaseName(rel.Tag)
  133. l.Debugf("expected release asset %q", expectedRelease)
  134. for _, asset := range rel.Assets {
  135. assetName := path.Base(asset.Name)
  136. l.Debugln("considering release", assetName)
  137. if strings.HasPrefix(assetName, expectedRelease) {
  138. return upgradeToURL(assetName, binary, asset.URL)
  139. }
  140. }
  141. return ErrNoReleaseDownload
  142. }
  143. // Upgrade to the given release, saving the previous binary with a ".old" extension.
  144. func upgradeToURL(archiveName, binary string, url string) error {
  145. fname, err := readRelease(archiveName, filepath.Dir(binary), url)
  146. if err != nil {
  147. return err
  148. }
  149. old := binary + ".old"
  150. os.Remove(old)
  151. err = os.Rename(binary, old)
  152. if err != nil {
  153. return err
  154. }
  155. err = os.Rename(fname, binary)
  156. if err != nil {
  157. return err
  158. }
  159. return nil
  160. }
  161. func readRelease(archiveName, dir, url string) (string, error) {
  162. l.Debugf("loading %q", url)
  163. req, err := http.NewRequest("GET", url, nil)
  164. if err != nil {
  165. return "", err
  166. }
  167. req.Header.Add("Accept", "application/octet-stream")
  168. resp, err := insecureHTTP.Do(req)
  169. if err != nil {
  170. return "", err
  171. }
  172. defer resp.Body.Close()
  173. switch runtime.GOOS {
  174. case "windows":
  175. return readZip(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  176. default:
  177. return readTarGz(archiveName, dir, io.LimitReader(resp.Body, maxArchiveSize))
  178. }
  179. }
  180. func readTarGz(archiveName, dir string, r io.Reader) (string, error) {
  181. gr, err := gzip.NewReader(r)
  182. if err != nil {
  183. return "", err
  184. }
  185. tr := tar.NewReader(gr)
  186. var tempName string
  187. var sig []byte
  188. // Iterate through the files in the archive.
  189. i := 0
  190. for {
  191. if i >= maxArchiveMembers {
  192. break
  193. }
  194. i++
  195. hdr, err := tr.Next()
  196. if err == io.EOF {
  197. // end of tar archive
  198. break
  199. }
  200. if err != nil {
  201. return "", err
  202. }
  203. if hdr.Size > maxBinarySize {
  204. // We don't even want to try processing or skipping over files
  205. // that are too large.
  206. break
  207. }
  208. err = archiveFileVisitor(dir, &tempName, &sig, hdr.Name, tr)
  209. if err != nil {
  210. return "", err
  211. }
  212. if tempName != "" && sig != nil {
  213. break
  214. }
  215. }
  216. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  217. return "", err
  218. }
  219. return tempName, nil
  220. }
  221. func readZip(archiveName, dir string, r io.Reader) (string, error) {
  222. body, err := ioutil.ReadAll(r)
  223. if err != nil {
  224. return "", err
  225. }
  226. archive, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
  227. if err != nil {
  228. return "", err
  229. }
  230. var tempName string
  231. var sig []byte
  232. // Iterate through the files in the archive.
  233. i := 0
  234. for _, file := range archive.File {
  235. if i >= maxArchiveMembers {
  236. break
  237. }
  238. i++
  239. if file.UncompressedSize64 > maxBinarySize {
  240. // We don't even want to try processing or skipping over files
  241. // that are too large.
  242. break
  243. }
  244. inFile, err := file.Open()
  245. if err != nil {
  246. return "", err
  247. }
  248. err = archiveFileVisitor(dir, &tempName, &sig, file.Name, inFile)
  249. inFile.Close()
  250. if err != nil {
  251. return "", err
  252. }
  253. if tempName != "" && sig != nil {
  254. break
  255. }
  256. }
  257. if err := verifyUpgrade(archiveName, tempName, sig); err != nil {
  258. return "", err
  259. }
  260. return tempName, nil
  261. }
  262. // archiveFileVisitor is called for each file in an archive. It may set
  263. // tempFile and signature.
  264. func archiveFileVisitor(dir string, tempFile *string, signature *[]byte, archivePath string, filedata io.Reader) error {
  265. var err error
  266. filename := path.Base(archivePath)
  267. archiveDir := path.Dir(archivePath)
  268. l.Debugf("considering file %s", archivePath)
  269. switch filename {
  270. case "syncthing", "syncthing.exe":
  271. archiveDirs := strings.Split(archiveDir, "/")
  272. if len(archiveDirs) > 1 {
  273. // Don't consider "syncthing" files found too deeply, as they may be
  274. // other things.
  275. return nil
  276. }
  277. l.Debugf("found upgrade binary %s", archivePath)
  278. *tempFile, err = writeBinary(dir, io.LimitReader(filedata, maxBinarySize))
  279. if err != nil {
  280. return err
  281. }
  282. case "release.sig":
  283. l.Debugf("found signature %s", archivePath)
  284. *signature, err = ioutil.ReadAll(io.LimitReader(filedata, maxSignatureSize))
  285. if err != nil {
  286. return err
  287. }
  288. }
  289. return nil
  290. }
  291. func verifyUpgrade(archiveName, tempName string, sig []byte) error {
  292. if tempName == "" {
  293. return fmt.Errorf("no upgrade found")
  294. }
  295. if sig == nil {
  296. return fmt.Errorf("no signature found")
  297. }
  298. l.Debugf("checking signature\n%s", sig)
  299. fd, err := os.Open(tempName)
  300. if err != nil {
  301. return err
  302. }
  303. // Create a new reader that will serve reads from, in order:
  304. //
  305. // - the archive name ("syncthing-linux-amd64-v0.13.0-beta.4.tar.gz")
  306. // followed by a newline
  307. //
  308. // - the temp file contents
  309. //
  310. // We then verify the release signature against the contents of this
  311. // multireader. This ensures that it is not only a bonafide syncthing
  312. // binary, but it it also of exactly the platform and version we expect.
  313. mr := io.MultiReader(bytes.NewBufferString(archiveName+"\n"), fd)
  314. err = signature.Verify(SigningKey, sig, mr)
  315. fd.Close()
  316. if err != nil {
  317. os.Remove(tempName)
  318. return err
  319. }
  320. return nil
  321. }
  322. func writeBinary(dir string, inFile io.Reader) (filename string, err error) {
  323. // Write the binary to a temporary file.
  324. outFile, err := ioutil.TempFile(dir, "syncthing")
  325. if err != nil {
  326. return "", err
  327. }
  328. _, err = io.Copy(outFile, inFile)
  329. if err != nil {
  330. os.Remove(outFile.Name())
  331. return "", err
  332. }
  333. err = outFile.Close()
  334. if err != nil {
  335. os.Remove(outFile.Name())
  336. return "", err
  337. }
  338. err = os.Chmod(outFile.Name(), os.FileMode(0755))
  339. if err != nil {
  340. os.Remove(outFile.Name())
  341. return "", err
  342. }
  343. return outFile.Name(), nil
  344. }