Пример #1
0
func main() {
	server := web.NewServer()
	server.Get("/", myHandler)
	server.Post("/", myHandler)

	http.ListenAndServe(":8000", nosurf.New(server))
}
Пример #2
0
func main() {
	goji.Get("/", IndexHandler) // Doesn't need CSRF protection (no POST/PUT/DELETE actions).

	signup := web.New()
	goji.Handle("/signup/*", signup)
	// But our signup forms do, so we add nosurf to their middleware stack (only).
	signup.Use(nosurf.NewPure)
	signup.Get("/signup/new", ShowSignupForm)
	signup.Post("/signup/submit", SubmitSignupForm)

	admin := web.New()
	// A more advanced example: we enforce secure cookies (HTTPS only),
	// set a domain and keep the expiry time low.
	a := nosurf.New(admin)
	a.SetBaseCookie(http.Cookie{
		Name:     "csrf_token",
		Domain:   "localhost",
		Path:     "/admin",
		MaxAge:   3600 * 4,
		HttpOnly: true,
		Secure:   true,
	})

	// Our /admin/* routes now have CSRF protection.
	goji.Handle("/admin/*", a)

	goji.Serve()
}
Пример #3
0
func nosurfing(h http.Handler) http.Handler {
	surfing := nosurf.New(h)
	surfing.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println("Failed to validate XSRF Token:", nosurf.Reason(r))
		w.WriteHeader(http.StatusBadRequest)
	}))
	return surfing
}
Пример #4
0
// WithCsrfHandler is a middleware wrapper providing CSRF validation
func WithCsrfHandler(h http.Handler) http.Handler {
	csrfHandler := nosurf.New(h)
	csrfHandler.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		rsn := nosurf.Reason(req).Error()
		log.DebugR(req, "failed csrf validation", log.Data{"reason": rsn})
		HTML(w, http.StatusBadRequest, "error", map[string]interface{}{"error": rsn})
	}))
	return csrfHandler
}
Пример #5
0
// CreateAdminRouter creates the routes for handling requests to the web interface.
// This function returns an http.Handler to be used in http.ListenAndServe().
func CreateAdminRouter() http.Handler {
	router := mux.NewRouter()
	// Base Front-end routes
	router.HandleFunc("/", Use(Base, mid.RequireLogin))
	router.HandleFunc("/login", Login)
	router.HandleFunc("/logout", Use(Logout, mid.RequireLogin))
	router.HandleFunc("/campaigns", Use(Campaigns, mid.RequireLogin))
	router.HandleFunc("/campaigns/{id:[0-9]+}", Use(CampaignID, mid.RequireLogin))
	router.HandleFunc("/templates", Use(Templates, mid.RequireLogin))
	router.HandleFunc("/users", Use(Users, mid.RequireLogin))
	router.HandleFunc("/landing_pages", Use(LandingPages, mid.RequireLogin))
	router.HandleFunc("/sending_profiles", Use(SendingProfiles, mid.RequireLogin))
	router.HandleFunc("/register", Use(Register, mid.RequireLogin))
	router.HandleFunc("/settings", Use(Settings, mid.RequireLogin))
	// Create the API routes
	api := router.PathPrefix("/api").Subrouter()
	api = api.StrictSlash(true)
	api.HandleFunc("/", Use(API, mid.RequireLogin))
	api.HandleFunc("/reset", Use(API_Reset, mid.RequireLogin))
	api.HandleFunc("/campaigns/", Use(API_Campaigns, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}", Use(API_Campaigns_Id, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}/results", Use(API_Campaigns_Id_Results, mid.RequireAPIKey))
	api.HandleFunc("/campaigns/{id:[0-9]+}/complete", Use(API_Campaigns_Id_Complete, mid.RequireAPIKey))
	api.HandleFunc("/groups/", Use(API_Groups, mid.RequireAPIKey))
	api.HandleFunc("/groups/{id:[0-9]+}", Use(API_Groups_Id, mid.RequireAPIKey))
	api.HandleFunc("/templates/", Use(API_Templates, mid.RequireAPIKey))
	api.HandleFunc("/templates/{id:[0-9]+}", Use(API_Templates_Id, mid.RequireAPIKey))
	api.HandleFunc("/pages/", Use(API_Pages, mid.RequireAPIKey))
	api.HandleFunc("/pages/{id:[0-9]+}", Use(API_Pages_Id, mid.RequireAPIKey))
	api.HandleFunc("/smtp/", Use(API_SMTP, mid.RequireAPIKey))
	api.HandleFunc("/smtp/{id:[0-9]+}", Use(API_SMTP_Id, mid.RequireAPIKey))
	api.HandleFunc("/util/send_test_email", Use(API_Send_Test_Email, mid.RequireAPIKey))
	api.HandleFunc("/import/group", API_Import_Group)
	api.HandleFunc("/import/email", API_Import_Email)
	api.HandleFunc("/import/site", API_Import_Site)

	// Setup static file serving
	router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))

	// Setup CSRF Protection
	csrfHandler := nosurf.New(router)
	// Exempt API routes and Static files
	csrfHandler.ExemptGlob("/api/campaigns")
	csrfHandler.ExemptGlob("/api/campaigns/*")
	csrfHandler.ExemptGlob("/api/groups")
	csrfHandler.ExemptGlob("/api/groups/*")
	csrfHandler.ExemptGlob("/api/templates")
	csrfHandler.ExemptGlob("/api/templates/*")
	csrfHandler.ExemptGlob("/api/pages")
	csrfHandler.ExemptGlob("/api/pages/*")
	csrfHandler.ExemptGlob("/api/smtp")
	csrfHandler.ExemptGlob("/api/smtp/*")
	csrfHandler.ExemptGlob("/api/import/*")
	csrfHandler.ExemptGlob("/api/util/*")
	csrfHandler.ExemptGlob("/static/*")
	return Use(csrfHandler.ServeHTTP, mid.GetContext)
}
Пример #6
0
func New(handler http.Handler) http.Handler {
	n := nosurf.New(handler)
	n.SetFailureHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		b := base.New(rw, r, false)
		b.SetTitle("text11")
		b.RenderContentPart(vioTmpl, nil)
		b.Render()
	}))

	return n
}
Пример #7
0
func Start(DB *Connection, config *Config) {
	// Create a new cookie store
	store := sessions.NewCookieStore([]byte(config.SecretKey))

	m := martini.Classic()

	// It will be available to all handlers as *sessions.CookieStore
	m.Map(store)

	// It will be available to all handlers as *connection *Connection
	m.Map(DB)

	// It will be available to all handlers as *Config
	m.Map(config)

	// public folder will serve the static content
	m.Use(martini.Static("public"))

	// Tag-related routes
	m.Get("/tag/:tag/:page", AuthRequired, GetTagHandler)

	// Bookmark-related routes
	m.Get("/bookmarks/:page", AuthRequired, GetBookmarksHandler)
	m.Post("/bookmark/new", AuthRequired, NewBookmarkHandler)
	m.Post("/bookmark/update/:bookmark", AuthRequired, EditBookmarkHandler)
	m.Delete("/bookmark/delete/:bookmark", AuthRequired, DeleteBookmarkHandler)

	// Search
	m.Post("/search/:page", AuthRequired, SearchHandler)

	// User-related routes
	m.Post("/login", LoginPostHandler)
	m.Get("/logout", AuthRequired, LogoutHandler)
	m.Post("/signup", SignUpHandler)
	m.Post("/new_token", AuthRequired, RequestNewToken)

	// Test
	m.Get("/test", TestHandler)

	// Home
	m.Get("/", func(cs *sessions.CookieStore, req *http.Request, w http.ResponseWriter, connection *Connection) {
		if GetUserID(cs, req, connection) == "" {
			LoginHandler(req, w)
		}
	}, IndexHandler)

	csrfHandler := nosurf.New(m)
	csrfHandler.SetFailureHandler(http.HandlerFunc(CsrfFailHandler))

	http.ListenAndServe(config.Port, csrfHandler)
}
Пример #8
0
Файл: web.go Проект: robvdl/gcms
// runWeb is an starts the GIN application
func runWeb(ctx *cli.Context) {
	r := gin.Default()
	r.HTMLRender = pongo2gin.Default() // Use Pongo2 for templates

	setupMiddleware(r)
	setupRoutes(r)

	// Initialise nosurf for csrf token support.
	csrfHandler := nosurf.New(r)
	csrfHandler.SetFailureHandler(http.HandlerFunc(csrfFailed))
	csrfHandler.ExemptRegexp("/api/(.*)") // ignore API urls for the time being

	// Start the Gin application with nosurf (for csrf protection).
	// This is an alternative way to start up the Gin application.
	http.ListenAndServe(":"+config.Config.Port, csrfHandler)
}
Пример #9
0
func main() {
	/*
	   myHandler := http.HandlerFunc(myFunc)
	   fmt.Println("Listening on http://127.0.0.1:8000/")
	   http.ListenAndServe(":8000", nosurf.New(myHandler))
	*/

	myHandler := http.HandlerFunc(myFunc)
	http.HandleFunc("/", nosurf.New(myHandler))
	fmt.Println("Listening on http://127.0.0.1:8000/")
	http.ListenAndServe(":8000", nil)

	/*
			http.HandleFunc("/", nosurf.New(myFunc))
		    fmt.Println("Listening on http://127.0.0.1:8000/")

		    http.ListenAndServe(":8000", nil)
	*/

}
Пример #10
0
// CsrfMiddleware adds CSRF support via nosurf.
func CsrfMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	var token string
	var passed bool

	// nosurf disposes of the token as soon as it calls the http.Handler you provide...
	// in order to use it as negroni middleware, pull out token and dispose of it ourselves
	csrfHandler := nosurf.New(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		token = nosurf.Token(r)
		passed = true
	}))
	csrfHandler.ExemptRegexp("/v1(.*)")
	csrfHandler.ServeHTTP(w, r)

	// csrf passed
	if passed {
		context.Set(r, "csrf_token", token)
		next(w, r)
		context.Delete(r, "csrf_token")
	}
}
Пример #11
0
func main() {
	http.HandleFunc("/", Index)

	// when you route urls with .Handle[Func]() they end up on DefaultServeMux
	csrfHandler := nosurf.New(http.DefaultServeMux)

	// exempting by an exact path...
	// won't exempt /faq/question-1
	csrfHandler.ExemptPath("/faq")

	// exempting by a glob
	// will exempt /post, /post1, /post2, etc.
	// won't exempt /post1/comments, as * stops at a /
	csrfHandler.ExemptGlob("/post*")

	// exempting by a regexp
	// will exempt /static, /static/, /static/favicon.ico, /static/css/style.css, etc.
	csrfHandler.ExemptRegexp("/static(.*)")

	// setting the failureHandler. Will call this in case the CSRF check fails.
	csrfHandler.SetFailureHandler(http.HandlerFunc(failHand))

	http.ListenAndServe(":8000", csrfHandler)
}
Пример #12
0
// Nosurf is a wrapper for justinas' csrf protection middleware
func Nosurf() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return nosurf.New(next)
	}
}
Пример #13
0
func main() {
	var port string

	hostname, err := os.Hostname()
	if err != nil {
		fmt.Println("Error getting hostname:", err)
	}

	if hostname == "pythia" {
		port = ":80"
	} else {
		port = ":8080"
	}

	fieldsToIndex := make(map[string][]string)
	fieldsToIndex["answers"] = []string{"tags"}
	fieldsToIndex["users"] = []string{"login"}

	db, err := ivy.OpenDB("data", fieldsToIndex)
	if err != nil {
		fmt.Println("Database initialization failed:", err)
	}

	defer db.Close()

	store := sessions.NewCookieStore([]byte("pythia-is-awesome"))

	gv := global_vars.GlobalVars{MyDB: db, SessionStore: store}

	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	r := mux.NewRouter()
	r.HandleFunc("/", makeHandler(answers_handler.Index, &gv)).Methods("GET")

	r.HandleFunc("/answers", makeHandler(answers_handler.Index, &gv)).Methods("GET")
	r.HandleFunc("/answers/search", makeHandler(answers_handler.Index, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}", makeHandler(answers_handler.View, &gv)).Methods("GET")
	r.HandleFunc("/answers/new", makeHandler(answers_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/answers/create", makeHandler(answers_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}/edit", makeHandler(answers_handler.Edit, &gv)).Methods("GET")
	r.HandleFunc("/answers/update", makeHandler(answers_handler.Update, &gv)).Methods("POST")
	r.HandleFunc("/answers/{id:[0-9]+}/delete", makeHandler(answers_handler.Delete, &gv)).Methods("GET")
	r.HandleFunc("/answers/destroy", makeHandler(answers_handler.Destroy, &gv)).Methods("POST")

	r.HandleFunc("/users", makeHandler(users_handler.Index, &gv)).Methods("GET")
	r.HandleFunc("/users/{id:[0-9]+}", makeHandler(users_handler.View, &gv)).Methods("GET")
	r.HandleFunc("/users/new", makeHandler(users_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/users/create", makeHandler(users_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/users/{id:[0-9]+}/edit", makeHandler(users_handler.Edit, &gv)).Methods("GET")
	r.HandleFunc("/users/update", makeHandler(users_handler.Update, &gv)).Methods("POST")
	r.HandleFunc("/users/{id:[0-9]+}/delete", makeHandler(users_handler.Delete, &gv)).Methods("GET")
	r.HandleFunc("/users/destroy", makeHandler(users_handler.Destroy, &gv)).Methods("POST")

	r.HandleFunc("/logins/new", makeHandler(logins_handler.New, &gv)).Methods("GET")
	r.HandleFunc("/logins/create", makeHandler(logins_handler.Create, &gv)).Methods("POST")
	r.HandleFunc("/logout", makeHandler(logins_handler.Logout, &gv)).Methods("GET")

	http.Handle("/", r)

	csrfHandler := nosurf.New(http.DefaultServeMux)

	csrfHandler.SetFailureHandler(http.HandlerFunc(failHand))

	http.ListenAndServe(port, csrfHandler)
}
Пример #14
0
func main() {

	//SSH goroutine

	go func() {
		config := ssh.ServerConfig{
			PublicKeyCallback: keyAuth,
		}
		config.AddHostKey(hostPrivateKeySigner)

		port := strconv.Itoa(hostSSHPort)

		socket, err := net.Listen("tcp", ":"+port)
		if err != nil {
			panic(err)
		}

		for {
			conn, err := socket.Accept()
			if err != nil {
				panic(err)
			}

			// From a standard TCP connection to an encrypted SSH connection
			sshConn, chans, reqs, err := ssh.NewServerConn(conn, &config)
			if err != nil {
				log.Println("Error accepting ssh connection: ", err)
				continue
			}

			log.Println("Connection from", sshConn.RemoteAddr())

			// Print incoming out-of-band Requests
			go handleRequests(reqs)
			// Accept all channels
			go handleChannels(chans)
		}
	}()

	//

	// Garbage collecting goroutine
	// For testing, a stop-the-world gc using mutexes shall be 'nuff
	go func() {

		for {
			authRequestMap.Lock()

			for k, v := range authRequestMap.timestamps {

				killtime := time.Now().Add(-5 * time.Minute)

				if v.Before(killtime) {
					log.Debugf("Garbage collected key %s, %v old", k, time.Now().Sub(v))
					delete(authRequestMap.timestamps, k)
					delete(authRequestMap.matches, k)
				}

			}

			authRequestMap.Unlock()
			time.Sleep(2 * time.Minute)
		}

	}()

	templateStart, err = template.New("index.html").ParseFiles("index.html")
	if err != nil {
		panic(err)
	}

	templateAuth, err = template.New("auth.html").ParseFiles("auth.html")
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/auth", authRequestHandler)
	http.HandleFunc("/", startHandler)

	weblogOptions := &weblogs.Options{

		Writer: nil,
		Logger: customLogger{},
	}

	csrfHandler := nosurf.New(http.DefaultServeMux)

	csrfHandler.SetBaseCookie(http.Cookie{HttpOnly: true, Secure: sslEnabled})

	handler := context.ClearHandler(weblogs.HandlerWithOptions(csrfHandler, weblogOptions))

	if sslEnabled {
		go http.ListenAndServe(":"+strconv.Itoa(hostHTTPPort), handler)
		http.ListenAndServeTLS(":"+strconv.Itoa(hostTLSPort), sslCertPath, sslKeyPath, handler)
	} else {
		http.ListenAndServe(":"+strconv.Itoa(hostHTTPPort), handler)
	}
}
Пример #15
0
func main() {
	myHandler := http.HandlerFunc(myFunc)
	fmt.Println("Listening on http://127.0.0.1:8000/")
	http.ListenAndServe(":8000", nosurf.New(myHandler))
}
Пример #16
0
func StartWeb() {
	store = sessions.NewCookieStore([]byte(Config.CookieSecret))

	staticServer := http.FileServer(http.Dir("./static"))
	http.Handle("/static/", http.StripPrefix("/static/", staticServer))

	var templates *template.Template
	ParseTemplates := func() *template.Template {
		tmpls := template.New("")
		err := filepath.Walk("./template", func(path string, info os.FileInfo, err error) error {
			if err != nil || info.IsDir() || !strings.HasSuffix(path, ".html") {
				return err
			}

			relativePath, err := filepath.Rel("./template", path)
			if err != nil {
				return err
			}

			subtmpl, err := template.ParseFiles(path)
			if err != nil {
				return err
			}

			_, err = tmpls.AddParseTree(relativePath, subtmpl.Tree)
			return err
		})
		if err != nil {
			log.Fatalln("Couldn't load HTML templates:", err.Error())
		}
		return tmpls
	}
	LookupTemplate := func(name string) *template.Template {
		tmpl := templates.Lookup(name)
		if tmpl == nil {
			log.Fatalln("Couldn't find HTML template", name)
		}
		return tmpl
	}

	// If in Debug mode, re-parse templates with each request.
	if Config.Debug {
		getTemplate = func(name string) *template.Template {
			templates = ParseTemplates()
			return LookupTemplate(name)
		}
	} else {
		getTemplate = LookupTemplate
	}

	http.HandleFunc("/signin", WebSignIn)
	http.HandleFunc("/signout", WebSignOut)

	webThingHandler := RequireAccountFunc(WebThing)
	http.Handle("/thing/", webThingHandler)
	http.Handle("/player/", webThingHandler)
	http.Handle("/place/", webThingHandler)
	http.Handle("/action/", webThingHandler)
	http.Handle("/program/", webThingHandler)

	webThingMux = http.NewServeMux()
	webThingMux.HandleFunc("/", WebThingEdit)
	webThingMux.HandleFunc("/table", WebThingTable)
	webThingMux.HandleFunc("/program", WebThingProgram)
	webThingMux.HandleFunc("/access", WebThingAccess)

	http.Handle("/create-thing", RequireAccountFunc(WebCreateThing))

	indexHandler := RequireAccountFunc(WebIndex)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.String() != "/" {
			http.NotFound(w, r)
			return
		}
		indexHandler.ServeHTTP(w, r)
	})

	log.Println("Listening for web requests at address", Config.WebAddress)
	webHandler := context.ClearHandler(nosurf.New(http.DefaultServeMux))
	http.ListenAndServe(Config.WebAddress, webHandler)
}