example_whitelist.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net"
  8. "net/http"
  9. "github.com/cloudflare/cfssl/whitelist"
  10. )
  11. var wl = whitelist.NewBasic()
  12. func addIP(w http.ResponseWriter, r *http.Request) {
  13. addr := r.FormValue("ip")
  14. ip := net.ParseIP(addr)
  15. wl.Add(ip)
  16. log.Printf("request to add %s to the whitelist", addr)
  17. w.Write([]byte(fmt.Sprintf("Added %s to whitelist.\n", addr)))
  18. }
  19. func delIP(w http.ResponseWriter, r *http.Request) {
  20. addr := r.FormValue("ip")
  21. ip := net.ParseIP(addr)
  22. wl.Remove(ip)
  23. log.Printf("request to remove %s from the whitelist", addr)
  24. w.Write([]byte(fmt.Sprintf("Removed %s from whitelist.\n", ip)))
  25. }
  26. func dumpWhitelist(w http.ResponseWriter, r *http.Request) {
  27. out, err := json.Marshal(wl)
  28. if err != nil {
  29. http.Error(w, err.Error(), http.StatusInternalServerError)
  30. } else {
  31. w.Write(out)
  32. }
  33. }
  34. type handler struct {
  35. h func(http.ResponseWriter, *http.Request)
  36. }
  37. func newHandler(h func(w http.ResponseWriter, r *http.Request)) http.Handler {
  38. return &handler{h: h}
  39. }
  40. func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  41. h.h(w, r)
  42. }
  43. func main() {
  44. root := flag.String("root", "files/", "file server root")
  45. flag.Parse()
  46. fileServer := http.StripPrefix("/files/",
  47. http.FileServer(http.Dir(*root)))
  48. wl.Add(net.IP{127, 0, 0, 1})
  49. adminWL := whitelist.NewBasic()
  50. adminWL.Add(net.IP{127, 0, 0, 1})
  51. adminWL.Add(net.ParseIP("::1"))
  52. protFiles, err := whitelist.NewHandler(fileServer, nil, wl)
  53. if err != nil {
  54. log.Fatalf("%v", err)
  55. }
  56. addHandler, err := whitelist.NewHandlerFunc(addIP, nil, adminWL)
  57. if err != nil {
  58. log.Fatalf("%v", err)
  59. }
  60. delHandler, err := whitelist.NewHandlerFunc(delIP, nil, adminWL)
  61. if err != nil {
  62. log.Fatalf("%v", err)
  63. }
  64. dumpHandler, err := whitelist.NewHandlerFunc(dumpWhitelist, nil, adminWL)
  65. if err != nil {
  66. log.Fatalf("%v", err)
  67. }
  68. http.Handle("/files/", protFiles)
  69. http.Handle("/add", addHandler)
  70. http.Handle("/del", delHandler)
  71. http.Handle("/dump", dumpHandler)
  72. log.Println("Serving files on :8080")
  73. log.Fatal(http.ListenAndServe(":8080", nil))
  74. }