pax_global_header00006660000000000000000000000064127144406130014514gustar00rootroot0000000000000052 comment=83bda8e8f5c478583525c4d2c9a5b40e4654b1e9 golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/000077500000000000000000000000001271444061300244105ustar00rootroot00000000000000golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/LICENSE000066400000000000000000000010471271444061300254170ustar00rootroot00000000000000Copyright 2015 Alan Shreve Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/README.md000066400000000000000000000044371271444061300256770ustar00rootroot00000000000000# go-update: Build self-updating Go programs [![godoc reference](https://godoc.org/github.com/inconshreveable/go-update?status.png)](https://godoc.org/github.com/inconshreveable/go-update) Package update provides functionality to implement secure, self-updating Go programs (or other single-file targets) A program can update itself by replacing its executable file with a new version. It provides the flexibility to implement different updating user experiences like auto-updating, or manual user-initiated updates. It also boasts advanced features like binary patching and code signing verification. Example of updating from a URL: ```go import ( "fmt" "net/http" "github.com/inconshreveable/go-update" ) func doUpdate(url string) error { resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() err := update.Apply(resp.Body, update.Options{}) if err != nil { // error handling } return err } ``` ## Features - Cross platform support (Windows too!) - Binary patch application - Checksum verification - Code signing verification - Support for updating arbitrary files ## [equinox.io](https://equinox.io) [equinox.io](https://equinox.io) is a complete ready-to-go updating solution built on top of go-update that provides: - Hosted updates - Update channels (stable, beta, nightly, ...) - Dynamically computed binary diffs - Automatic key generation and code - Release tooling with proper code signing - Update/download metrics ## API Compatibility Promises The master branch of `go-update` is *not* guaranteed to have a stable API over time. For any production application, you should vendor your dependency on `go-update` with a tool like git submodules, [gb](http://getgb.io/) or [govendor](https://github.com/kardianos/govendor). The `go-update` package makes the following promises about API compatibility: 1. A list of all API-breaking changes will be documented in this README. 1. `go-update` will strive for as few API-breaking changes as possible. ## API Breaking Changes - **Sept 3, 2015**: The `Options` struct passed to `Apply` was changed to be passed by value instead of passed by pointer. Old API at `28de026`. - **Aug 9, 2015**: 2.0 API. Old API at `221d034` or `gopkg.in/inconshreveable/go-update.v0`. ## License Apache golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/apply.go000066400000000000000000000221201271444061300260610ustar00rootroot00000000000000package update import ( "bytes" "crypto" "crypto/x509" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "github.com/kardianos/osext" ) var ( openFile = os.OpenFile ) // Apply performs an update of the current executable (or opts.TargetFile, if set) with the contents of the given io.Reader. // // Apply performs the following actions to ensure a safe cross-platform update: // // 1. If configured, applies the contents of the update io.Reader as a binary patch. // // 2. If configured, computes the checksum of the new executable and verifies it matches. // // 3. If configured, verifies the signature with a public key. // // 4. Creates a new file, /path/to/.target.new with the TargetMode with the contents of the updated file // // 5. Renames /path/to/target to /path/to/.target.old // // 6. Renames /path/to/.target.new to /path/to/target // // 7. If the final rename is successful, deletes /path/to/.target.old, returns no error. On Windows, // the removal of /path/to/target.old always fails, so instead Apply hides the old file instead. // // 8. If the final rename fails, attempts to roll back by renaming /path/to/.target.old // back to /path/to/target. // // If the roll back operation fails, the file system is left in an inconsistent state (betweet steps 5 and 6) where // there is no new executable file and the old executable file could not be be moved to its original location. In this // case you should notify the user of the bad news and ask them to recover manually. Applications can determine whether // the rollback failed by calling RollbackError, see the documentation on that function for additional detail. func Apply(update io.Reader, opts Options) error { // validate verify := false switch { case opts.Signature != nil && opts.PublicKey != nil: // okay verify = true case opts.Signature != nil: return errors.New("no public key to verify signature with") case opts.PublicKey != nil: return errors.New("No signature to verify with") } // set defaults if opts.Hash == 0 { opts.Hash = crypto.SHA256 } if opts.Verifier == nil { opts.Verifier = NewECDSAVerifier() } if opts.TargetMode == 0 { opts.TargetMode = 0755 } // get target path var err error opts.TargetPath, err = opts.getPath() if err != nil { return err } var newBytes []byte if opts.Patcher != nil { if newBytes, err = opts.applyPatch(update); err != nil { return err } } else { // no patch to apply, go on through if newBytes, err = ioutil.ReadAll(update); err != nil { return err } } // verify checksum if requested if opts.Checksum != nil { if err = opts.verifyChecksum(newBytes); err != nil { return err } } if verify { if err = opts.verifySignature(newBytes); err != nil { return err } } // get the directory the executable exists in updateDir := filepath.Dir(opts.TargetPath) filename := filepath.Base(opts.TargetPath) // Copy the contents of newbinary to a new executable file newPath := filepath.Join(updateDir, fmt.Sprintf(".%s.new", filename)) fp, err := openFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, opts.TargetMode) if err != nil { return err } defer fp.Close() _, err = io.Copy(fp, bytes.NewReader(newBytes)) if err != nil { return err } // if we don't call fp.Close(), windows won't let us move the new executable // because the file will still be "in use" fp.Close() // this is where we'll move the executable to so that we can swap in the updated replacement oldPath := opts.OldSavePath removeOld := opts.OldSavePath == "" if removeOld { oldPath = filepath.Join(updateDir, fmt.Sprintf(".%s.old", filename)) } // delete any existing old exec file - this is necessary on Windows for two reasons: // 1. after a successful update, Windows can't remove the .old file because the process is still running // 2. windows rename operations fail if the destination file already exists _ = os.Remove(oldPath) // move the existing executable to a new file in the same directory err = os.Rename(opts.TargetPath, oldPath) if err != nil { return err } // move the new exectuable in to become the new program err = os.Rename(newPath, opts.TargetPath) if err != nil { // move unsuccessful // // The filesystem is now in a bad state. We have successfully // moved the existing binary to a new location, but we couldn't move the new // binary to take its place. That means there is no file where the current executable binary // used to be! // Try to rollback by restoring the old binary to its original path. rerr := os.Rename(oldPath, opts.TargetPath) if rerr != nil { return &rollbackErr{err, rerr} } return err } // move successful, remove the old binary if needed if removeOld { errRemove := os.Remove(oldPath) // windows has trouble with removing old binaries, so hide it instead if errRemove != nil { _ = hideFile(oldPath) } } return nil } // RollbackError takes an error value returned by Apply and returns the error, if any, // that occurred when attempting to roll back from a failed update. Applications should // always call this function on any non-nil errors returned by Apply. // // If no rollback was needed or if the rollback was successful, RollbackError returns nil, // otherwise it returns the error encountered when trying to roll back. func RollbackError(err error) error { if err == nil { return nil } if rerr, ok := err.(*rollbackErr); ok { return rerr.rollbackErr } return nil } type rollbackErr struct { error // original error rollbackErr error // error encountered while rolling back } type Options struct { // TargetPath defines the path to the file to update. // The emptry string means 'the executable file of the running program'. TargetPath string // Create TargetPath replacement with this file mode. If zero, defaults to 0755. TargetMode os.FileMode // Checksum of the new binary to verify against. If nil, no checksum or signature verification is done. Checksum []byte // Public key to use for signature verification. If nil, no signature verification is done. PublicKey crypto.PublicKey // Signature to verify the updated file. If nil, no signature verification is done. Signature []byte // Pluggable signature verification algorithm. If nil, ECDSA is used. Verifier Verifier // Use this hash function to generate the checksum. If not set, SHA256 is used. Hash crypto.Hash // If nil, treat the update as a complete replacement for the contents of the file at TargetPath. // If non-nil, treat the update contents as a patch and use this object to apply the patch. Patcher Patcher // Store the old executable file at this path after a successful update. // The empty string means the old executable file will be removed after the update. OldSavePath string } // CheckPermissions determines whether the process has the correct permissions to // perform the requested update. If the update can proceed, it returns nil, otherwise // it returns the error that would occur if an update were attempted. func (o *Options) CheckPermissions() error { // get the directory the file exists in path, err := o.getPath() if err != nil { return err } fileDir := filepath.Dir(path) fileName := filepath.Base(path) // attempt to open a file in the file's directory newPath := filepath.Join(fileDir, fmt.Sprintf(".%s.new", fileName)) fp, err := openFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, o.TargetMode) if err != nil { return err } fp.Close() _ = os.Remove(newPath) return nil } // SetPublicKeyPEM is a convenience method to set the PublicKey property // used for checking a completed update's signature by parsing a // Public Key formatted as PEM data. func (o *Options) SetPublicKeyPEM(pembytes []byte) error { block, _ := pem.Decode(pembytes) if block == nil { return errors.New("couldn't parse PEM data") } pub, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return err } o.PublicKey = pub return nil } func (o *Options) getPath() (string, error) { if o.TargetPath == "" { return osext.Executable() } else { return o.TargetPath, nil } } func (o *Options) applyPatch(patch io.Reader) ([]byte, error) { // open the file to patch old, err := os.Open(o.TargetPath) if err != nil { return nil, err } defer old.Close() // apply the patch var applied bytes.Buffer if err = o.Patcher.Patch(old, &applied, patch); err != nil { return nil, err } return applied.Bytes(), nil } func (o *Options) verifyChecksum(updated []byte) error { checksum, err := checksumFor(o.Hash, updated) if err != nil { return err } if !bytes.Equal(o.Checksum, checksum) { return fmt.Errorf("Updated file has wrong checksum. Expected: %x, got: %x", o.Checksum, checksum) } return nil } func (o *Options) verifySignature(updated []byte) error { checksum, err := checksumFor(o.Hash, updated) if err != nil { return err } return o.Verifier.VerifySignature(checksum, o.Signature, o.Hash, o.PublicKey) } func checksumFor(h crypto.Hash, payload []byte) ([]byte, error) { if !h.Available() { return nil, errors.New("requested hash function not available") } hash := h.New() hash.Write(payload) // guaranteed not to error return hash.Sum([]byte{}), nil } golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/apply_test.go000066400000000000000000000262761271444061300271400ustar00rootroot00000000000000package update import ( "bytes" "crypto" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" "os" "testing" "github.com/kr/binarydist" ) var ( oldFile = []byte{0xDE, 0xAD, 0xBE, 0xEF} newFile = []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06} newFileChecksum = sha256.Sum256(newFile) ) func cleanup(path string) { os.Remove(path) os.Remove(fmt.Sprintf(".%s.new", path)) } // we write with a separate name for each test so that we can run them in parallel func writeOldFile(path string, t *testing.T) { if err := ioutil.WriteFile(path, oldFile, 0777); err != nil { t.Fatalf("Failed to write file for testing preparation: %v", err) } } func validateUpdate(path string, err error, t *testing.T) { if err != nil { t.Fatalf("Failed to update: %v", err) } buf, err := ioutil.ReadFile(path) if err != nil { t.Fatalf("Failed to read file post-update: %v", err) } if !bytes.Equal(buf, newFile) { t.Fatalf("File was not updated! Bytes read: %v, Bytes expected: %v", buf, newFile) } } func TestApplySimple(t *testing.T) { fName := "TestApplySimple" defer cleanup(fName) writeOldFile(fName, t) err := Apply(bytes.NewReader(newFile), Options{ TargetPath: fName, }) validateUpdate(fName, err, t) } func TestApplyOldSavePath(t *testing.T) { fName := "TestApplyOldSavePath" defer cleanup(fName) writeOldFile(fName, t) oldfName := "OldSavePath" err := Apply(bytes.NewReader(newFile), Options{ TargetPath: fName, OldSavePath: oldfName, }) validateUpdate(fName, err, t) if _, err := os.Stat(oldfName); os.IsNotExist(err) { t.Fatalf("Failed to find the old file: %v", err) } cleanup(oldfName) } func TestVerifyChecksum(t *testing.T) { fName := "TestVerifyChecksum" defer cleanup(fName) writeOldFile(fName, t) err := Apply(bytes.NewReader(newFile), Options{ TargetPath: fName, Checksum: newFileChecksum[:], }) validateUpdate(fName, err, t) } func TestVerifyChecksumNegative(t *testing.T) { fName := "TestVerifyChecksumNegative" defer cleanup(fName) writeOldFile(fName, t) badChecksum := []byte{0x0A, 0x0B, 0x0C, 0xFF} err := Apply(bytes.NewReader(newFile), Options{ TargetPath: fName, Checksum: badChecksum, }) if err == nil { t.Fatalf("Failed to detect bad checksum!") } } func TestApplyPatch(t *testing.T) { fName := "TestApplyPatch" defer cleanup(fName) writeOldFile(fName, t) patch := new(bytes.Buffer) err := binarydist.Diff(bytes.NewReader(oldFile), bytes.NewReader(newFile), patch) if err != nil { t.Fatalf("Failed to create patch: %v", err) } err = Apply(patch, Options{ TargetPath: fName, Patcher: NewBSDiffPatcher(), }) validateUpdate(fName, err, t) } func TestCorruptPatch(t *testing.T) { fName := "TestCorruptPatch" defer cleanup(fName) writeOldFile(fName, t) badPatch := []byte{0x44, 0x38, 0x86, 0x3c, 0x4f, 0x8d, 0x26, 0x54, 0xb, 0x11, 0xce, 0xfe, 0xc1, 0xc0, 0xf8, 0x31, 0x38, 0xa0, 0x12, 0x1a, 0xa2, 0x57, 0x2a, 0xe1, 0x3a, 0x48, 0x62, 0x40, 0x2b, 0x81, 0x12, 0xb1, 0x21, 0xa5, 0x16, 0xed, 0x73, 0xd6, 0x54, 0x84, 0x29, 0xa6, 0xd6, 0xb2, 0x1b, 0xfb, 0xe6, 0xbe, 0x7b, 0x70} err := Apply(bytes.NewReader(badPatch), Options{ TargetPath: fName, Patcher: NewBSDiffPatcher(), }) if err == nil { t.Fatalf("Failed to detect corrupt patch!") } } func TestVerifyChecksumPatchNegative(t *testing.T) { fName := "TestVerifyChecksumPatchNegative" defer cleanup(fName) writeOldFile(fName, t) patch := new(bytes.Buffer) anotherFile := []byte{0x77, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66} err := binarydist.Diff(bytes.NewReader(oldFile), bytes.NewReader(anotherFile), patch) if err != nil { t.Fatalf("Failed to create patch: %v", err) } err = Apply(patch, Options{ TargetPath: fName, Checksum: newFileChecksum[:], Patcher: NewBSDiffPatcher(), }) if err == nil { t.Fatalf("Failed to detect patch to wrong file!") } } const ecdsaPublicKey = ` -----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEL8ThbSyEucsCxnd4dCZR2hIy5nea54ko O+jUUfIjkvwhCWzASm0lpCVdVpXKZXIe+NZ+44RQRv3+OqJkCCGzUgJkPNI3lxdG 9zu8rbrnxISV06VQ8No7Ei9wiTpqmTBB -----END PUBLIC KEY----- ` const ecdsaPrivateKey = ` -----BEGIN EC PRIVATE KEY----- MIGkAgEBBDBttCB/1NOY4T+WrG4FSV49Ayn3gK1DNzfGaJ01JUXeiNFCWQM2pqpU om8ATPP/dkegBwYFK4EEACKhZANiAAQvxOFtLIS5ywLGd3h0JlHaEjLmd5rniSg7 6NRR8iOS/CEJbMBKbSWkJV1Wlcplch741n7jhFBG/f46omQIIbNSAmQ80jeXF0b3 O7ytuufEhJXTpVDw2jsSL3CJOmqZMEE= -----END EC PRIVATE KEY----- ` const rsaPublicKey = ` -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxSWmu7trWKAwDFjiCN2D Tk2jj2sgcr/CMlI4cSSiIOHrXCFxP1I8i9PvQkd4hasXQrLbT5WXKrRGv1HKUKab b9ead+kD0kxk7i2bFYvKX43oq66IW0mOLTQBO7I9UyT4L7svcMD+HUQ2BqHoaQe4 y20C59dPr9Dpcz8DZkdLsBV6YKF6Ieb3iGk8oRLMWNaUqPa8f1BGgxAkvPHcqDjT x4xRnjgTRRRlZvRtALHMUkIChgxDOhoEzKpGiqnX7HtMJfrhV6h0PAXNA4h9Kjv5 5fhJ08Rz7mmZmtH5JxTK5XTquo59sihSajR4bSjZbbkQ1uLkeFlY3eli3xdQ7Nrf fQIDAQAB -----END PUBLIC KEY-----` const rsaPrivateKey = ` -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAxSWmu7trWKAwDFjiCN2DTk2jj2sgcr/CMlI4cSSiIOHrXCFx P1I8i9PvQkd4hasXQrLbT5WXKrRGv1HKUKabb9ead+kD0kxk7i2bFYvKX43oq66I W0mOLTQBO7I9UyT4L7svcMD+HUQ2BqHoaQe4y20C59dPr9Dpcz8DZkdLsBV6YKF6 Ieb3iGk8oRLMWNaUqPa8f1BGgxAkvPHcqDjTx4xRnjgTRRRlZvRtALHMUkIChgxD OhoEzKpGiqnX7HtMJfrhV6h0PAXNA4h9Kjv55fhJ08Rz7mmZmtH5JxTK5XTquo59 sihSajR4bSjZbbkQ1uLkeFlY3eli3xdQ7NrffQIDAQABAoIBAAkN+6RvrTR61voa Mvd5RQiZpEN4Bht/Fyo8gH8h0Zh1B9xJZOwlmMZLS5fdtHlfLEhR8qSrGDBL61vq I8KkhEsUufF78EL+YzxVN+Q7cWYGHIOWFokqza7hzpSxUQO6lPOMQ1eIZaNueJTB Zu07/47ISPPg/bXzgGVcpYlTCPTjUwKjtfyMqvX9AD7fIyYRm6zfE7EHj1J2sBFt Yz1OGELg6HfJwXfpnPfBvftD0hWGzJ78Bp71fPJe6n5gnqmSqRvrcXNWFnH/yqkN d6vPIxD6Z3LjvyZpkA7JillLva2L/zcIFhg4HZvQnWd8/PpDnUDonu36hcj4SC5j W4aVPLkCgYEA4XzNKWxqYcajzFGZeSxlRHupSAl2MT7Cc5085MmE7dd31wK2T8O4 n7N4bkm/rjTbX85NsfWdKtWb6mpp8W3VlLP0rp4a/12OicVOkg4pv9LZDmY0sRlE YuDJk1FeCZ50UrwTZI3rZ9IhZHhkgVA6uWAs7tYndONkxNHG0pjqs4sCgYEA39MZ JwMqo3qsPntpgP940cCLflEsjS9hYNO3+Sv8Dq3P0HLVhBYajJnotf8VuU0fsQZG grmtVn1yThFbMq7X1oY4F0XBA+paSiU18c4YyUnwax2u4sw9U/Q9tmQUZad5+ueT qriMBwGv+ewO+nQxqvAsMUmemrVzrfwA5Oct+hcCgYAfiyXoNZJsOy2O15twqBVC j0oPGcO+/9iT89sg5lACNbI+EdMPNYIOVTzzsL1v0VUfAe08h++Enn1BPcG0VHkc ZFBGXTfJoXzfKQrkw7ZzbzuOGB4m6DH44xlP0oIlNlVvfX/5ASF9VJf3RiBJNsAA TsP6ZVr/rw/ZuL7nlxy+IQKBgDhL/HOXlE3yOQiuOec8WsNHTs7C1BXe6PtVxVxi 988pYK/pclL6zEq5G5NLSceF4obAMVQIJ9UtUGbabrncyGUo9UrFPLsjYvprSZo8 YHegpVwL50UcYgCP2kXZ/ldjPIcjYDz8lhvdDMor2cidGTEJn9P11HLNWP9V91Ob 4jCZAoGAPNRSC5cC8iP/9j+s2/kdkfWJiNaolPYAUrmrkL6H39PYYZM5tnhaIYJV Oh9AgABamU0eb3p3vXTISClVgV7ifq1HyZ7BSUhMfaY2Jk/s3sUHCWFxPZe9sgEG KinIY/373KIkIV/5g4h2v1w330IWcfptxKcY/Er3DJr38f695GE= -----END RSA PRIVATE KEY-----` func signec(privatePEM string, source []byte, t *testing.T) []byte { parseFn := func(p []byte) (crypto.Signer, error) { return x509.ParseECPrivateKey(p) } return sign(parseFn, privatePEM, source, t) } func signrsa(privatePEM string, source []byte, t *testing.T) []byte { parseFn := func(p []byte) (crypto.Signer, error) { return x509.ParsePKCS1PrivateKey(p) } return sign(parseFn, privatePEM, source, t) } func sign(parsePrivKey func([]byte) (crypto.Signer, error), privatePEM string, source []byte, t *testing.T) []byte { block, _ := pem.Decode([]byte(privatePEM)) if block == nil { t.Fatalf("Failed to parse private key PEM") } priv, err := parsePrivKey(block.Bytes) if err != nil { t.Fatalf("Failed to parse private key DER: %v", err) } checksum := sha256.Sum256(source) sig, err := priv.Sign(rand.Reader, checksum[:], crypto.SHA256) if err != nil { t.Fatalf("Failed to sign: %v", sig) } return sig } func TestVerifyECSignature(t *testing.T) { fName := "TestVerifyECSignature" defer cleanup(fName) writeOldFile(fName, t) opts := Options{TargetPath: fName} err := opts.SetPublicKeyPEM([]byte(ecdsaPublicKey)) if err != nil { t.Fatalf("Could not parse public key: %v", err) } opts.Signature = signec(ecdsaPrivateKey, newFile, t) err = Apply(bytes.NewReader(newFile), opts) validateUpdate(fName, err, t) } func TestVerifyRSASignature(t *testing.T) { fName := "TestVerifyRSASignature" defer cleanup(fName) writeOldFile(fName, t) opts := Options{ TargetPath: fName, Verifier: NewRSAVerifier(), } err := opts.SetPublicKeyPEM([]byte(rsaPublicKey)) if err != nil { t.Fatalf("Could not parse public key: %v", err) } opts.Signature = signrsa(rsaPrivateKey, newFile, t) err = Apply(bytes.NewReader(newFile), opts) validateUpdate(fName, err, t) } func TestVerifyFailBadSignature(t *testing.T) { fName := "TestVerifyFailBadSignature" defer cleanup(fName) writeOldFile(fName, t) opts := Options{ TargetPath: fName, Signature: []byte{0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA}, } err := opts.SetPublicKeyPEM([]byte(ecdsaPublicKey)) if err != nil { t.Fatalf("Could not parse public key: %v", err) } err = Apply(bytes.NewReader(newFile), opts) if err == nil { t.Fatalf("Did not fail with bad signature") } } func TestVerifyFailNoSignature(t *testing.T) { fName := "TestVerifySignatureWithPEM" defer cleanup(fName) writeOldFile(fName, t) opts := Options{TargetPath: fName} err := opts.SetPublicKeyPEM([]byte(ecdsaPublicKey)) if err != nil { t.Fatalf("Could not parse public key: %v", err) } err = Apply(bytes.NewReader(newFile), opts) if err == nil { t.Fatalf("Did not fail with empty signature") } } const wrongKey = ` -----BEGIN EC PRIVATE KEY----- MIGkAgEBBDBzqYp6N2s8YWYifBjS03/fFfmGeIPcxQEi+bbFeekIYt8NIKIkhD+r hpaIwSmot+qgBwYFK4EEACKhZANiAAR0EC8Usbkc4k30frfEB2ECmsIghu9DJSqE RbH7jfq2ULNv8tN/clRjxf2YXgp+iP3SQF1R1EYERKpWr8I57pgfIZtoZXjwpbQC VBbP/Ff+05HOqwPC7rJMy1VAJLKg7Cw= -----END EC PRIVATE KEY----- ` func TestVerifyFailWrongSignature(t *testing.T) { fName := "TestVerifyFailWrongSignature" defer cleanup(fName) writeOldFile(fName, t) opts := Options{TargetPath: fName} err := opts.SetPublicKeyPEM([]byte(ecdsaPublicKey)) if err != nil { t.Fatalf("Could not parse public key: %v", err) } opts.Signature = signec(wrongKey, newFile, t) err = Apply(bytes.NewReader(newFile), opts) if err == nil { t.Fatalf("Verified an update that was signed by an untrusted key!") } } func TestSignatureButNoPublicKey(t *testing.T) { fName := "TestSignatureButNoPublicKey" defer cleanup(fName) writeOldFile(fName, t) err := Apply(bytes.NewReader(newFile), Options{ TargetPath: fName, Signature: signec(ecdsaPrivateKey, newFile, t), }) if err == nil { t.Fatalf("Allowed an update with a signautre verification when no public key was specified!") } } func TestPublicKeyButNoSignature(t *testing.T) { fName := "TestPublicKeyButNoSignature" defer cleanup(fName) writeOldFile(fName, t) opts := Options{TargetPath: fName} if err := opts.SetPublicKeyPEM([]byte(ecdsaPublicKey)); err != nil { t.Fatalf("Could not parse public key: %v", err) } err := Apply(bytes.NewReader(newFile), opts) if err == nil { t.Fatalf("Allowed an update with no signautre when a public key was specified!") } } func TestWriteError(t *testing.T) { fName := "TestWriteError" defer cleanup(fName) writeOldFile(fName, t) openFile = func(name string, flags int, perm os.FileMode) (*os.File, error) { f, err := os.OpenFile(name, flags, perm) // simulate Write() error by closing the file prematurely f.Close() return f, err } defer func() { openFile = os.OpenFile }() err := Apply(bytes.NewReader(newFile), Options{TargetPath: fName}) if err == nil { t.Fatalf("Allowed an update to an empty file") } } golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/doc.go000066400000000000000000000121631271444061300255070ustar00rootroot00000000000000/* Package update provides functionality to implement secure, self-updating Go programs (or other single-file targets). For complete updating solutions please see Equinox (https://equinox.io) and go-tuf (https://github.com/flynn/go-tuf). Basic Example This example shows how to update a program remotely from a URL. import ( "fmt" "net/http" "github.com/inconshreveable/go-update" ) func doUpdate(url string) error { // request the new file resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() err := update.Apply(resp.Body, update.Options{}) if err != nil { if rerr := update.RollbackError(err); rerr != nil { fmt.Println("Failed to rollback from bad update: %v", rerr) } } return err } Binary Patching Go binaries can often be large. It can be advantageous to only ship a binary patch to a client instead of the complete program text of a new version. This example shows how to update a program with a bsdiff binary patch. Other patch formats may be applied by implementing the Patcher interface. import ( "encoding/hex" "io" "github.com/inconshreveable/go-update" ) func updateWithPatch(patch io.Reader) error { err := update.Apply(patch, update.Options{ Patcher: update.NewBSDiffPatcher() }) if err != nil { // error handling } return err } Checksum Verification Updating executable code on a computer can be a dangerous operation unless you take the appropriate steps to guarantee the authenticity of the new code. While checksum verification is important, it should always be combined with signature verification (next section) to guarantee that the code came from a trusted party. go-update validates SHA256 checksums by default, but this is pluggable via the Hash property on the Options struct. This example shows how to guarantee that the newly-updated binary is verified to have an appropriate checksum (that was otherwise retrived via a secure channel) specified as a hex string. import ( "crypto" _ "crypto/sha256" "encoding/hex" "io" "github.com/inconshreveable/go-update" ) func updateWithChecksum(binary io.Reader, hexChecksum string) error { checksum, err := hex.DecodeString(hexChecksum) if err != nil { return err } err = update.Apply(binary, update.Options{ Hash: crypto.SHA256, // this is the default, you don't need to specify it Checksum: checksum, }) if err != nil { // error handling } return err } Cryptographic Signature Verification Cryptographic verification of new code from an update is an extremely important way to guarantee the security and integrity of your updates. Verification is performed by validating the signature of a hash of the new file. This means nothing changes if you apply your update with a patch. This example shows how to add signature verification to your updates. To make all of this work an application distributor must first create a public/private key pair and embed the public key into their application. When they issue a new release, the issuer must sign the new executable file with the private key and distribute the signature along with the update. import ( "crypto" _ "crypto/sha256" "encoding/hex" "io" "github.com/inconshreveable/go-update" ) var publicKey = []byte(` -----BEGIN PUBLIC KEY----- MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEtrVmBxQvheRArXjg2vG1xIprWGuCyESx MMY8pjmjepSy2kuz+nl9aFLqmr+rDNdYvEBqQaZrYMc6k29gjvoQnQ== -----END PUBLIC KEY----- `) func verifiedUpdate(binary io.Reader, hexChecksum, hexSignature string) { checksum, err := hex.DecodeString(hexChecksum) if err != nil { return err } signature, err := hex.DecodeString(hexSignature) if err != nil { return err } opts := update.Options{ Checksum: checksum, Signature: signature, Hash: crypto.SHA256, // this is the default, you don't need to specify it Verifier: update.NewECDSAVerifier(), // this is the default, you don't need to specify it } err = opts.SetPublicKeyPEM(publicKey) if err != nil { return err } err = update.Apply(binary, opts) if err != nil { // error handling } return err } Building Single-File Go Binaries In order to update a Go application with go-update, you must distributed it as a single executable. This is often easy, but some applications require static assets (like HTML and CSS asset files or TLS certificates). In order to update applications like these, you'll want to make sure to embed those asset files into the distributed binary with a tool like go-bindata (my favorite): https://github.com/jteeuwen/go-bindata Non-Goals Mechanisms and protocols for determining whether an update should be applied and, if so, which one are out of scope for this package. Please consult go-tuf (https://github.com/flynn/go-tuf) or Equinox (https://equinox.io) for more complete solutions. go-update only works for self-updating applications that are distributed as a single binary, i.e. applications that do not have additional assets or dependency files. Updating application that are distributed as mutliple on-disk files is out of scope, although this may change in future versions of this library. */ package update golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/hide_noop.go000066400000000000000000000001251271444061300267010ustar00rootroot00000000000000// +build !windows package update func hideFile(path string) error { return nil } golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/hide_windows.go000066400000000000000000000005341271444061300274240ustar00rootroot00000000000000package update import ( "syscall" "unsafe" ) func hideFile(path string) error { kernel32 := syscall.NewLazyDLL("kernel32.dll") setFileAttributes := kernel32.NewProc("SetFileAttributesW") r1, _, err := setFileAttributes.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))), 2) if r1 == 0 { return err } else { return nil } } golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/patcher.go000066400000000000000000000011661271444061300263710ustar00rootroot00000000000000package update import ( "io" "github.com/kr/binarydist" ) // Patcher defines an interface for applying binary patches to an old item to get an updated item. type Patcher interface { Patch(old io.Reader, new io.Writer, patch io.Reader) error } type patchFn func(io.Reader, io.Writer, io.Reader) error func (fn patchFn) Patch(old io.Reader, new io.Writer, patch io.Reader) error { return fn(old, new, patch) } // NewBSDifferPatcher returns a new Patcher that applies binary patches using // the bsdiff algorithm. See http://www.daemonology.net/bsdiff/ func NewBSDiffPatcher() Patcher { return patchFn(binarydist.Patch) } golang-github-inconshreveable-go-update-0.0~git20160112.0.8152e7e+ds/verifier.go000066400000000000000000000041171271444061300265550ustar00rootroot00000000000000package update import ( "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/rsa" "encoding/asn1" "errors" "math/big" ) // Verifier defines an interface for verfiying an update's signature with a public key. type Verifier interface { VerifySignature(checksum, signature []byte, h crypto.Hash, publicKey crypto.PublicKey) error } type verifyFn func([]byte, []byte, crypto.Hash, crypto.PublicKey) error func (fn verifyFn) VerifySignature(checksum []byte, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error { return fn(checksum, signature, hash, publicKey) } // NewRSAVerifier returns a Verifier that uses the RSA algorithm to verify updates. func NewRSAVerifier() Verifier { return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error { key, ok := publicKey.(*rsa.PublicKey) if !ok { return errors.New("not a valid RSA public key") } return rsa.VerifyPKCS1v15(key, hash, checksum, signature) }) } type rsDER struct { R *big.Int S *big.Int } // NewECDSAVerifier returns a Verifier that uses the ECDSA algorithm to verify updates. func NewECDSAVerifier() Verifier { return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error { key, ok := publicKey.(*ecdsa.PublicKey) if !ok { return errors.New("not a valid ECDSA public key") } var rs rsDER if _, err := asn1.Unmarshal(signature, &rs); err != nil { return err } if !ecdsa.Verify(key, checksum, rs.R, rs.S) { return errors.New("failed to verify ecsda signature") } return nil }) } // NewDSAVerifier returns a Verifier that uses the DSA algorithm to verify updates. func NewDSAVerifier() Verifier { return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error { key, ok := publicKey.(*dsa.PublicKey) if !ok { return errors.New("not a valid DSA public key") } var rs rsDER if _, err := asn1.Unmarshal(signature, &rs); err != nil { return err } if !dsa.Verify(key, checksum, rs.R, rs.S) { return errors.New("failed to verify ecsda signature") } return nil }) }