sasl.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package sasl
  26. import (
  27. "bufio"
  28. "bytes"
  29. "encoding/base64"
  30. "encoding/hex"
  31. "errors"
  32. "fmt"
  33. "io"
  34. "log"
  35. "net"
  36. "os"
  37. "strconv"
  38. "strings"
  39. "time"
  40. "git.semlanik.org/semlanik/gostfix/auth"
  41. "github.com/google/uuid"
  42. )
  43. type SaslServer struct {
  44. pid int
  45. cuid int
  46. authenticator *auth.Authenticator
  47. }
  48. const (
  49. Version = "VERSION"
  50. CPid = "CPID"
  51. SPid = "SPID"
  52. Cuid = "CUID"
  53. Cookie = "COOKIE"
  54. Mech = "MECH"
  55. Done = "DONE"
  56. Auth = "AUTH"
  57. Fail = "FAIL"
  58. Cont = "CONT"
  59. Ok = "OK"
  60. )
  61. const (
  62. ContinueStateNone = iota
  63. ContinueStateCredentials
  64. )
  65. func NewSaslServer() (*SaslServer, error) {
  66. authenticator, err := auth.NewAuthenticator()
  67. if err != nil {
  68. return nil, err
  69. }
  70. return &SaslServer{
  71. pid: os.Getpid(),
  72. cuid: 0,
  73. authenticator: authenticator,
  74. }, nil
  75. }
  76. func (s *SaslServer) Run() {
  77. go func() {
  78. l, err := net.Listen("tcp", "127.0.0.1:65201")
  79. if err != nil {
  80. log.Fatalf("Coulf not start SASL server: %s\n", err)
  81. return
  82. }
  83. defer l.Close()
  84. log.Printf("Listen sasl on: %s\n", l.Addr().String())
  85. for {
  86. conn, err := l.Accept()
  87. s.cuid++
  88. if err != nil {
  89. log.Println("Error accepting: ", err.Error())
  90. continue
  91. }
  92. go s.handleRequest(conn)
  93. }
  94. }()
  95. }
  96. func (s *SaslServer) handleRequest(conn net.Conn) {
  97. conn.SetReadDeadline(time.Time{})
  98. defer conn.Close()
  99. connectionReader := bufio.NewReader(conn)
  100. continueState := ContinueStateNone
  101. for {
  102. fullbuf, err := connectionReader.ReadString('\n')
  103. if err == io.EOF {
  104. break
  105. }
  106. if err != nil {
  107. log.Printf("Read error %s\n", err)
  108. break
  109. }
  110. currentMessage := fullbuf
  111. ids := strings.Split(currentMessage, "\t")
  112. if len(ids) < 2 {
  113. break
  114. }
  115. switch ids[0] {
  116. case Version:
  117. if len(ids) < 3 {
  118. break
  119. }
  120. if major, err := strconv.Atoi(ids[1]); err != nil || major != 1 {
  121. break
  122. }
  123. cookieUuid := uuid.New()
  124. fmt.Fprintf(conn, "%s\t%d\t%d\n", Version, 1, 2)
  125. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "PLAIN", "plaintext")
  126. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "LOGIN", "plaintext")
  127. fmt.Fprintf(conn, "%s\t%d\n", SPid, s.pid)
  128. fmt.Fprintf(conn, "%s\t%d\n", Cuid, s.cuid)
  129. fmt.Fprintf(conn, "%s\t%s\n", Cookie, hex.EncodeToString(cookieUuid[:]))
  130. fmt.Fprintf(conn, "%s\n", Done)
  131. case Auth:
  132. for _, authId := range ids {
  133. if strings.Index(authId, "resp=") == 0 {
  134. login, err := s.checkCredentials(authId[5:])
  135. if err != nil {
  136. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  137. } else {
  138. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  139. }
  140. continueState = ContinueStateNone
  141. continue
  142. }
  143. }
  144. fmt.Fprintf(conn, "%s\t%s\t%s\n", Cont, ids[1], base64.StdEncoding.EncodeToString([]byte("Username:")))
  145. continueState = ContinueStateCredentials
  146. case Cont:
  147. if len(ids) < 2 {
  148. break
  149. }
  150. if continueState == ContinueStateCredentials {
  151. if len(ids) < 3 {
  152. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid base64 data")
  153. return
  154. }
  155. login, err := s.checkCredentials(ids[2])
  156. if err != nil {
  157. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  158. } else {
  159. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  160. }
  161. continueState = ContinueStateNone
  162. } else {
  163. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid user or password")
  164. }
  165. }
  166. }
  167. }
  168. func (s *SaslServer) checkCredentials(credentialsBase64 string) (string, error) {
  169. credentials, err := base64.StdEncoding.DecodeString(credentialsBase64)
  170. if err != nil {
  171. return "", errors.New("invalid base64 data")
  172. }
  173. credentialList := bytes.Split(credentials, []byte{0})
  174. if len(credentialList) < 3 {
  175. return "", errors.New("invalid user or password")
  176. }
  177. identity := string(credentialList[0])
  178. login := string(credentialList[1])
  179. password := string(credentialList[2])
  180. if identity == "token" {
  181. if s.authenticator.Verify(login, password) {
  182. return login, nil
  183. }
  184. } else {
  185. if err := s.authenticator.CheckUser(login, password); err == nil {
  186. return login, nil
  187. }
  188. }
  189. return "", errors.New("invalid user or password")
  190. }