sasl.go 5.1 KB

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