123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package emailer
- import (
- "crypto/hmac"
- "crypto/md5"
- "errors"
- "fmt"
- )
- type Auth interface {
-
-
-
-
-
-
- Start(server *ServerInfo) (proto string, toServer []byte, err error)
-
-
-
-
-
-
- Next(fromServer []byte, more bool) (toServer []byte, err error)
- IsTLS() bool
- }
- type ServerInfo struct {
- Name string
- TLS bool
- Auth []string
- }
- type plainAuth struct {
- identity, username, password string
- host string
- tls bool
- }
- func (s *plainAuth) IsTLS() bool {
- return s.tls
- }
- func PlainAuth(identity, username, password, host string, tls bool) Auth {
- return &plainAuth{identity, username, password, host, tls}
- }
- func isLocalhost(name string) bool {
- return name == "localhost" || name == "127.0.0.1" || name == "::1"
- }
- func (a *plainAuth) Start(server *ServerInfo) (string, []byte, error) {
-
-
-
-
-
- if !server.TLS && !isLocalhost(server.Name) {
- return "", nil, errors.New("unencrypted connection")
- }
- if server.Name != a.host {
- return "", nil, errors.New("wrong host name")
- }
- resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password)
- return "PLAIN", resp, nil
- }
- func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, error) {
- if more {
-
- return nil, errors.New("unexpected server challenge")
- }
- return nil, nil
- }
- type cramMD5Auth struct {
- username, secret string
- tls bool
- }
- func CRAMMD5Auth(username, secret string, tls bool) Auth {
- return &cramMD5Auth{username, secret, tls}
- }
- func (s *cramMD5Auth) IsTLS() bool {
- return s.tls
- }
- func (a *cramMD5Auth) Start(server *ServerInfo) (string, []byte, error) {
- return "CRAM-MD5", nil, nil
- }
- func (a *cramMD5Auth) Next(fromServer []byte, more bool) ([]byte, error) {
- if more {
- d := hmac.New(md5.New, []byte(a.secret))
- d.Write(fromServer)
- s := make([]byte, 0, d.Size())
- return []byte(fmt.Sprintf("%s %x", a.username, d.Sum(s))), nil
- }
- return nil, nil
- }
|