diff options
| author | Christine Dodrill <me@christine.website> | 2018-10-05 14:30:43 -0700 |
|---|---|---|
| committer | Christine Dodrill <me@christine.website> | 2018-10-05 14:31:22 -0700 |
| commit | a37fe34bc17f2f3d122da6b121ed83ef8ee7b0fa (patch) | |
| tree | ac3be2cf3f091ec3cec4aa247f1b9cb264c1bee5 /vendor/github.com | |
| parent | 2c85a708989624df6bb9eca0a77ceeda8cf05f28 (diff) | |
| download | x-a37fe34bc17f2f3d122da6b121ed83ef8ee7b0fa.tar.xz x-a37fe34bc17f2f3d122da6b121ed83ef8ee7b0fa.zip | |
automate xena/xperimental build
Diffstat (limited to 'vendor/github.com')
24 files changed, 0 insertions, 2215 deletions
diff --git a/vendor/github.com/GeertJohan/yubigo/.gitignore b/vendor/github.com/GeertJohan/yubigo/.gitignore deleted file mode 100644 index e6d7d4e..0000000 --- a/vendor/github.com/GeertJohan/yubigo/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/yubigo -/yubigo.sublime-project -/yubigo.sublime-workspace -/test -.apikey
\ No newline at end of file diff --git a/vendor/github.com/GeertJohan/yubigo/LICENSE b/vendor/github.com/GeertJohan/yubigo/LICENSE deleted file mode 100644 index cb489ee..0000000 --- a/vendor/github.com/GeertJohan/yubigo/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012, Geert-Johan Riemer -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/GeertJohan/yubigo/readme.md b/vendor/github.com/GeertJohan/yubigo/readme.md deleted file mode 100644 index 73b2f7e..0000000 --- a/vendor/github.com/GeertJohan/yubigo/readme.md +++ /dev/null @@ -1,84 +0,0 @@ - -## yubigo - -Yubigo is a Yubikey client API library that provides an easy way to integrate the Yubikey into any Go application. - -## Installation - -Installation is simple. Use go get: -`go get github.com/GeertJohan/yubigo` - -## Usage - -Make sure to import the library: `import "github.com/GeertJohan/yubigo"` - -For use with the default Yubico servers, make sure you have an API key. [Request a key][getapikey]. - -**Basic OTP checking usage:** -```go - -// create a new yubiAuth instance with id and key -yubiAuth, err := yubigo.NewYubiAuth("1234", "fdsaffqaf4vrc2q3cds=") -if err != nil { - // probably an invalid key was given - log.Fatalln(err) -} - -// verify an OTP string -result, ok, err := yubiAuth.Verify("ccccccbetgjevivbklihljgtbenbfrefccveiglnjfbc") -if err != nil { - log.Fatalln(err) -} - -if ok { - // succes!! The OTP is valid! - log.Printf("Used query was: %s\n", result.GetRequestQuery()) // this query string includes the url of the api-server that responded first. -} else { - // fail! The OTP is invalid or has been used before. - log.Println("The given OTP is invalid!!!") -} -``` - - -**Do not verify HTTPS certificate:** -```go -// Disable HTTPS cert verification. Use true to enable again. -yubiAuth.HttpsVerifyCertificate(false) -``` - - -**HTTP instead of HTTPS:** -```go -// Disable HTTPS. Use true to enable again. -yubiAuth.UseHttps(false) -``` - - -**Custom API server:** -```go -// Set a list of n servers, each server as host + path. -// Do not prepend with protocol -yubiAuth.SetApiServerList("api0.server.com/api/verify", "api1.server.com/api/verify", "otherserver.com/api/verify") -``` - -## Licence - -This project is licensed under a Simplified BSD license. Please read the [LICENSE file][license]. - - -## Todo - - Test files - - More documentation - - Getters/Setters for some options on the YubiAuth object. - -## Protocol & Package documentation - -This project is implementing a pure-Go Yubico OTP Validation Client and is following the [Yubico Validation Protocol Version 2.0][validationProtocolV20]. - -You will find "go doc"-like [package documentation at go.pkgdoc.org][pkgdoc]. - - - [license]: https://github.com/GeertJohan/yubigo/blob/master/LICENSE - [getapikey]: https://upgrade.yubico.com/getapikey/ - [pkgdoc]: http://go.pkgdoc.org/github.com/GeertJohan/yubigo - [validationProtocolV20]: http://code.google.com/p/yubikey-val-server-php/wiki/ValidationProtocolV20
\ No newline at end of file diff --git a/vendor/github.com/GeertJohan/yubigo/yubigo.go b/vendor/github.com/GeertJohan/yubigo/yubigo.go deleted file mode 100644 index f317679..0000000 --- a/vendor/github.com/GeertJohan/yubigo/yubigo.go +++ /dev/null @@ -1,565 +0,0 @@ -package yubigo - -import ( - "bufio" - "crypto/hmac" - "crypto/sha1" - "crypto/tls" - "encoding/base64" - "errors" - "fmt" - "io" - "log" - "math/rand" - "net/http" - "regexp" - "sort" - "strings" - "sync" - "time" -) - -var ( - dvorakToQwerty = strings.NewReplacer( - "j", "c", "x", "b", "e", "d", ".", "e", "u", "f", "i", "g", "d", "h", "c", "i", - "h", "j", "t", "k", "n", "l", "b", "n", "p", "r", "y", "t", "g", "u", "k", "v", - "J", "C", "X", "B", "E", "D", ".", "E", "U", "F", "I", "G", "D", "H", "C", "I", - "H", "J", "T", "K", "N", "L", "B", "N", "P", "R", "Y", "T", "G", "U", "K", "V") - matchDvorak = regexp.MustCompile(`^[jxe.uidchtnbpygkJXE.UIDCHTNBPYGK]{32,48}$`) - matchQwerty = regexp.MustCompile(`^[cbdefghijklnrtuvCBDEFGHIJKLNRTUV]{32,48}$`) - signatureUrlFix = regexp.MustCompile(`\+`) -) - -// Package variable used to override the http client used for communication -// with Yubico. If nil the standard http.Client will be used - if overriding -// you need to ensure the transport options are set. -var HTTPClient *http.Client = nil - -// Parse and verify the given OTP string into prefix (identity) and ciphertext. -// Function returns a non-nil error when given OTP is not in valid format. -// NOTE: This function does NOT verify if the OTP is correct and unused/unique. -func ParseOTP(otp string) (prefix string, ciphertext string, err error) { - if len(otp) < 32 || len(otp) > 48 { - err = errors.New("OTP has wrong length.") - return - } - - // When otp matches dvorak-otp, then translate to qwerty. - if matchDvorak.MatchString(otp) { - otp = dvorakToQwerty.Replace(otp) - } - - // Verify that otp matches qwerty expectations - if !matchQwerty.MatchString(otp) { - err = errors.New("Given string is not a valid Yubikey OTP. It contains invalid characters and/or the length is wrong.") - return - } - - l := len(otp) - prefix = otp[0 : l-32] - ciphertext = otp[l-32 : l] - return -} - -type YubiAuth struct { - id string - key []byte - apiServerList []string - protocol string - verifyCertificate bool - workers []*verifyWorker - use sync.Mutex - debug bool -} - -type verifyWorker struct { - ya *YubiAuth // YubiAuth this worker belongs to - id int // Worker id - client *http.Client // http client standing by ready for work - apiServer string // API server URL - work chan *workRequest // Channel on which the worker receives work - stop chan bool // Channel for stop signal -} - -type workRequest struct { - paramString *string - resultChan chan *workResult -} - -type workResult struct { - response *http.Response - requestQuery string - err error // indicates a failing server/network. This doesn't mean the OTP is invalid. -} - -func (vw *verifyWorker) process() { - if vw.ya.debug { - log.Printf("worker[%d]: Started.\n", vw.id) - } - for { - select { - case w := <-vw.work: - - // Create url - url := vw.ya.protocol + vw.apiServer + *w.paramString - - if vw.ya.debug { - log.Printf("worker[%d]: Have work. Requesting: %s\n", vw.id, url) - } - - // Create request - request, err := http.NewRequest("GET", url, nil) - if err != nil { - w.resultChan <- &workResult{ - response: nil, - requestQuery: url, - err: fmt.Errorf("Could not create http request. Error: %s\n", err), - } - continue - } - request.Header.Add("User-Agent", "github.com/GeertJohan/yubigo") - - // Call server - response, err := vw.client.Do(request) - - // If we received an error from the client, return that (wrapped) on the channel. - if err != nil { - w.resultChan <- &workResult{ - response: nil, - requestQuery: url, - err: fmt.Errorf("Http client error: %s\n", err), - } - if vw.ya.debug { - log.Printf("worker[%d]: Http client error: %s", vw.id, err) - } - continue - } - - // It seems everything is ok! return the response (wrapped) on the channel. - if vw.ya.debug { - log.Printf("worker[%d] Received result from api server. Sending on channel.", vw.id) - } - w.resultChan <- &workResult{ - response: response, - requestQuery: url, - err: nil, - } - continue - case <-vw.stop: - if vw.ya.debug { - log.Printf("worker[%d]: received stop signal.\n", vw.id) - } - return - } - } -} - -// Create a yubiAuth instance with given API-id and API-key. -// Returns an error when the key could not be base64 decoded. -// To use yubigo with the Yubico Web Service (default api servers), create an API id+key here: https://upgrade.yubico.com/getapikey/ -// Debugging is disabled. For debugging: use NewYubiAuthDebug(..) -func NewYubiAuth(id string, key string) (auth *YubiAuth, err error) { - return NewYubiAuthDebug(id, key, false) -} - -// Create a yubiAuth instance for given API-id and API-key. -// Has third parameter `debug`. When debug is true this YubiAuth instance will spam the console with logging messages. -// Returns an error when the key could not be base64 decoded. -// To use yubigo with the Yubico Web Service (default api servers), create an API id+key here: https://upgrade.yubico.com/getapikey/ -func NewYubiAuthDebug(id string, key string, debug bool) (auth *YubiAuth, err error) { - keyBytes, err := base64.StdEncoding.DecodeString(key) - if err != nil { - err = fmt.Errorf("Given key seems to be invalid. Could not base64_decode. Error: %s\n", err) - return - } - - if debug { - log.Printf("NewYubiAuthDebug: Given key is base64 decodable. Creating new YubiAuth instance with api id '%s'.\n", id) - } - - auth = &YubiAuth{ - id: id, - key: keyBytes, - - apiServerList: []string{"api.yubico.com/wsapi/2.0/verify", - "api2.yubico.com/wsapi/2.0/verify", - "api3.yubico.com/wsapi/2.0/verify", - "api4.yubico.com/wsapi/2.0/verify", - "api5.yubico.com/wsapi/2.0/verify"}, - - protocol: "https://", - verifyCertificate: true, - - debug: debug, - } - - if debug { - log.Printf("NewYubiAuthDebug: Using yubico web servers: %#v\n", auth.apiServerList) - log.Println("NewYubiAuthDebug: Going to build workers.") - } - - // Build workers - auth.buildWorkers() - - // All done :) - return -} - -// Stops existing workers and creates new ones. -func (ya *YubiAuth) buildWorkers() { - // Unexported (internal) method, so no locking. - - // create tls config - tlsConfig := &tls.Config{} - if !ya.verifyCertificate { - tlsConfig.InsecureSkipVerify = true - } - - // stop all existing workers - for _, worker := range ya.workers { - worker.stop <- true - } - - // create new (empty) slice with exact capacity - ya.workers = make([]*verifyWorker, 0, len(ya.apiServerList)) - - // start new workers. One for each apiServerString - for id, apiServer := range ya.apiServerList { - // create worker instance with new http.Client instance - worker := &verifyWorker{ - ya: ya, - id: id, - apiServer: apiServer + "?", - work: make(chan *workRequest), - stop: make(chan bool), - } - - if HTTPClient == nil { - worker.client = &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - }, - } - } else { - worker.client = HTTPClient - } - - ya.workers = append(ya.workers, worker) - - // start worker process in new goroutine - go worker.process() - } -} - -// Use this method to specify a list of servers for verification. -// Each server string should contain host + path. -// Example: "api.yubico.com/wsapi/2.0/verify". -func (ya *YubiAuth) SetApiServerList(urls ...string) { - // Lock - ya.use.Lock() - defer ya.use.Unlock() - - // save setting - ya.apiServerList = urls - - // rebuild workers (api server url's have changed) - ya.buildWorkers() -} - -// Retrieve the the ist of servers that are being used for verification. -func (ya *YubiAuth) GetApiServerList() []string { - return ya.apiServerList -} - -// Enable or disable the use of https -func (ya *YubiAuth) UseHttps(useHttps bool) { - // Lock - ya.use.Lock() - defer ya.use.Unlock() - - // change setting - if useHttps { - ya.protocol = "https://" - } else { - ya.protocol = "http://" - } - - // no need to rebuild workers, they re-read ya.protocol on each request. -} - -// Enable or disable https certificate verification -// Disable this at your own risk. -func (ya *YubiAuth) HttpsVerifyCertificate(verifyCertificate bool) { - // Lock - ya.use.Lock() - defer ya.use.Unlock() - - // save setting - ya.verifyCertificate = verifyCertificate - - // rebuild workers (client has to be changed) - ya.buildWorkers() -} - -// The verify method calls the API with given OTP and returns if the OTP is valid or not. -// This method will return an error if something unexpected happens -// If no error was returned, the returned 'ok bool' indicates if the OTP is valid -// if the 'ok bool' is true, additional informtion can be found in the returned YubiResponse object -func (ya *YubiAuth) Verify(otp string) (yr *YubiResponse, ok bool, err error) { - // Lock - ya.use.Lock() - defer ya.use.Unlock() - - // check the OTP - _, _, err = ParseOTP(otp) - if err != nil { - return nil, false, err - } - - // create slice to store parameters for this verification request - paramSlice := make([]string, 0) - paramSlice = append(paramSlice, "id="+ya.id) - paramSlice = append(paramSlice, "otp="+otp) - - // Create 40 characters nonce - rand.Seed(time.Now().UnixNano()) - k := make([]rune, 40) - for i := 0; i < 40; i++ { - c := rand.Intn(35) - if c < 10 { - c += 48 // numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9') - } else { - c += 87 // lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z') - } - k[i] = rune(c) - } - nonce := string(k) - paramSlice = append(paramSlice, "nonce="+nonce) - - // These settings are hardcoded in the library for now. - //++ TODO(GeertJohan): add these values to the yubiAuth object and create getters/setters - // paramSlice = append(paramSlice, "timestamp=1") - paramSlice = append(paramSlice, "sl=secure") - - //++ TODO(GeertJohan): Add timeout support? - //++ //paramSlice = append(paramSlice, "timeout=") - - // sort the slice - sort.Strings(paramSlice) - - // create parameter string - paramString := strings.Join(paramSlice, "&") - - // generate signature - if len(ya.key) > 0 { - hmacenc := hmac.New(sha1.New, ya.key) - _, err := hmacenc.Write([]byte(paramString)) - if err != nil { - return nil, false, fmt.Errorf("Could not calculate signature. Error: %s\n", err) - } - signature := base64.StdEncoding.EncodeToString(hmacenc.Sum([]byte{})) - signature = signatureUrlFix.ReplaceAllString(signature, `%2B`) - paramString = paramString + "&h=" + signature - } - - // create result channel, buffersize equals the amount of workers. - resultChan := make(chan *workResult, len(ya.workers)) - - // create workRequest instance - wr := &workRequest{ - paramString: ¶mString, - resultChan: resultChan, - } - - // send workRequest to each worker - for _, worker := range ya.workers { - worker.work <- wr - } - - // count the errors so we can handle when all servers fail (network fail for instance) - errCount := 0 - - // local result var, will contain the first result we have - var result *workResult - - // keep looping until we have a good result - for { - // listen for result from a worker - result = <-resultChan - - // check for error - if result.err != nil { - // increment error counter - errCount++ - - if ya.debug { - // debug logging - log.Printf("A server (%s) gave error back: %s\n", result.requestQuery, result.err) - } - - if errCount == len(ya.apiServerList) { - // All workers are done, there's nothing left to try. we return an error. - return nil, false, errors.New("None of the servers responded properly.") - } - - // we have an error, but not all workers responded yet, so lets wait for the next result. - continue - } - - // create a yubiResult from the workers response. - yr, err = newYubiResponse(result) - if err != nil { - return nil, false, err - } - - // Check for "REPLAYED_REQUEST" result. - if status, _ := yr.resultParameters["status"]; status == "REPLAYED_REQUEST" { - // The result status is "REPLAYED_REQUEST". - // This means that the server for this request got sync with an other server before our request. - // Lets wait for the result from the other server. - // See: http://forum.yubico.com/viewtopic.php?f=3&t=701 - - // increment error counter - errCount++ - - if ya.debug { - // debug logging - log.Println("Got replayed request: ", result.response.Body) - } - - if errCount == len(ya.apiServerList) { - // All workers are done, there' is nothing left to try. We return an error. - return nil, false, errors.New("None of the servers responded properly.") - } - - // We have a replayed request, but not all workers responded yet, so lets wait for the next result. - continue - } - - // No error or REPLAYED_REQUEST. Seems like we have a proper result. - break - } - - // check status - status, ok := yr.resultParameters["status"] - if !ok || status != "OK" { - switch status { - case "BAD_OTP": - return yr, false, nil - case "REPLAYED_OTP": - return yr, false, errors.New("The OTP is valid, but has been used before. If you receive this error, you might be the victim of a man-in-the-middle attack.") - case "BAD_SIGNATURE": - return yr, false, errors.New("Signature verification at the api server failed. The used id/key combination could be invalid or is not activated (yet).") - case "NO_SUCH_CLIENT": - return yr, false, errors.New("The api server does not accept the given id. It might be invalid or is not activated (yet).") - case "OPERATION_NOT_ALLOWED": - return yr, false, errors.New("The api server does not allow the given api id to verify OTPs.") - case "BACKEND_ERROR": - return yr, false, errors.New("The api server seems to be broken. Please contact the api servers system administration (yubico servers? contact yubico).") - case "NOT_ENOUGH_ANSWERS": - return yr, false, errors.New("The api server could not get requested number of syncs during before timeout") - case "REPLAYED_REQUEST": - panic("Unexpected. This status should've been catched in the worker response loop.") - return yr, false, errors.New("The api server has seen this unique request before. If you receive this error, you might be the victim of a man-in-the-middle attack.") - default: - return yr, false, fmt.Errorf("Unknown status parameter (%s) sent by api server.", status) - } - } - - // check otp - otpCheck, ok := yr.resultParameters["otp"] - if !ok || otp != otpCheck { - return nil, false, errors.New("Could not validate otp value from server response.") - } - - // check nonce - nonceCheck, ok := yr.resultParameters["nonce"] - if !ok || nonce != nonceCheck { - return nil, false, errors.New("Could not validate nonce value from server response.") - } - - // check attached signature with remake of that signature, if key is actually in use. - if len(ya.key) > 0 { - receivedSignature, ok := yr.resultParameters["h"] - if !ok || len(receivedSignature) == 0 { - return nil, false, errors.New("No signature hash was attached by the api server, we do expect one though. This might be a hacking attempt.") - } - - // create a slice with the same size-1 as the parameters map (we're leaving the hash itself out of it's replica calculation) - receivedValuesSlice := make([]string, 0, len(yr.resultParameters)-1) - for key, value := range yr.resultParameters { - if key != "h" { - receivedValuesSlice = append(receivedValuesSlice, key+"="+value) - } - } - sort.Strings(receivedValuesSlice) - receivedValuesString := strings.Join(receivedValuesSlice, "&") - hmacenc := hmac.New(sha1.New, ya.key) - _, err := hmacenc.Write([]byte(receivedValuesString)) - if err != nil { - return nil, false, fmt.Errorf("Could not calculate signature replica. Error: %s\n", err) - } - recievedSignatureReplica := base64.StdEncoding.EncodeToString(hmacenc.Sum([]byte{})) - - if receivedSignature != recievedSignatureReplica { - return nil, false, errors.New("The received signature hash is not valid. This might be a hacking attempt.") - } - } - - // we're done! - yr.validOTP = true - return yr, true, nil - -} - -// Contains details about yubikey OTP verification. -type YubiResponse struct { - requestQuery string - resultParameters map[string]string - validOTP bool -} - -func newYubiResponse(result *workResult) (*YubiResponse, error) { - bodyReader := bufio.NewReader(result.response.Body) - yr := &YubiResponse{} - yr.resultParameters = make(map[string]string) - yr.requestQuery = result.requestQuery - for { - // read through the response lines - line, err := bodyReader.ReadString('\n') - - // handle error, which at one point should be an expected io.EOF (end of file) - if err != nil { - if err == io.EOF { - break // successfully done with reading lines, lets break this for loop - } - return nil, fmt.Errorf("Could not read result body from the server. Error: %s\n", err) - } - - // parse result lines, split on first '=', trim \n and \r - keyvalue := strings.SplitN(line, "=", 2) - if len(keyvalue) == 2 { - yr.resultParameters[keyvalue[0]] = strings.Trim(keyvalue[1], "\n\r") - } - } - return yr, nil -} - -// Returns wether the verification was successful -func (yr *YubiResponse) IsValidOTP() bool { - return yr.validOTP -} - -// Get the requestQuery that was used during verification. -func (yr *YubiResponse) GetRequestQuery() string { - return yr.requestQuery -} - -// Retrieve a parameter from the api's response -func (yr *YubiResponse) GetResultParameter(key string) (value string) { - value, ok := yr.resultParameters[key] - if !ok { - value = "" - } - return value -} diff --git a/vendor/github.com/hypersleep/easyssh/.gitignore b/vendor/github.com/hypersleep/easyssh/.gitignore deleted file mode 100644 index daf913b..0000000 --- a/vendor/github.com/hypersleep/easyssh/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/hypersleep/easyssh/README.md b/vendor/github.com/hypersleep/easyssh/README.md deleted file mode 100644 index 96f5cb3..0000000 --- a/vendor/github.com/hypersleep/easyssh/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# easyssh - -## Description - -Package easyssh provides a simple implementation of some SSH protocol features in Go. -You can simply run command on remote server or upload a file even simple than native console SSH client. -Do not need to think about Dials, sessions, defers and public keys...Let easyssh will be think about it! - -## So easy to use! - -[Run a command on remote server and get STDOUT output](https://github.com/hypersleep/easyssh/blob/master/example/run.go) - -[Upload a file to remote server](https://github.com/hypersleep/easyssh/blob/master/example/scp.go) diff --git a/vendor/github.com/hypersleep/easyssh/easyssh.go b/vendor/github.com/hypersleep/easyssh/easyssh.go deleted file mode 100644 index c530eea..0000000 --- a/vendor/github.com/hypersleep/easyssh/easyssh.go +++ /dev/null @@ -1,225 +0,0 @@ -// Package easyssh provides a simple implementation of some SSH protocol -// features in Go. You can simply run a command on a remote server or get a file -// even simpler than native console SSH client. You don't need to think about -// Dials, sessions, defers, or public keys... Let easyssh think about it! -package easyssh - -import ( - "bufio" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "os/user" - "path/filepath" - "time" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/agent" -) - -// Contains main authority information. -// User field should be a name of user on remote server (ex. john in ssh john@example.com). -// Server field should be a remote machine address (ex. example.com in ssh john@example.com) -// Key is a path to private key on your local machine. -// Port is SSH server port on remote machine. -// Note: easyssh looking for private key in user's home directory (ex. /home/john + Key). -// Then ensure your Key begins from '/' (ex. /.ssh/id_rsa) -type MakeConfig struct { - User string - Server string - Key string - Port string - Password string -} - -// returns ssh.Signer from user you running app home path + cutted key path. -// (ex. pubkey,err := getKeyFile("/.ssh/id_rsa") ) -func getKeyFile(keypath string) (ssh.Signer, error) { - usr, err := user.Current() - if err != nil { - return nil, err - } - - file := usr.HomeDir + keypath - buf, err := ioutil.ReadFile(file) - if err != nil { - return nil, err - } - - pubkey, err := ssh.ParsePrivateKey(buf) - if err != nil { - return nil, err - } - - return pubkey, nil -} - -// connects to remote server using MakeConfig struct and returns *ssh.Session -func (ssh_conf *MakeConfig) connect() (*ssh.Session, error) { - // auths holds the detected ssh auth methods - auths := []ssh.AuthMethod{} - - // figure out what auths are requested, what is supported - if ssh_conf.Password != "" { - auths = append(auths, ssh.Password(ssh_conf.Password)) - } - - if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { - auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) - defer sshAgent.Close() - } - - if pubkey, err := getKeyFile(ssh_conf.Key); err == nil { - auths = append(auths, ssh.PublicKeys(pubkey)) - } - - config := &ssh.ClientConfig{ - User: ssh_conf.User, - Auth: auths, - } - - client, err := ssh.Dial("tcp", ssh_conf.Server+":"+ssh_conf.Port, config) - if err != nil { - return nil, err - } - - session, err := client.NewSession() - if err != nil { - return nil, err - } - - return session, nil -} - -// Stream returns one channel that combines the stdout and stderr of the command -// as it is run on the remote machine, and another that sends true when the -// command is done. The sessions and channels will then be closed. -func (ssh_conf *MakeConfig) Stream(command string, timeout int) (stdout chan string, stderr chan string, done chan bool, err error) { - // connect to remote host - session, err := ssh_conf.connect() - if err != nil { - return stdout, stderr, done, err - } - // connect to both outputs (they are of type io.Reader) - outReader, err := session.StdoutPipe() - if err != nil { - return stdout, stderr, done, err - } - errReader, err := session.StderrPipe() - if err != nil { - return stdout, stderr, done, err - } - // combine outputs, create a line-by-line scanner - stdoutReader := io.MultiReader(outReader) - stderrReader := io.MultiReader(errReader) - err = session.Start(command) - stdoutScanner := bufio.NewScanner(stdoutReader) - stderrScanner := bufio.NewScanner(stderrReader) - // continuously send the command's output over the channel - stdoutChan := make(chan string) - stderrChan := make(chan string) - done = make(chan bool) - - go func(stdoutScanner, stderrScanner *bufio.Scanner, stdoutChan, stderrChan chan string, done chan bool) { - defer close(stdoutChan) - defer close(stderrChan) - defer close(done) - - timeoutChan := time.After(time.Duration(timeout) * time.Second) - res := make(chan bool, 1) - - go func() { - for stdoutScanner.Scan() { - stdoutChan <- stdoutScanner.Text() - } - for stderrScanner.Scan() { - stderrChan <- stderrScanner.Text() - } - // close all of our open resources - res <- true |
