gssapi_kerberos.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package sarama
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "time"
  8. "github.com/jcmturner/gofork/encoding/asn1"
  9. "gopkg.in/jcmturner/gokrb5.v7/asn1tools"
  10. "gopkg.in/jcmturner/gokrb5.v7/gssapi"
  11. "gopkg.in/jcmturner/gokrb5.v7/iana/chksumtype"
  12. "gopkg.in/jcmturner/gokrb5.v7/iana/keyusage"
  13. "gopkg.in/jcmturner/gokrb5.v7/messages"
  14. "gopkg.in/jcmturner/gokrb5.v7/types"
  15. )
  16. const (
  17. TOK_ID_KRB_AP_REQ = 256
  18. GSS_API_GENERIC_TAG = 0x60
  19. KRB5_USER_AUTH = 1
  20. KRB5_KEYTAB_AUTH = 2
  21. GSS_API_INITIAL = 1
  22. GSS_API_VERIFY = 2
  23. GSS_API_FINISH = 3
  24. )
  25. type GSSAPIConfig struct {
  26. AuthType int
  27. KeyTabPath string
  28. KerberosConfigPath string
  29. ServiceName string
  30. Username string
  31. Password string
  32. Realm string
  33. DisablePAFXFAST bool
  34. }
  35. type GSSAPIKerberosAuth struct {
  36. Config *GSSAPIConfig
  37. ticket messages.Ticket
  38. encKey types.EncryptionKey
  39. NewKerberosClientFunc func(config *GSSAPIConfig) (KerberosClient, error)
  40. step int
  41. }
  42. type KerberosClient interface {
  43. Login() error
  44. GetServiceTicket(spn string) (messages.Ticket, types.EncryptionKey, error)
  45. Domain() string
  46. CName() types.PrincipalName
  47. Destroy()
  48. }
  49. /*
  50. *
  51. * Appends length in big endian before payload, and send it to kafka
  52. *
  53. */
  54. func (krbAuth *GSSAPIKerberosAuth) writePackage(broker *Broker, payload []byte) (int, error) {
  55. length := len(payload)
  56. finalPackage := make([]byte, length+4) //4 byte length header + payload
  57. copy(finalPackage[4:], payload)
  58. binary.BigEndian.PutUint32(finalPackage, uint32(length))
  59. bytes, err := broker.conn.Write(finalPackage)
  60. if err != nil {
  61. return bytes, err
  62. }
  63. return bytes, nil
  64. }
  65. /*
  66. *
  67. * Read length (4 bytes) and then read the payload
  68. *
  69. */
  70. func (krbAuth *GSSAPIKerberosAuth) readPackage(broker *Broker) ([]byte, int, error) {
  71. bytesRead := 0
  72. lengthInBytes := make([]byte, 4)
  73. bytes, err := io.ReadFull(broker.conn, lengthInBytes)
  74. if err != nil {
  75. return nil, bytesRead, err
  76. }
  77. bytesRead += bytes
  78. payloadLength := binary.BigEndian.Uint32(lengthInBytes)
  79. payloadBytes := make([]byte, payloadLength) // buffer for read..
  80. bytes, err = io.ReadFull(broker.conn, payloadBytes) // read bytes
  81. if err != nil {
  82. return payloadBytes, bytesRead, err
  83. }
  84. bytesRead += bytes
  85. return payloadBytes, bytesRead, nil
  86. }
  87. func (krbAuth *GSSAPIKerberosAuth) newAuthenticatorChecksum() []byte {
  88. a := make([]byte, 24)
  89. flags := []int{gssapi.ContextFlagInteg, gssapi.ContextFlagConf}
  90. binary.LittleEndian.PutUint32(a[:4], 16)
  91. for _, i := range flags {
  92. f := binary.LittleEndian.Uint32(a[20:24])
  93. f |= uint32(i)
  94. binary.LittleEndian.PutUint32(a[20:24], f)
  95. }
  96. return a
  97. }
  98. /*
  99. *
  100. * Construct Kerberos AP_REQ package, conforming to RFC-4120
  101. * https://tools.ietf.org/html/rfc4120#page-84
  102. *
  103. */
  104. func (krbAuth *GSSAPIKerberosAuth) createKrb5Token(
  105. domain string, cname types.PrincipalName,
  106. ticket messages.Ticket,
  107. sessionKey types.EncryptionKey) ([]byte, error) {
  108. auth, err := types.NewAuthenticator(domain, cname)
  109. if err != nil {
  110. return nil, err
  111. }
  112. auth.Cksum = types.Checksum{
  113. CksumType: chksumtype.GSSAPI,
  114. Checksum: krbAuth.newAuthenticatorChecksum(),
  115. }
  116. APReq, err := messages.NewAPReq(
  117. ticket,
  118. sessionKey,
  119. auth,
  120. )
  121. if err != nil {
  122. return nil, err
  123. }
  124. aprBytes := make([]byte, 2)
  125. binary.BigEndian.PutUint16(aprBytes, TOK_ID_KRB_AP_REQ)
  126. tb, err := APReq.Marshal()
  127. if err != nil {
  128. return nil, err
  129. }
  130. aprBytes = append(aprBytes, tb...)
  131. return aprBytes, nil
  132. }
  133. /*
  134. *
  135. * Append the GSS-API header to the payload, conforming to RFC-2743
  136. * Section 3.1, Mechanism-Independent Token Format
  137. *
  138. * https://tools.ietf.org/html/rfc2743#page-81
  139. *
  140. * GSSAPIHeader + <specific mechanism payload>
  141. *
  142. */
  143. func (krbAuth *GSSAPIKerberosAuth) appendGSSAPIHeader(payload []byte) ([]byte, error) {
  144. oidBytes, err := asn1.Marshal(gssapi.OID(gssapi.OIDKRB5))
  145. if err != nil {
  146. return nil, err
  147. }
  148. tkoLengthBytes := asn1tools.MarshalLengthBytes(len(oidBytes) + len(payload))
  149. GSSHeader := append([]byte{GSS_API_GENERIC_TAG}, tkoLengthBytes...)
  150. GSSHeader = append(GSSHeader, oidBytes...)
  151. GSSPackage := append(GSSHeader, payload...)
  152. return GSSPackage, nil
  153. }
  154. func (krbAuth *GSSAPIKerberosAuth) initSecContext(bytes []byte, kerberosClient KerberosClient) ([]byte, error) {
  155. switch krbAuth.step {
  156. case GSS_API_INITIAL:
  157. aprBytes, err := krbAuth.createKrb5Token(
  158. kerberosClient.Domain(),
  159. kerberosClient.CName(),
  160. krbAuth.ticket,
  161. krbAuth.encKey)
  162. if err != nil {
  163. return nil, err
  164. }
  165. krbAuth.step = GSS_API_VERIFY
  166. return krbAuth.appendGSSAPIHeader(aprBytes)
  167. case GSS_API_VERIFY:
  168. wrapTokenReq := gssapi.WrapToken{}
  169. if err := wrapTokenReq.Unmarshal(bytes, true); err != nil {
  170. return nil, err
  171. }
  172. // Validate response.
  173. isValid, err := wrapTokenReq.Verify(krbAuth.encKey, keyusage.GSSAPI_ACCEPTOR_SEAL)
  174. if !isValid {
  175. return nil, err
  176. }
  177. wrapTokenResponse, err := gssapi.NewInitiatorWrapToken(wrapTokenReq.Payload, krbAuth.encKey)
  178. if err != nil {
  179. return nil, err
  180. }
  181. krbAuth.step = GSS_API_FINISH
  182. return wrapTokenResponse.Marshal()
  183. }
  184. return nil, nil
  185. }
  186. /* This does the handshake for authorization */
  187. func (krbAuth *GSSAPIKerberosAuth) Authorize(broker *Broker) error {
  188. kerberosClient, err := krbAuth.NewKerberosClientFunc(krbAuth.Config)
  189. if err != nil {
  190. Logger.Printf("Kerberos client error: %s", err)
  191. return err
  192. }
  193. err = kerberosClient.Login()
  194. if err != nil {
  195. Logger.Printf("Kerberos client error: %s", err)
  196. return err
  197. }
  198. // Construct SPN using serviceName and host
  199. // SPN format: <SERVICE>/<FQDN>
  200. host := strings.SplitN(broker.addr, ":", 2)[0] // Strip port part
  201. spn := fmt.Sprintf("%s/%s", broker.conf.Net.SASL.GSSAPI.ServiceName, host)
  202. ticket, encKey, err := kerberosClient.GetServiceTicket(spn)
  203. if err != nil {
  204. Logger.Printf("Error getting Kerberos service ticket : %s", err)
  205. return err
  206. }
  207. krbAuth.ticket = ticket
  208. krbAuth.encKey = encKey
  209. krbAuth.step = GSS_API_INITIAL
  210. var receivedBytes []byte = nil
  211. defer kerberosClient.Destroy()
  212. for {
  213. packBytes, err := krbAuth.initSecContext(receivedBytes, kerberosClient)
  214. if err != nil {
  215. Logger.Printf("Error while performing GSSAPI Kerberos Authentication: %s\n", err)
  216. return err
  217. }
  218. requestTime := time.Now()
  219. bytesWritten, err := krbAuth.writePackage(broker, packBytes)
  220. if err != nil {
  221. Logger.Printf("Error while performing GSSAPI Kerberos Authentication: %s\n", err)
  222. return err
  223. }
  224. broker.updateOutgoingCommunicationMetrics(bytesWritten)
  225. if krbAuth.step == GSS_API_VERIFY {
  226. bytesRead := 0
  227. receivedBytes, bytesRead, err = krbAuth.readPackage(broker)
  228. requestLatency := time.Since(requestTime)
  229. broker.updateIncomingCommunicationMetrics(bytesRead, requestLatency)
  230. if err != nil {
  231. Logger.Printf("Error while performing GSSAPI Kerberos Authentication: %s\n", err)
  232. return err
  233. }
  234. } else if krbAuth.step == GSS_API_FINISH {
  235. return nil
  236. }
  237. }
  238. }