Skip to content

Commit

Permalink
feat(ssh.go): adds private ssh key authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
struckchure committed Aug 21, 2024
1 parent 686ad98 commit 3a1b5d5
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,37 @@ import (
type Ssh struct{}

type AuthenticateArgs struct {
User string
Password string
Host string
Port int
User string
Password string
Host string
Port int
PrivateSshKey string
}

func (s *Ssh) Authenticate(args AuthenticateArgs) (*ssh.Client, error) {
signers := make([]ssh.AuthMethod, 0)

if args.PrivateSshKey == "" && args.Password == "" {
return nil, errors.New("ssh key or password is required")
}

if args.PrivateSshKey != "" {
privateKey, err := ssh.ParsePrivateKey([]byte(args.PrivateSshKey))
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
signers = append(signers, ssh.PublicKeys(privateKey))
} else {
signers = append(signers, ssh.Password(args.Password))
}

sshConfig := &ssh.ClientConfig{
User: args.User,
Auth: []ssh.AuthMethod{
ssh.Password(args.Password), // Use a password
},
Auth: signers,
// TODO: For production, use a more secure host key callback
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}

if args.Password != "" {
sshConfig.Auth = []ssh.AuthMethod{ssh.Password(args.Password)}
} else {
sshConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys()}
}

// Connect to the SSH server
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", args.Host, args.Port), sshConfig)
if err != nil {
Expand Down

0 comments on commit 3a1b5d5

Please sign in to comment.