123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320 |
- package ssh_test
- import (
- "bufio"
- "bytes"
- "fmt"
- "io/ioutil"
- "log"
- "net"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "golang.org/x/crypto/ssh"
- "golang.org/x/crypto/ssh/terminal"
- )
- func ExampleNewServerConn() {
-
-
-
- authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys")
- if err != nil {
- log.Fatalf("Failed to load authorized_keys, err: %v", err)
- }
- authorizedKeysMap := map[string]bool{}
- for len(authorizedKeysBytes) > 0 {
- pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
- if err != nil {
- log.Fatal(err)
- }
- authorizedKeysMap[string(pubKey.Marshal())] = true
- authorizedKeysBytes = rest
- }
-
-
- config := &ssh.ServerConfig{
-
- PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
-
-
- if c.User() == "testuser" && string(pass) == "tiger" {
- return nil, nil
- }
- return nil, fmt.Errorf("password rejected for %q", c.User())
- },
-
- PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
- if authorizedKeysMap[string(pubKey.Marshal())] {
- return &ssh.Permissions{
-
- Extensions: map[string]string{
- "pubkey-fp": ssh.FingerprintSHA256(pubKey),
- },
- }, nil
- }
- return nil, fmt.Errorf("unknown public key for %q", c.User())
- },
- }
- privateBytes, err := ioutil.ReadFile("id_rsa")
- if err != nil {
- log.Fatal("Failed to load private key: ", err)
- }
- private, err := ssh.ParsePrivateKey(privateBytes)
- if err != nil {
- log.Fatal("Failed to parse private key: ", err)
- }
- config.AddHostKey(private)
-
-
- listener, err := net.Listen("tcp", "0.0.0.0:2022")
- if err != nil {
- log.Fatal("failed to listen for connection: ", err)
- }
- nConn, err := listener.Accept()
- if err != nil {
- log.Fatal("failed to accept incoming connection: ", err)
- }
-
-
- conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
- if err != nil {
- log.Fatal("failed to handshake: ", err)
- }
- log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"])
-
- go ssh.DiscardRequests(reqs)
-
- for newChannel := range chans {
-
-
-
-
- if newChannel.ChannelType() != "session" {
- newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
- continue
- }
- channel, requests, err := newChannel.Accept()
- if err != nil {
- log.Fatalf("Could not accept channel: %v", err)
- }
-
-
-
- go func(in <-chan *ssh.Request) {
- for req := range in {
- req.Reply(req.Type == "shell", nil)
- }
- }(requests)
- term := terminal.NewTerminal(channel, "> ")
- go func() {
- defer channel.Close()
- for {
- line, err := term.ReadLine()
- if err != nil {
- break
- }
- fmt.Println(line)
- }
- }()
- }
- }
- func ExampleClientConfig_HostKeyCallback() {
-
-
- host := "hostname"
- file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
- if err != nil {
- log.Fatal(err)
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- var hostKey ssh.PublicKey
- for scanner.Scan() {
- fields := strings.Split(scanner.Text(), " ")
- if len(fields) != 3 {
- continue
- }
- if strings.Contains(fields[0], host) {
- var err error
- hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
- if err != nil {
- log.Fatalf("error parsing %q: %v", fields[2], err)
- }
- break
- }
- }
- if hostKey == nil {
- log.Fatalf("no hostkey for %s", host)
- }
- config := ssh.ClientConfig{
- User: os.Getenv("USER"),
- HostKeyCallback: ssh.FixedHostKey(hostKey),
- }
- _, err = ssh.Dial("tcp", host+":22", &config)
- log.Println(err)
- }
- func ExampleDial() {
- var hostKey ssh.PublicKey
-
-
-
-
-
- config := &ssh.ClientConfig{
- User: "username",
- Auth: []ssh.AuthMethod{
- ssh.Password("yourpassword"),
- },
- HostKeyCallback: ssh.FixedHostKey(hostKey),
- }
- client, err := ssh.Dial("tcp", "yourserver.com:22", config)
- if err != nil {
- log.Fatal("Failed to dial: ", err)
- }
-
-
- session, err := client.NewSession()
- if err != nil {
- log.Fatal("Failed to create session: ", err)
- }
- defer session.Close()
-
-
- var b bytes.Buffer
- session.Stdout = &b
- if err := session.Run("/usr/bin/whoami"); err != nil {
- log.Fatal("Failed to run: " + err.Error())
- }
- fmt.Println(b.String())
- }
- func ExamplePublicKeys() {
- var hostKey ssh.PublicKey
-
-
-
-
-
- key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
- if err != nil {
- log.Fatalf("unable to read private key: %v", err)
- }
-
- signer, err := ssh.ParsePrivateKey(key)
- if err != nil {
- log.Fatalf("unable to parse private key: %v", err)
- }
- config := &ssh.ClientConfig{
- User: "user",
- Auth: []ssh.AuthMethod{
-
- ssh.PublicKeys(signer),
- },
- HostKeyCallback: ssh.FixedHostKey(hostKey),
- }
-
- client, err := ssh.Dial("tcp", "host.com:22", config)
- if err != nil {
- log.Fatalf("unable to connect: %v", err)
- }
- defer client.Close()
- }
- func ExampleClient_Listen() {
- var hostKey ssh.PublicKey
- config := &ssh.ClientConfig{
- User: "username",
- Auth: []ssh.AuthMethod{
- ssh.Password("password"),
- },
- HostKeyCallback: ssh.FixedHostKey(hostKey),
- }
-
- conn, err := ssh.Dial("tcp", "localhost:22", config)
- if err != nil {
- log.Fatal("unable to connect: ", err)
- }
- defer conn.Close()
-
- l, err := conn.Listen("tcp", "0.0.0.0:8080")
- if err != nil {
- log.Fatal("unable to register tcp forward: ", err)
- }
- defer l.Close()
-
- http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(resp, "Hello world!\n")
- }))
- }
- func ExampleSession_RequestPty() {
- var hostKey ssh.PublicKey
-
- config := &ssh.ClientConfig{
- User: "username",
- Auth: []ssh.AuthMethod{
- ssh.Password("password"),
- },
- HostKeyCallback: ssh.FixedHostKey(hostKey),
- }
-
- conn, err := ssh.Dial("tcp", "localhost:22", config)
- if err != nil {
- log.Fatal("unable to connect: ", err)
- }
- defer conn.Close()
-
- session, err := conn.NewSession()
- if err != nil {
- log.Fatal("unable to create session: ", err)
- }
- defer session.Close()
-
- modes := ssh.TerminalModes{
- ssh.ECHO: 0,
- ssh.TTY_OP_ISPEED: 14400,
- ssh.TTY_OP_OSPEED: 14400,
- }
-
- if err := session.RequestPty("xterm", 40, 80, modes); err != nil {
- log.Fatal("request for pseudo terminal failed: ", err)
- }
-
- if err := session.Shell(); err != nil {
- log.Fatal("failed to start shell: ", err)
- }
- }
|