()
| 23 | ) |
| 24 | |
| 25 | func ExampleNewServerConn() { |
| 26 | // Public key authentication is done by comparing |
| 27 | // the public key of a received connection |
| 28 | // with the entries in the authorized_keys file. |
| 29 | authorizedKeysBytes, err := os.ReadFile("authorized_keys") |
| 30 | if err != nil { |
| 31 | log.Fatalf("Failed to load authorized_keys, err: %v", err) |
| 32 | } |
| 33 | |
| 34 | authorizedKeysMap := map[string]bool{} |
| 35 | for len(authorizedKeysBytes) > 0 { |
| 36 | pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) |
| 37 | if err != nil { |
| 38 | log.Fatal(err) |
| 39 | } |
| 40 | |
| 41 | authorizedKeysMap[string(pubKey.Marshal())] = true |
| 42 | authorizedKeysBytes = rest |
| 43 | } |
| 44 | |
| 45 | // An SSH server is represented by a ServerConfig, which holds |
| 46 | // certificate details and handles authentication of ServerConns. |
| 47 | config := &ssh.ServerConfig{ |
| 48 | // Remove to disable password auth. |
| 49 | PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { |
| 50 | // Should use constant-time compare (or better, salt+hash) in |
| 51 | // a production setting. |
| 52 | if c.User() == "testuser" && string(pass) == "tiger" { |
| 53 | return nil, nil |
| 54 | } |
| 55 | return nil, fmt.Errorf("password rejected for %q", c.User()) |
| 56 | }, |
| 57 | |
| 58 | // Remove to disable public key auth. |
| 59 | PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { |
| 60 | if authorizedKeysMap[string(pubKey.Marshal())] { |
| 61 | return &ssh.Permissions{ |
| 62 | // Record the public key used for authentication. |
| 63 | Extensions: map[string]string{ |
| 64 | "pubkey-fp": ssh.FingerprintSHA256(pubKey), |
| 65 | }, |
| 66 | }, nil |
| 67 | } |
| 68 | return nil, fmt.Errorf("unknown public key for %q", c.User()) |
| 69 | }, |
| 70 | } |
| 71 | |
| 72 | privateBytes, err := os.ReadFile("id_rsa") |
| 73 | if err != nil { |
| 74 | log.Fatal("Failed to load private key: ", err) |
| 75 | } |
| 76 | |
| 77 | private, err := ssh.ParsePrivateKey(privateBytes) |
| 78 | if err != nil { |
| 79 | log.Fatal("Failed to parse private key: ", err) |
| 80 | } |
| 81 | config.AddHostKey(private) |
| 82 |
nothing calls this directly
no test coverage detected
searching dependent graphs…