sasl.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. "git.semlanik.org/semlanik/gostfix/config"
  42. "github.com/google/uuid"
  43. )
  44. type SaslServer struct {
  45. pid int
  46. cuid int
  47. authenticator *auth.Authenticator
  48. }
  49. const (
  50. Version = "VERSION"
  51. CPid = "CPID"
  52. SPid = "SPID"
  53. Cuid = "CUID"
  54. Cookie = "COOKIE"
  55. Mech = "MECH"
  56. Done = "DONE"
  57. Auth = "AUTH"
  58. Fail = "FAIL"
  59. Cont = "CONT"
  60. Ok = "OK"
  61. )
  62. const (
  63. ContinueStateNone = iota
  64. ContinueStateCredentials
  65. )
  66. func NewSaslServer() (*SaslServer, error) {
  67. authenticator, err := auth.NewAuthenticator()
  68. if err != nil {
  69. return nil, err
  70. }
  71. return &SaslServer{
  72. pid: os.Getpid(),
  73. cuid: 0,
  74. authenticator: authenticator,
  75. }, nil
  76. }
  77. func (s *SaslServer) Run() {
  78. go func() {
  79. l, err := net.Listen("tcp", "127.0.0.1:"+config.ConfigInstance().SASLPort)
  80. if err != nil {
  81. log.Fatalf("Coulf not start SASL server: %s\n", err)
  82. return
  83. }
  84. defer l.Close()
  85. log.Printf("Listen sasl on: %s\n", l.Addr().String())
  86. for {
  87. conn, err := l.Accept()
  88. s.cuid++
  89. if err != nil {
  90. log.Println("Error accepting: ", err.Error())
  91. continue
  92. }
  93. go s.handleRequest(conn)
  94. }
  95. }()
  96. }
  97. func (s *SaslServer) handleRequest(conn net.Conn) {
  98. conn.SetReadDeadline(time.Time{})
  99. defer conn.Close()
  100. connectionReader := bufio.NewReader(conn)
  101. continueState := ContinueStateNone
  102. for {
  103. fullbuf, err := connectionReader.ReadString('\n')
  104. if err == io.EOF {
  105. break
  106. }
  107. if err != nil {
  108. log.Printf("Read error %s\n", err)
  109. break
  110. }
  111. currentMessage := fullbuf
  112. ids := strings.Split(currentMessage, "\t")
  113. if len(ids) < 2 {
  114. break
  115. }
  116. switch ids[0] {
  117. case Version:
  118. if len(ids) < 3 {
  119. break
  120. }
  121. if major, err := strconv.Atoi(ids[1]); err != nil || major != 1 {
  122. break
  123. }
  124. cookieUuid := uuid.New()
  125. fmt.Fprintf(conn, "%s\t%d\t%d\n", Version, 1, 2)
  126. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "PLAIN", "plaintext")
  127. fmt.Fprintf(conn, "%s\t%s\t%s\n", Mech, "LOGIN", "plaintext")
  128. fmt.Fprintf(conn, "%s\t%d\n", SPid, s.pid)
  129. fmt.Fprintf(conn, "%s\t%d\n", Cuid, s.cuid)
  130. fmt.Fprintf(conn, "%s\t%s\n", Cookie, hex.EncodeToString(cookieUuid[:]))
  131. fmt.Fprintf(conn, "%s\n", Done)
  132. case Auth:
  133. for _, authId := range ids {
  134. if strings.Index(authId, "resp=") == 0 {
  135. login, err := s.checkCredentials(authId[5:])
  136. if err != nil {
  137. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  138. } else {
  139. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  140. }
  141. continueState = ContinueStateNone
  142. continue
  143. }
  144. }
  145. fmt.Fprintf(conn, "%s\t%s\t%s\n", Cont, ids[1], base64.StdEncoding.EncodeToString([]byte("Username:")))
  146. continueState = ContinueStateCredentials
  147. case Cont:
  148. if len(ids) < 2 {
  149. break
  150. }
  151. if continueState == ContinueStateCredentials {
  152. if len(ids) < 3 {
  153. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid base64 data")
  154. return
  155. }
  156. login, err := s.checkCredentials(ids[2])
  157. if err != nil {
  158. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], err.Error())
  159. } else {
  160. fmt.Fprintf(conn, "%s\t%s\tuser=%s\n", Ok, ids[1], login)
  161. }
  162. continueState = ContinueStateNone
  163. } else {
  164. fmt.Fprintf(conn, "%s\t%s\treason=%s\n", Fail, ids[1], "invalid user or password")
  165. }
  166. }
  167. }
  168. }
  169. func (s *SaslServer) checkCredentials(credentialsBase64 string) (string, error) {
  170. credentials, err := base64.StdEncoding.DecodeString(credentialsBase64)
  171. if err != nil {
  172. return "", errors.New("invalid base64 data")
  173. }
  174. credentialList := bytes.Split(credentials, []byte{0})
  175. if len(credentialList) < 3 {
  176. return "", errors.New("invalid user or password")
  177. }
  178. identity := string(credentialList[0])
  179. login := string(credentialList[1])
  180. password := string(credentialList[2])
  181. if identity == "token" {
  182. if s.authenticator.Verify(login, password) {
  183. return login, nil
  184. }
  185. } else {
  186. if err := s.authenticator.CheckUser(login, password); err == nil {
  187. return login, nil
  188. }
  189. }
  190. return "", errors.New("invalid user or password")
  191. }