Exemple #1
0
func startApp(port string) {
	// Load environment variables
	envVars := loadEnvVars()
	// Override with cloud foundry user provided service credentials if specified.
	loadUPSVars(&envVars)

	app, settings, err := controllers.InitApp(envVars)
	if err != nil {
		// Print the error.
		fmt.Println(err.Error())
		// Terminate the program with a non-zero value number.
		// Need this for testing purposes.
		os.Exit(1)
	}
	if settings.PProfEnabled {
		pprof.InitPProfRouter(app)
	}

	if envVars.NewRelicLicense != "" {
		fmt.Println("starting monitoring...")
		startMonitoring(envVars.NewRelicLicense)
	}

	fmt.Println("starting app now...")

	// TODO add better timeout message. By default it will just say "Timeout"
	protect := csrf.Protect([]byte(envVars.SessionKey), csrf.Secure(settings.SecureCookies))
	http.ListenAndServe(":"+port, protect(
		http.TimeoutHandler(context.ClearHandler(app), helpers.TimeoutConstant, ""),
	))
}
Exemple #2
0
func init() {
	//configs = my_local.Load_config(filepath.Join(getCurrentDir(), "config.json"))
	configs = my_config.Load_config("./config.json")
	//cookieHandler = securecookie.New(
	//	securecookie.GenerateRandomKey(32),
	//	securecookie.GenerateRandomKey(32))
	cookieHandler = securecookie.New(
		[]byte(configs.HashKey),
		[]byte(configs.BlockKey))
	CSRF = csrf.Protect([]byte(configs.CsrfAuthKey), csrf.Secure(false))
	// First we create a FuncMap with which to register the function.
	funcMap = template.FuncMap{
		// The name "title" is what the function will be called in the template text.
		"trim":  strings.TrimSpace,
		"lower": strings.ToLower,
		"upper": strings.ToUpper,
		"safehtml": func(text string) template.HTML {
			return template.HTML(text)
		},
	}
	g_templates = make(myTemplates)
	loadTemplates("")
	fmt.Printf("%v\n", g_templates)
	r = gin.New()
}
Exemple #3
0
func main() {
	mux := http.NewServeMux()
	mux.Handle("/", routes.Router())
	admin.Admin.MountTo("/admin", mux)
	admin.Widgets.WidgetSettingResource.IndexAttrs("Name")

	api.API.MountTo("/api", mux)
	admin.Filebox.MountTo("/downloads", mux)

	for _, path := range []string{"system", "javascripts", "stylesheets", "images"} {
		mux.Handle(fmt.Sprintf("/%s/", path), http.FileServer(http.Dir("public")))
	}

	fmt.Printf("Listening on: %v\n", config.Config.Port)
	skipCheck := func(h http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			if !strings.HasPrefix(r.URL.Path, "/auth") {
				r = csrf.UnsafeSkipCheck(r)
			}
			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
	handler := csrf.Protect([]byte("3693f371bf91487c99286a777811bd4e"), csrf.Secure(false))(mux)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", config.Config.Port), skipCheck(handler)); err != nil {
		panic(err)
	}
}
Exemple #4
0
// newCSRF initializes a new CSRF handler
func newCSRFHandler(keyPath string) func(h http.Handler) http.Handler {
	authKey := newAuthKey(keyPath)
	return csrf.Protect(
		authKey,
		csrf.HttpOnly(false),
		csrf.Secure(false),
	)
}
Exemple #5
0
func (m *CSRF) MiddlewareFunc() interface{} {
	key := []byte(m.ProtectKey)
	return func(c *web.C, h http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			h.ServeHTTP(w, r)
		}
		return csrf.Protect(key)(http.HandlerFunc(fn))
	}
}
Exemple #6
0
func createHandler(dir string, d string, e string, flags TLSFlags) http.Handler {
	var (
		mux         = http.NewServeMux()
		fileHandler = http.FileServer(http.Dir(dir))
		h           http.Handler
	)

	u, perr := url.Parse(e)
	if perr != nil {
		log.Fatal(perr)
	}

	if u.Scheme == "tcp" {
		if flags.tls {
			h = createTcpHandlerWithTLS(u, flags)
		} else {
			h = createTcpHandler(u)
		}
	} else if u.Scheme == "unix" {
		var socketPath = u.Path
		if _, err := os.Stat(socketPath); err != nil {
			if os.IsNotExist(err) {
				log.Fatalf("unix socket %s does not exist", socketPath)
			}
			log.Fatal(err)
		}
		h = createUnixHandler(socketPath)
	} else {
		log.Fatalf("Bad Docker enpoint: %s. Only unix:// and tcp:// are supported.", e)
	}

	// Use existing csrf authKey if present or generate a new one.
	var authKeyPath = d + "/" + authKeyFile
	dat, err := ioutil.ReadFile(authKeyPath)
	if err != nil {
		fmt.Println(err)
		authKey = securecookie.GenerateRandomKey(32)
		err := ioutil.WriteFile(authKeyPath, authKey, 0644)
		if err != nil {
			fmt.Println("unable to persist auth key", err)
		}
	} else {
		authKey = dat
	}

	CSRF := csrf.Protect(
		authKey,
		csrf.HttpOnly(false),
		csrf.Secure(false),
	)

	mux.Handle("/dockerapi/", http.StripPrefix("/dockerapi", h))
	mux.Handle("/", fileHandler)
	return CSRF(csrfWrapper(mux))
}
Exemple #7
0
// Init ... GAEハンドラー登録
func Init() {

	// コンテンツ用
	r := mux.NewRouter()
	r.HandleFunc("/", ok).Methods("GET")
	r.HandleFunc("/start", ok).Methods("GET")
	r.HandleFunc("/_ah/stop", ok).Methods("GET")

	// 管理者用(login: adminで制限かけてるのでCSRF不要)
	r = admin.Init(r)

	// API(CSRF対策エリア)
	api := mux.NewRouter()
	CSRF := csrf.Protect([]byte(def.CsrfKey))
	if def.Dev() {
		CSRF = csrf.Protect([]byte(def.CsrfKey), csrf.Secure(false))
	}
	r.PathPrefix("/api").Handler(CSRF(api))

	http.Handle("/", r)
}
Exemple #8
0
func main() {
	var err error
	db, err := shorturl.ConnectToDatabase()
	if err != nil {
		log.Fatal(err)
	}

	contentRoot := "."
	if len(os.Args) >= 2 {
		contentRoot = os.Args[1]
	}

	csrfSecretFile := path.Join(contentRoot, "csrf.secret")
	if _, err := os.Stat(csrfSecretFile); os.IsNotExist(err) {
		randBytes := make([]byte, 32)
		_, err := rand.Read(randBytes)
		if err != nil {
			log.Fatal(err)
		}
		ioutil.WriteFile(csrfSecretFile, randBytes, 0600)
	}
	csrfSecret, err := ioutil.ReadFile(csrfSecretFile)
	// FIXME: use secure cookie (default)
	CSRF := csrf.Protect([]byte(csrfSecret), csrf.Secure(false))

	if err != nil {
		log.Fatal(err)
	}
	if len(csrfSecret) != 32 {
		panic("CSRF secret file must be 32 bytes")
	}

	addr := "0.0.0.0:39284"
	log.Print("Listening on http://", addr)
	view := shorturl.NewView(contentRoot, db)

	r := mux.NewRouter()
	r.HandleFunc("/favicon.ico", view.FaviconHandler)
	r.HandleFunc("/{key}", view.Redirect)
	r.HandleFunc("/", view.Index)
	r.HandleFunc("/add/", view.Add)
	r.Handle("/p/{key}", http.StripPrefix("/p/", http.HandlerFunc(view.Preview)))

	// Static files
	staticHandler := http.FileServer(http.Dir(path.Join(contentRoot, "static")))
	r.PathPrefix("/static/").Handler(
		http.StripPrefix("/static/", staticHandler))

	r.HandleFunc("/always-preview/enable", setAlwaysPreview)
	r.HandleFunc("/always-preview/disable", unsetAlwaysPreview)
	http.ListenAndServe(addr, CSRF(r))
}
Exemple #9
0
func New(conf *config.Config, db db.DB) (*Server, error) {
	s := &Server{
		config: conf,
		db:     db,
	}

	if !s.config.Server.Development {
		tmpl, err := s.loadTemplates()
		if err != nil {
			return nil, err
		}
		s.tmpl = tmpl
	}

	n := negroni.Classic()

	csrfHandler := csrf.Protect(
		[]byte(s.config.Server.CSRFAuthKey),
		csrf.Secure(!s.config.Server.Development),
		csrf.FieldName("_csrf"),
	)
	n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		csrfHandler(next).ServeHTTP(w, r)
	})

	n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		handlers.HTTPMethodOverrideHandler(next).ServeHTTP(w, r)
	})
	n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		handlers.CompressHandler(next).ServeHTTP(w, r)
	})

	n.UseFunc(s.userAuthMiddleware)

	r := httprouter.New()
	r.ServeFiles("/static/*filepath", http.Dir(path.Join(DataDir, "public")))
	r.GET("/signin", s.wrapHandler(s.HandleGetSignIn))
	r.POST("/signin", s.wrapHandler(s.HandlePostSignIn))
	r.POST("/signout", s.wrapHandler(s.HandlePostSignOut))
	r.GET("/logs", s.wrapHandler(s.HandleGetLogs))
	r.POST("/logs", s.wrapHandler(s.HandlePostLog))
	r.GET("/logs/:id/download", s.wrapHandler(s.HandleDownloadLog))
	r.GET("/logs/:id", s.wrapHandler(s.HandleGetLog))
	r.PATCH("/logs/:id", s.wrapHandler(s.HandlePatchLog))
	r.DELETE("/logs/:id", s.wrapHandler(s.HandleDeleteLog))
	r.GET("/", s.wrapHandler(s.HandleDashboard))
	n.UseHandler(r)

	s.handler = n
	return s, nil
}
Exemple #10
0
func main() {
	if len(os.Args) > 1 && os.Args[1] == "update" {
		ok, err := update()
		if err != nil {
			log.Printf("Failed to check for update: %s\n", err.Error())
			return
		}

		if ok {
			return
		}
	}
	if DevEnv() {
		log.Printf("EVEMu Gate starting in development mode")
	} else {
		log.Printf("EVEmuGate starting in deployment mode")
	}
	r := mux.NewRouter()
	var fs = http.FileServer(&assetfs.AssetFS{
		Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "assets",
	})

	r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", fs))

	r.HandleFunc("/", HandlerIndex)
	r.HandleFunc("/login", HandlerLogin)
	r.HandleFunc("/logout", HandlerLogout)
	r.HandleFunc("/register", HandlerRegister)
	r.HandleFunc("/characters", HandlerCharacters)

	chain := NewMiddlewareChain(
		// this will fail without Secure false on http
		csrf.Protect([]byte(Config.CSRFToken), csrf.Secure(false)),
		SetServerStatus,
		SetUser,
	)

	http.Handle("/", r)

	log.Printf("Starting EVEmu Gate at %s", Config.GateHost)

	err := http.ListenAndServe(Config.GateHost, chain.Do(r))
	if err != nil {
		log.Panicf("ListenAndServe: %s", err.Error())
	}
}
Exemple #11
0
// ServeSSL serves cosgo on port 443 with attached key+cert
func (c *Cosgo) ServeSSL() {
	go func() {
		time.Sleep(100 * time.Millisecond)
		log.Println("Cosgo: Serving TLS on", *sslport)
	}()

	log.Fatalln(http.ListenAndServeTLS(*sslport, *path2cert, *path2key,
		csrf.Protect(c.antiCSRFkey,
			csrf.HttpOnly(true),
			csrf.FieldName(*cookie),
			csrf.CookieName(*cookie),
			csrf.Secure(true),
			csrf.MaxAge(600),
			csrf.ErrorHandler(http.HandlerFunc(csrfErrorHandler)),
		)(c.r)))

}
Exemple #12
0
func main() {

	muxRouter := mux.NewRouter()

	muxRouter.HandleFunc("/", getMovies).Methods("GET")
	//-------Api ----------
	muxRouter.HandleFunc("/api/movie", apiMovies).Methods("GET")
	muxRouter.HandleFunc("/api/movie/{imdbKey}", apiMovies).Methods("GET", "POST", "DELETE", "PUT")

	CSRF := csrf.Protect([]byte("_yJ3~mY#i{l}=mt^kIUfxW9o:Z~ydF(."))

	go http.ListenAndServe(":3000", CSRF(muxRouter))

	log.Println("Servidor Iniciado http://127.0.0.1:3000/, presiona <ENTER> para salir.")
	fmt.Scanln()

}
Exemple #13
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 := csrf.Protect([]byte(auth.GenerateSecureKey()),
		csrf.FieldName("csrf_token"),
		csrf.Secure(config.Conf.AdminConf.UseTLS))
	csrfRouter := csrfHandler(router)
	return Use(csrfRouter.ServeHTTP, mid.CSRFExceptions, mid.GetContext)
}
Exemple #14
0
func exec() {
	scfg := config.Server
	db, err := db.NewBoltDB(scfg.Database)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	smtpAuth := smtp.PlainAuth("", config.Mail.Username, config.Mail.Password, config.Mail.Server)
	mailer := mail.NewMailer(config.Mail.Server, config.Mail.Username, smtpAuth)

	handler := server.NewRootHandler(db, ".", []byte(scfg.SessionKey), mailer, scfg.URLRoot)
	if scfg.TLSCert != "" && scfg.TLSKey != "" && len(scfg.SessionKey) == 32 {
		CSRF := csrf.Protect([]byte(scfg.SessionKey))
		log.Fatal(http.ListenAndServeTLS(":"+scfg.Port, scfg.TLSCert, scfg.TLSKey, CSRF(handler)))
	} else {
		log.Fatal(http.ListenAndServe(":"+scfg.Port, handler))
	}
}
Exemple #15
0
func main() {
	r := mux.NewRouter()

	// Set template and the delimeters
	t := template.New("index")
	t.Delims("<<<", ">>>")
	temps = template.Must(t.ParseFiles("./views/index.html"))

	CSRF := csrf.Protect(
		[]byte(conf.CSRFKey),
		csrf.RequestHeader("Request-Token"),
		csrf.FieldName("request_token"),
		csrf.Secure(!conf.Debug),
	)

	r.HandleFunc("/", indexHandler)
	r.PathPrefix("/dist/").Handler(createStaticHandler("/dist/", "./dist/"))
	r.HandleFunc("/save", api.SaveSnippet)
	r.HandleFunc("/snippet/{id}", api.GetSnippet)
	http.ListenAndServe(":"+conf.Port, CSRF(r))
}
Exemple #16
0
//InitCsrf initializes gorilla CSRF handler
func InitCsrf() {
	CSRF = csrf.Protect([]byte(GetConfig().CsrfSecret), csrf.Secure(GetConfig().Ssl), csrf.Path("/"), csrf.Domain(GetConfig().Domain))
}
// Register the handlers for a given route.
func Register(db *sql.DB, authorizer httpauth.Authorizer, authBackend httpauth.AuthBackend,
	roles map[string]httpauth.Role, templates *template.Template, pinger *pinger.Pinger,
	version string, cookieKey []byte, secureCookie bool) {

	// setup CSRF protection for the post requests.
	CSRF := csrf.Protect(cookieKey, csrf.Secure(secureCookie))
	router := mux.NewRouter()

	hc := new(homeController)
	hc.template = templates.Lookup("home.gohtml")
	hc.authorizer = authorizer
	hc.DB = db
	router.Handle("/", authorizeRole(appHandler(hc.get), authorizer, "user"))

	rc := new(reportsController)
	rc.template = templates.Lookup("reports.gohtml")
	rc.authorizer = authorizer
	rc.DB = db
	router.Handle("/reports", authorizeRole(appHandler(rc.get), authorizer, "user"))

	pc := new(profileController)
	pc.template = templates.Lookup("profile.gohtml")
	pc.authorizer = authorizer
	pc.authBackend = authBackend
	pc.DB = db
	router.Handle("/profile", authorizeRole(appHandler(pc.get), authorizer, "user")).Methods("GET")
	router.Handle("/profile", authorizeRole(appHandler(pc.post), authorizer, "user")).Methods("POST")

	ac := new(aboutController)
	ac.template = templates.Lookup("about.gohtml")
	ac.authorizer = authorizer
	ac.version = version
	router.HandleFunc("/about", ac.get)

	lc := new(loginController)
	lc.template = templates.Lookup("login.gohtml")
	lc.authorizer = authorizer
	router.HandleFunc("/login", lc.get).Methods("GET")
	router.HandleFunc("/login", lc.post).Methods("POST")

	loc := new(logoutController)
	loc.authorizer = authorizer
	router.HandleFunc("/logout", loc.get)

	sc := new(settingsController)
	sc.template = templates.Lookup("settings.gohtml")
	sc.authorizer = authorizer
	sc.DB = db
	router.Handle("/settings", authorizeRole(appHandler(sc.get), authorizer, "admin"))

	//settingsSub is a subrouter "/settings"
	settingsSub := router.PathPrefix("/settings").Subrouter()

	// /settings/users
	uc := new(usersController)
	uc.getTemplate = templates.Lookup("users.gohtml")
	uc.editTemplate = templates.Lookup("user_edit.gohtml")
	uc.newTemplate = templates.Lookup("user_new.gohtml")
	uc.deleteTemplate = templates.Lookup("user_delete.gohtml")
	uc.authorizer = authorizer
	uc.authBackend = authBackend
	uc.roles = roles
	settingsSub.Handle("/users", authorizeRole(appHandler(uc.get), authorizer, "admin"))
	settingsSub.Handle("/users/{username}/edit", authorizeRole(appHandler(uc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/{username}/edit", authorizeRole(appHandler(uc.editPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/users/{username}/delete", authorizeRole(appHandler(uc.deleteGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/{username}/delete", authorizeRole(appHandler(uc.deletePost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/users/new", authorizeRole(appHandler(uc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/users/new", authorizeRole(appHandler(uc.newPost), authorizer, "admin")).Methods("POST")

	// /settings/contacts
	cc := new(contactsController)
	cc.getTemplate = templates.Lookup("contacts.gohtml")
	cc.editTemplate = templates.Lookup("contact_edit.gohtml")
	cc.newTemplate = templates.Lookup("contact_new.gohtml")
	cc.deleteTemplate = templates.Lookup("contact_delete.gohtml")
	cc.authorizer = authorizer
	cc.pinger = pinger
	cc.DB = db
	settingsSub.Handle("/contacts", authorizeRole(appHandler(cc.get), authorizer, "admin"))
	settingsSub.Handle("/contacts/{contactID}/edit", authorizeRole(appHandler(cc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/{contactID}/edit", authorizeRole(appHandler(cc.editPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/contacts/{contactID}/delete", authorizeRole(appHandler(cc.deleteGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/{contactID}/delete", authorizeRole(appHandler(cc.deletePost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/contacts/new", authorizeRole(appHandler(cc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/contacts/new", authorizeRole(appHandler(cc.newPost), authorizer, "admin")).Methods("POST")

	// /settings/sites
	stc := new(sitesController)
	stc.detailsTemplate = templates.Lookup("site_details.gohtml")
	stc.editTemplate = templates.Lookup("site_edit.gohtml")
	stc.newTemplate = templates.Lookup("site_new.gohtml")
	stc.changeContactsTemplate = templates.Lookup("site_change_contacts.gohtml")
	stc.authorizer = authorizer
	stc.pinger = pinger
	stc.DB = db
	// Site list is handled on main settings page so not required here.
	settingsSub.Handle("/sites/new", authorizeRole(appHandler(stc.newGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/sites/new", authorizeRole(appHandler(stc.newPost), authorizer, "admin")).Methods("POST")
	settingsSub.Handle("/sites/{siteID}", authorizeRole(appHandler(stc.getDetails), authorizer, "admin"))
	settingsSub.Handle("/sites/{siteID}/edit", authorizeRole(appHandler(stc.editGet), authorizer, "admin")).Methods("GET")
	settingsSub.Handle("/sites/{siteID}/edit", authorizeRole(appHandler(stc.editPost), authorizer, "admin")).Methods("POST")

	// Wrap the router in the CSRF protection.
	http.Handle("/", CSRF(router))

	http.HandleFunc("/img/", serveResource)
	http.HandleFunc("/css/", serveResource)
	http.HandleFunc("/js/", serveResource)
	http.HandleFunc("/fonts/", serveResource)
}
Exemple #18
0
// CSRF - adds CSRF protection
func (m *Middleware) CSRF(h http.Handler) http.Handler {
	CSRF := csrf.Protect([]byte(os.Getenv("TPD_CSRF_KEY")), csrf.CookieName(os.Getenv("TPD_CSRF_NAME")))
	return CSRF(h)
}
Exemple #19
0
func main() {

	// Create the server, load mbox and fortunes and run initialize
	cosgo := setup()

	// Set all the needed /url paths
	e := cosgo.route(cwd)
	if e != nil {
		log.Fatalln(e)
	}

	// Needs to be compiled with build tag 'debug' to be redefined, and -debug CLI flag to be activated
	if *debug {
		cosgo.debug()
	}
	cosgo.Bind = *bind
	cosgo.Port = strconv.Itoa(*portnum)
	log.Println("Refreshing every", *refreshTime)
	go func() {
		time.Sleep(100 * time.Millisecond)
		log.Println("Listening on", cosgo.Bind+":"+cosgo.Port)
	}()
	// Try to bind
	listener, binderr := net.Listen("tcp", cosgo.Bind+":"+cosgo.Port)
	if binderr != nil {
		log.Println(binderr)
		os.Exit(1)
	}

	if cosgo.antiCSRFkey == nil {
		cosgo.antiCSRFkey = anticsrfGen()
	}
	if *path2cert != *path2key {
		go cosgo.ServeSSL()
	}

	// Is nolog enabled?
	if *nolog {
		*logfile = os.DevNull
	}
	// stdout or a filename
	openLogFile()

	// Start Serving
	// Here we either use fastcgi or normal http server, using csrf and mux.
	// with custom csrf error handler and 10 minute cookie.
	if !*fastcgi {

		go func() {
			if listener != nil {
				go http.Serve(listener,
					csrf.Protect(cosgo.antiCSRFkey,
						csrf.HttpOnly(true),
						csrf.FieldName(*cookie),
						csrf.CookieName(*cookie),
						csrf.Secure(*secure), csrf.MaxAge(600), csrf.ErrorHandler(http.HandlerFunc(csrfErrorHandler)))(cosgo.r))
			} else {
				log.Fatalln("nil listener")
			}

		}()
	} else {
		go func() {
			if listener != nil {
				go fcgi.Serve(listener,
					csrf.Protect(cosgo.antiCSRFkey,
						csrf.HttpOnly(true),
						csrf.FieldName(*cookie),
						csrf.CookieName(*cookie),
						csrf.Secure(*secure), csrf.MaxAge(600), csrf.ErrorHandler(http.HandlerFunc(csrfErrorHandler)))(cosgo.r))
			} else {
				log.Fatalln("nil listener")
			}
		}()
	}

	select {

	// Fire up the cosgo engine

	case <-time.After(*refreshTime):
		cosgo.rw.Lock()
		if *debug && !*quiet {
			log.Println("Info: Generating Random 40 URL Key...")
		}
		t1 := time.Now()
		// set a random URL key (40 char length).
		kee := generateURLKey(40)
		cosgo.URLKey = kee
		if *debug && !*quiet {
			log.Printf("Generated URL Key %q in %v", cosgo.URLKey, time.Now().Sub(t1))
		}
		cosgo.rw.Unlock()

		// every X minutes change the URL key (default 42 minutes)
		// break tests uncomment next line
		//*refreshTime = time.Nanosecond

		if !*quiet {
			log.Printf("Uptime: %s (%s)", time.Since(timeboot), humanize(time.Since(timeboot)))
			log.Printf("Hits: %v", hitcounter)
			log.Printf("Messages: %v", inboxcount)
			if *debug {
				log.Printf("Port: %v", cosgo.Port)
			}
			if *path2cert != "" {
				log.Println("TLS: ON")
			}
		}

	}
}
Exemple #20
0
func (self *httpFrontend) Mainloop() {
	EnsureDir(self.webroot_dir)
	if !CheckFile(self.template_dir) {
		log.Fatalf("no such template folder %s", self.template_dir)
	}
	template.changeTemplateDir(self.template_dir)

	// set up handler mux
	self.httpmux = mux.NewRouter()

	self.httpmux.NotFoundHandler = template.createNotFoundHandler(self.prefix, self.name)

	// create mod ui
	self.modui = createHttpModUI(self)

	cache_handler := self.cache.GetHandler()

	// csrf protection
	b := []byte(self.secret)
	var sec [32]byte
	copy(sec[:], b)
	// TODO: make configurable
	CSRF := csrf.Protect(sec[:], csrf.Secure(false))

	m := mux.NewRouter()
	// modui handlers
	m.Path("/mod/").HandlerFunc(self.modui.ServeModPage).Methods("GET")
	m.Path("/mod/feeds").HandlerFunc(self.modui.ServeModPage).Methods("GET")
	m.Path("/mod/keygen").HandlerFunc(self.modui.HandleKeyGen).Methods("GET")
	m.Path("/mod/login").HandlerFunc(self.modui.HandleLogin).Methods("POST")
	m.Path("/mod/del/{article_hash}").HandlerFunc(self.modui.HandleDeletePost).Methods("GET")
	m.Path("/mod/ban/{address}").HandlerFunc(self.modui.HandleBanAddress).Methods("GET")
	m.Path("/mod/unban/{address}").HandlerFunc(self.modui.HandleUnbanAddress).Methods("GET")
	m.Path("/mod/addkey/{pubkey}").HandlerFunc(self.modui.HandleAddPubkey).Methods("GET")
	m.Path("/mod/delkey/{pubkey}").HandlerFunc(self.modui.HandleDelPubkey).Methods("GET")
	m.Path("/mod/admin/{action}").HandlerFunc(self.modui.HandleAdminCommand).Methods("GET", "POST")
	self.httpmux.PathPrefix("/mod/").Handler(CSRF(m))
	m = self.httpmux
	m.Path("/").Handler(cache_handler)
	// robots.txt handler
	m.Path("/robots.txt").HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "User-Agent: *\nDisallow: /\n")
	})).Methods("GET")

	m.Path("/thm/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	m.Path("/img/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	m.Path("/{f}.html").Handler(cache_handler).Methods("GET", "HEAD")
	m.Path("/{f}.json").Handler(cache_handler).Methods("GET", "HEAD")
	m.Path("/static/{f}").Handler(http.FileServer(http.Dir(self.static_dir)))
	m.Path("/post/{f}").HandlerFunc(self.handle_poster).Methods("POST")
	m.Path("/captcha/img").HandlerFunc(self.new_captcha).Methods("GET")
	m.Path("/captcha/{f}").Handler(captcha.Server(350, 175)).Methods("GET")
	m.Path("/captcha/new.json").HandlerFunc(self.new_captcha_json).Methods("GET")
	m.Path("/new/").HandlerFunc(self.handle_newboard).Methods("GET")
	m.Path("/api/{meth}").HandlerFunc(self.handle_api).Methods("POST", "GET")
	// live ui websocket
	m.Path("/live").HandlerFunc(self.handle_liveui).Methods("GET")
	// live ui page
	m.Path("/livechan/").HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		template.writeTemplate("live.mustache", map[string]interface{}{"prefix": self.prefix}, w)
	})).Methods("GET", "HEAD")
	var err error

	// run daemon's mod engine with our frontend
	go RunModEngine(self.daemon.mod, self.cache.RegenOnModEvent)

	// start cache
	self.cache.Start()

	// before we go further ensure all db models are loaded into template model cache
	template.loadAllModels(self.prefix, self.name, self.daemon.database)

	// poll channels
	go self.poll()

	// poll liveui
	go self.poll_liveui()

	// start webserver here
	log.Printf("frontend %s binding to %s", self.name, self.bindaddr)

	// serve it!
	err = http.ListenAndServe(self.bindaddr, self.httpmux)
	if err != nil {
		log.Fatalf("failed to bind frontend %s %s", self.name, err)
	}
}