github.com/puellanivis/breton@v0.2.16/lib/files/sftpfiles/option.go (about) 1 package sftpfiles 2 3 import ( 4 "github.com/puellanivis/breton/lib/files" 5 6 "golang.org/x/crypto/ssh" 7 ) 8 9 func noopOption() files.Option { 10 return func(_ files.File) (files.Option, error) { 11 return noopOption(), nil 12 } 13 } 14 15 func withAuths(auths []ssh.AuthMethod) files.Option { 16 type authSetter interface { 17 SetAuths([]ssh.AuthMethod) []ssh.AuthMethod 18 } 19 20 return func(f files.File) (files.Option, error) { 21 h, ok := f.(authSetter) 22 if !ok { 23 return noopOption(), nil 24 } 25 26 save := h.SetAuths(auths) 27 return withAuths(save), nil 28 } 29 } 30 31 // WithAuth includes an arbitrary ssh.AuthMethod to be used for authentication during the ssh.Dial. 32 func WithAuth(auth ssh.AuthMethod) files.Option { 33 type authAdder interface { 34 AddAuth(ssh.AuthMethod) []ssh.AuthMethod 35 } 36 37 return func(f files.File) (files.Option, error) { 38 h, ok := f.(authAdder) 39 if !ok { 40 return noopOption(), nil 41 } 42 43 save := h.AddAuth(auth) 44 return withAuths(save), nil 45 } 46 } 47 48 // IgnoreHostKeys specifies whether the ssh.Dial should ignore host keys during connection. Using this is insecure! 49 // 50 // Setting this to true will override any existing WithHostKey option, unless it is later turned off. 51 func IgnoreHostKeys(state bool) files.Option { 52 type hostkeyIgnorer interface { 53 IgnoreHostKeys(bool) bool 54 } 55 56 return func(f files.File) (files.Option, error) { 57 h, ok := f.(hostkeyIgnorer) 58 if !ok { 59 return noopOption(), nil 60 } 61 62 save := h.IgnoreHostKeys(state) 63 return IgnoreHostKeys(save), nil 64 } 65 } 66 67 func withHostKeyCallback(cb ssh.HostKeyCallback, algos []string) files.Option { 68 type hostkeySetter interface { 69 SetHostKeyCallback(ssh.HostKeyCallback, []string) (ssh.HostKeyCallback, []string) 70 } 71 72 return func(f files.File) (files.Option, error) { 73 h, ok := f.(hostkeySetter) 74 if !ok { 75 return noopOption(), nil 76 } 77 78 saveHK, saveAlgos := h.SetHostKeyCallback(cb, algos) 79 return withHostKeyCallback(saveHK, saveAlgos), nil 80 } 81 } 82 83 // WithHostKey defines an expected host key from the authorized key format specified in the sshd(8) man page. 84 // 85 // i.e. ssh-keytype BASE64BLOB string-comment 86 // 87 // If the IgnoreHostKeys option has been set, then this option will be ignored. 88 func WithHostKey(hostkey []byte) files.Option { 89 key, _, _, _, err := ssh.ParseAuthorizedKey(hostkey) 90 if err != nil { 91 return func(_ files.File) (files.Option, error) { 92 return nil, err 93 } 94 } 95 96 return withHostKeyCallback(ssh.FixedHostKey(key), []string{key.Type()}) 97 }