http_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package spnego
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "mime/multipart"
  11. "net/http"
  12. "net/http/httptest"
  13. "os"
  14. "sync"
  15. "testing"
  16. "github.com/stretchr/testify/assert"
  17. "gopkg.in/jcmturner/goidentity.v3"
  18. "gopkg.in/jcmturner/gokrb5.v7/client"
  19. "gopkg.in/jcmturner/gokrb5.v7/config"
  20. "gopkg.in/jcmturner/gokrb5.v7/keytab"
  21. "gopkg.in/jcmturner/gokrb5.v7/service"
  22. "gopkg.in/jcmturner/gokrb5.v7/test"
  23. "gopkg.in/jcmturner/gokrb5.v7/test/testdata"
  24. )
  25. func TestClient_SetSPNEGOHeader(t *testing.T) {
  26. test.Integration(t)
  27. b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
  28. kt := keytab.New()
  29. kt.Unmarshal(b)
  30. c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
  31. addr := os.Getenv("TEST_KDC_ADDR")
  32. if addr == "" {
  33. addr = testdata.TEST_KDC_ADDR
  34. }
  35. c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
  36. l := log.New(os.Stderr, "SPNEGO Client:", log.LstdFlags)
  37. cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c, client.Logger(l))
  38. err := cl.Login()
  39. if err != nil {
  40. t.Fatalf("error on AS_REQ: %v\n", err)
  41. }
  42. urls := []string{
  43. "http://cname.test.gokrb5",
  44. "http://host.test.gokrb5",
  45. }
  46. paths := []string{
  47. "/modkerb/index.html",
  48. //"/modgssapi/index.html",
  49. }
  50. for _, url := range urls {
  51. for _, p := range paths {
  52. r, _ := http.NewRequest("GET", url+p, nil)
  53. httpResp, err := http.DefaultClient.Do(r)
  54. if err != nil {
  55. t.Fatalf("%s request error: %v", url+p, err)
  56. }
  57. assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected")
  58. err = SetSPNEGOHeader(cl, r, "")
  59. if err != nil {
  60. t.Fatalf("error setting client SPNEGO header: %v", err)
  61. }
  62. httpResp, err = http.DefaultClient.Do(r)
  63. if err != nil {
  64. t.Fatalf("%s request error: %v\n", url+p, err)
  65. }
  66. assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
  67. }
  68. }
  69. }
  70. func TestSPNEGOHTTPClient(t *testing.T) {
  71. test.Integration(t)
  72. b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
  73. kt := keytab.New()
  74. kt.Unmarshal(b)
  75. c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
  76. addr := os.Getenv("TEST_KDC_ADDR")
  77. if addr == "" {
  78. addr = testdata.TEST_KDC_ADDR
  79. }
  80. c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
  81. l := log.New(os.Stderr, "SPNEGO Client:", log.LstdFlags)
  82. cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c, client.Logger(l))
  83. err := cl.Login()
  84. if err != nil {
  85. t.Fatalf("error on AS_REQ: %v\n", err)
  86. }
  87. urls := []string{
  88. "http://cname.test.gokrb5",
  89. "http://host.test.gokrb5",
  90. }
  91. // This path issues a redirect which the http client will automatically follow.
  92. // It should cause a replay issue if the negInit token is sent in the first instance.
  93. paths := []string{
  94. "/modgssapi", // This issues a redirect which the http client will automatically follow. Could cause a replay issue
  95. "/redirect",
  96. }
  97. for _, url := range urls {
  98. for _, p := range paths {
  99. r, _ := http.NewRequest("GET", url+p, nil)
  100. httpCl := http.DefaultClient
  101. httpCl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  102. t.Logf("http client redirect: %+v", *req)
  103. return nil
  104. }
  105. spnegoCl := NewClient(cl, httpCl, "")
  106. httpResp, err := spnegoCl.Do(r)
  107. if err != nil {
  108. t.Fatalf("%s request error: %v", url+p, err)
  109. }
  110. assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
  111. }
  112. }
  113. }
  114. func TestService_SPNEGOKRB_NoAuthHeader(t *testing.T) {
  115. s := httpServer()
  116. defer s.Close()
  117. r, _ := http.NewRequest("GET", s.URL, nil)
  118. httpResp, err := http.DefaultClient.Do(r)
  119. if err != nil {
  120. t.Fatalf("Request error: %v\n", err)
  121. }
  122. assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected")
  123. assert.Equal(t, "Negotiate", httpResp.Header.Get("WWW-Authenticate"), "Negotiation header not set by server.")
  124. }
  125. func TestService_SPNEGOKRB_ValidUser(t *testing.T) {
  126. test.Integration(t)
  127. s := httpServer()
  128. defer s.Close()
  129. r, _ := http.NewRequest("GET", s.URL, nil)
  130. cl := getClient()
  131. err := SetSPNEGOHeader(cl, r, "HTTP/host.test.gokrb5")
  132. if err != nil {
  133. t.Fatalf("error setting client's SPNEGO header: %v", err)
  134. }
  135. httpResp, err := http.DefaultClient.Do(r)
  136. if err != nil {
  137. t.Fatalf("Request error: %v\n", err)
  138. }
  139. assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
  140. }
  141. func TestService_SPNEGOKRB_Replay(t *testing.T) {
  142. test.Integration(t)
  143. s := httpServer()
  144. defer s.Close()
  145. r1, _ := http.NewRequest("GET", s.URL, nil)
  146. cl := getClient()
  147. err := SetSPNEGOHeader(cl, r1, "HTTP/host.test.gokrb5")
  148. if err != nil {
  149. t.Fatalf("error setting client's SPNEGO header: %v", err)
  150. }
  151. // First request with this ticket should be accepted
  152. httpResp, err := http.DefaultClient.Do(r1)
  153. if err != nil {
  154. t.Fatalf("Request error: %v\n", err)
  155. }
  156. assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
  157. // Use ticket again should be rejected
  158. httpResp, err = http.DefaultClient.Do(r1)
  159. if err != nil {
  160. t.Fatalf("Request error: %v\n", err)
  161. }
  162. assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
  163. // Form a 2nd ticket
  164. r2, _ := http.NewRequest("GET", s.URL, nil)
  165. err = SetSPNEGOHeader(cl, r2, "HTTP/host.test.gokrb5")
  166. if err != nil {
  167. t.Fatalf("error setting client's SPNEGO header: %v", err)
  168. }
  169. // First use of 2nd ticket should be accepted
  170. httpResp, err = http.DefaultClient.Do(r2)
  171. if err != nil {
  172. t.Fatalf("Request error: %v\n", err)
  173. }
  174. assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
  175. // Using the 1st ticket again should still be rejected
  176. httpResp, err = http.DefaultClient.Do(r1)
  177. if err != nil {
  178. t.Fatalf("Request error: %v\n", err)
  179. }
  180. assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
  181. // Using the 2nd again should be rejected as replay
  182. httpResp, err = http.DefaultClient.Do(r2)
  183. if err != nil {
  184. t.Fatalf("Request error: %v\n", err)
  185. }
  186. assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
  187. }
  188. func TestService_SPNEGOKRB_ReplayCache_Concurrency(t *testing.T) {
  189. test.Integration(t)
  190. s := httpServer()
  191. defer s.Close()
  192. r1, _ := http.NewRequest("GET", s.URL, nil)
  193. cl := getClient()
  194. err := SetSPNEGOHeader(cl, r1, "HTTP/host.test.gokrb5")
  195. if err != nil {
  196. t.Fatalf("error setting client's SPNEGO header: %v", err)
  197. }
  198. r2, _ := http.NewRequest("GET", s.URL, nil)
  199. err = SetSPNEGOHeader(cl, r2, "HTTP/host.test.gokrb5")
  200. if err != nil {
  201. t.Fatalf("error setting client's SPNEGO header: %v", err)
  202. }
  203. // Concurrent 1st requests should be OK
  204. var wg sync.WaitGroup
  205. wg.Add(2)
  206. go httpGet(r1, &wg)
  207. go httpGet(r2, &wg)
  208. wg.Wait()
  209. // A number of concurrent requests with the same ticket should be rejected due to replay
  210. var wg2 sync.WaitGroup
  211. noReq := 10
  212. wg2.Add(noReq * 2)
  213. for i := 0; i < noReq; i++ {
  214. go httpGet(r1, &wg2)
  215. go httpGet(r2, &wg2)
  216. }
  217. wg2.Wait()
  218. }
  219. func TestService_SPNEGOKRB_Upload(t *testing.T) {
  220. test.Integration(t)
  221. s := httpServer()
  222. defer s.Close()
  223. bodyBuf := &bytes.Buffer{}
  224. bodyWriter := multipart.NewWriter(bodyBuf)
  225. fileWriter, err := bodyWriter.CreateFormFile("uploadfile", "testfile.bin")
  226. if err != nil {
  227. t.Fatalf("error writing to buffer: %v", err)
  228. }
  229. data := make([]byte, 10240)
  230. rand.Read(data)
  231. br := bytes.NewReader(data)
  232. _, err = io.Copy(fileWriter, br)
  233. if err != nil {
  234. t.Fatalf("error copying bytes: %v", err)
  235. }
  236. bodyWriter.Close()
  237. r, _ := http.NewRequest("POST", s.URL, bodyBuf)
  238. r.Header.Set("Content-Type", bodyWriter.FormDataContentType())
  239. cl := getClient()
  240. spnegoCl := NewClient(cl, nil, "HTTP/host.test.gokrb5")
  241. httpResp, err := spnegoCl.Do(r)
  242. if err != nil {
  243. t.Fatalf("Request error: %v\n", err)
  244. }
  245. if httpResp.StatusCode != http.StatusOK {
  246. bodyBytes, _ := ioutil.ReadAll(httpResp.Body)
  247. bodyString := string(bodyBytes)
  248. httpResp.Body.Close()
  249. t.Errorf("unexpected code from http server (%d): %s", httpResp.StatusCode, bodyString)
  250. }
  251. }
  252. func httpGet(r *http.Request, wg *sync.WaitGroup) {
  253. defer wg.Done()
  254. http.DefaultClient.Do(r)
  255. }
  256. func httpServer() *httptest.Server {
  257. l := log.New(os.Stderr, "GOKRB5 Service Tests: ", log.Ldate|log.Ltime|log.Lshortfile)
  258. b, _ := hex.DecodeString(testdata.HTTP_KEYTAB)
  259. kt := keytab.New()
  260. kt.Unmarshal(b)
  261. th := http.HandlerFunc(testAppHandler)
  262. s := httptest.NewServer(SPNEGOKRB5Authenticate(th, kt, service.Logger(l)))
  263. return s
  264. }
  265. func testAppHandler(w http.ResponseWriter, r *http.Request) {
  266. if r.Method == http.MethodPost {
  267. maxUploadSize := int64(11240)
  268. if err := r.ParseMultipartForm(maxUploadSize); err != nil {
  269. http.Error(w, fmt.Sprintf("cannot parse multipart form: %v", err), http.StatusBadRequest)
  270. return
  271. }
  272. r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
  273. file, _, err := r.FormFile("uploadfile")
  274. if err != nil {
  275. http.Error(w, "INVALID_FILE", http.StatusBadRequest)
  276. return
  277. }
  278. defer file.Close()
  279. // write out to /dev/null
  280. _, err = io.Copy(ioutil.Discard, file)
  281. if err != nil {
  282. http.Error(w, "WRITE_ERR", http.StatusInternalServerError)
  283. return
  284. }
  285. }
  286. w.WriteHeader(http.StatusOK)
  287. ctx := r.Context()
  288. fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>",
  289. ctx.Value(CTXKeyCredentials).(goidentity.Identity).UserName(),
  290. ctx.Value(CTXKeyCredentials).(goidentity.Identity).Domain())
  291. return
  292. }
  293. func getClient() *client.Client {
  294. b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
  295. kt := keytab.New()
  296. kt.Unmarshal(b)
  297. c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
  298. c.LibDefaults.NoAddresses = true
  299. addr := os.Getenv("TEST_KDC_ADDR")
  300. if addr == "" {
  301. addr = testdata.TEST_KDC_ADDR
  302. }
  303. c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
  304. c.Realms[0].KPasswdServer = []string{addr + ":464"}
  305. cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c)
  306. return cl
  307. }