Exemplo n.º 1
0
func Startup() {

	templating.Setup()

	mux := httprouter.New()

	for path := range PathMapForGet {
		mux.GET(path, PathMapForGet[path])
	}
	for path := range PathMapForPost {
		mux.POST(path, PathMapForPost[path])
	}

	// handle static files
	mux.ServeFiles("/assets/*filepath", http.Dir(config.PATH_BASE_GOLANG_ASSETS))

	var u *url.URL
	var err error
	u, err = url.Parse(config.BACK_END_URL)
	if err != nil {
		log.Fatal(err)
	}
	// handle reserve proxy
	proxy := handler(httputil.NewSingleHostReverseProxy(u))

	// set GET paths
	for _, path := range ProxyPathListForGet {
		mux.HandlerFunc("GET", path, proxy)
	}

	// set POST paths
	for _, path := range ProxyPathListForPost {
		mux.HandlerFunc("POST", path, proxy)
	}

	secureMiddleware := secure.New(secure.Options{
		SSLRedirect: true,
		SSLHost:     config.HOST,
	})
	app := authenticationHandler(secureMiddleware.Handler(mux))

	log.Println("Starting...")

	models.DbMap = initDbMap()
	defer models.DbMap.Close()
	err = models.DbMap.Ping()
	if err != nil {
		log.Fatal("ping:", err)
	}

	// HTTP
	go func() {
		log.Fatal(http.ListenAndServe(config.PORT_HTTP, mux))
	}()

	// HTTPS

	log.Fatal(http.ListenAndServeTLS(config.PORT_HTTPS, config.PATH_BASE_GOLANG_CERT+"/cert.pem", config.PATH_BASE_GOLANG_CERT+"/key.pem", app))

}
Exemplo n.º 2
0
func Secure(isProd bool) gin.HandlerFunc {
	secureMiddleware := secure.New(secure.Options{
		SSLRedirect:          true,
		STSSeconds:           315360000,
		SSLProxyHeaders:      map[string]string{"X-Forwarded-Proto": "https"},
		STSIncludeSubdomains: true,
		FrameDeny:            true,
		ContentTypeNosniff:   true,
		BrowserXssFilter:     true,
		IsDevelopment:        !isProd,
	})

	return func(c *gin.Context) {
		if shouldAllowOrigin(c.Request) {
			c.Writer.Header().Add(allowOriginHeader, "*")
		}

		err := secureMiddleware.Process(c.Writer, c.Request)
		if err != nil {
			return
		}

		c.Next()
	}
}
Exemplo n.º 3
0
func main() {
	mw := interpose.New()

	// Use unrolled's secure framework
	// If you inspect the headers, you will see X-Frame-Options set to DENY
	// Must be called before the router because it modifies HTTP headers
	secureMiddleware := secure.New(secure.Options{
		FrameDeny: true,
	})
	mw.Use(secureMiddleware.Handler)

	// Apply the router. By adding it first, all of our other middleware will be
	// executed before the router, allowing us to modify headers before any
	// output has been generated.
	router := mux.NewRouter()
	mw.UseHandler(router)

	router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"])
	})

	// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
	// connections to end
	graceful.Run(":3001", 10*time.Second, mw)
}
Exemplo n.º 4
0
func setupMiddleware() []http.Handler {
	return []http.Handler{
		adaptors.HandlerFromNegroni(cors.New(cors.Options{
			AllowedOrigins:   viper.GetStringSlice("cors.allowed_origins"),
			AllowedMethods:   viper.GetStringSlice("cors.allowed_methods"),
			AllowCredentials: viper.GetBool("cors.allow_credentials"),
		})),
		adaptors.HandlerFromNegroni(negroni.HandlerFunc(secure.New(secure.Options{
			AllowedHosts:            []string{},
			SSLRedirect:             false,
			SSLTemporaryRedirect:    false,
			SSLHost:                 "",
			SSLProxyHeaders:         map[string]string{},
			STSSeconds:              0,
			STSIncludeSubdomains:    false,
			STSPreload:              false,
			ForceSTSHeader:          false,
			FrameDeny:               false,
			CustomFrameOptionsValue: "",
			ContentTypeNosniff:      false,
			BrowserXssFilter:        false,
			ContentSecurityPolicy:   "",
			IsDevelopment:           viper.GetString("environment") == "development",
		}).HandlerFuncWithNext)),
	}
}
Exemplo n.º 5
0
func init() {
	// Check the github repo and set these options properly when the site
	// goes live.
	secureOpts = secure.New(secure.Options{
		AllowedHosts:         []string{"localhost"},
		SSLRedirect:          false,
		SSLHost:              "ssl.example.com",
		SSLProxyHeaders:      map[string]string{"X-Forwarded-Proto": "https"},
		STSSeconds:           315360000,
		STSIncludeSubdomains: true,
		STSPreload:           true,
		FrameDeny:            true,
		ContentTypeNosniff:   true,
		BrowserXssFilter:     true,
		// ContentSecurityPolicy: "default-src 'self'",
		IsDevelopment: true,
	})

	// Logging (in conjunction with compression).
	opts := useful.DefaultOptions()
	opts.LogDestination = useful.File
	opts.LogName = filepath.Join("log", "access.log")
	opts.ArchiveDir = filepath.Join("log", "archives")
	useful.LogFile.Init(opts)

	cleanup.Register("glog", glog.Flush)             // Make sure logs flush before we exit.
	cleanup.Register("useful", useful.LogFile.Close) // Close our log file.

}
Exemplo n.º 6
0
// NewSecure returns instance of secure.Secure to redirect http to https
func NewSecure(isDevelopment bool) *secure.Secure {
	return secure.New(secure.Options{
		SSLRedirect:     true,
		SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
		IsDevelopment:   isDevelopment,
	})
}
Exemplo n.º 7
0
// NewHandler is what vulcand uses to create a handler from the middleware config and insert it
// into the chain
func (m *SecureMiddleware) NewHandler(next http.Handler) (http.Handler, error) {
	s := secure.New(m.Opts)
	return &SecureHandler{
		next: next,
		cfg:  *m,
		s:    s,
	}, nil
}
Exemplo n.º 8
0
func main() {
	secureMiddleware := secure.New(secure.Options{
		FrameDeny:     true,
		IsDevelopment: true,
	})

	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
	// n.UseHandler(mx)
	n.Run(":8080")

}
Exemplo n.º 9
0
func NewServer(dba utils.DatabaseAccessor, cua utils.CurrentUserAccessor, clientID, clientSecret,
	sessionSecret string, isDevelopment bool, gaKey string) *Server {
	s := Server{negroni.Classic()}
	session := utils.NewSessionManager()
	basePage := utils.NewBasePageCreator(cua, gaKey)
	renderer := render.New()

	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles("views/layout.html", "views/index.html")
		t.Execute(w, basePage.Get(r))
	})
	router.HandleFunc("/legal", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles("views/layout.html", "views/legal.html")
		t.Execute(w, basePage.Get(r))
	})
	router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles("views/layout.html", "views/404.html")
		t.Execute(w, basePage.Get(r))
	})

	accountController := controllers.NewAccountController(clientID, clientSecret, isDevelopment, session, dba, cua, basePage, renderer)
	accountController.Register(router)
	createServiceController := controllers.NewCreateServiceController(cua, basePage, renderer, dba)
	createServiceController.Register(router)
	serviceController := controllers.NewServiceController(cua, basePage, renderer, dba)
	serviceController.Register(router)
	codeController := controllers.NewReferralCodeController(cua, renderer, dba)
	codeController.Register(router)
	searchController := controllers.NewSearchController(cua, basePage, renderer, dba)
	searchController.Register(router)
	sitemapController := controllers.NewSitemapController(dba)
	sitemapController.Register(router)

	s.Use(negroni.HandlerFunc(secure.New(secure.Options{
		AllowedHosts:       []string{"www.refer-madness.com", "refer-madness.com"},
		ContentTypeNosniff: true,
		BrowserXssFilter:   true,
		FrameDeny:          true,
		IsDevelopment:      isDevelopment,
	}).HandlerFuncWithNext))
	s.Use(sessions.Sessions("refermadness", cookiestore.New([]byte(sessionSecret))))
	s.Use(middleware.NewDatabase(dba).Middleware())
	s.Use(middleware.NewAuthenticator(dba, session, cua).Middleware())
	s.UseHandler(router)

	return &s
}
Exemplo n.º 10
0
// Run runs the server and block until the server is shutdown
func (s *Server) Run() {
	// XXX(tsileo) make the key persisiting between restart?
	// TODO retrive both key from the KvStore
	hawkKey := make([]byte, 64)
	if _, err := rand.Read(hawkKey); err != nil {
		panic(err)
	}
	// Set up auth
	// TODO Try to retrieve the API key from the KvStore or generate a new (UUID v4)
	// Maybe handle a master key with multiple key? so key can be revoked?
	authMiddleware := middleware.BasicAuth("", "token")
	middlewares := &serverMiddleware.SharedMiddleware{
		Auth: authMiddleware,
	}
	// FIXME token as parameter
	authFunc := httputil.BasicAuthFunc("", "token")
	// Start the HTTP API
	s.SetUp()
	r := mux.NewRouter()
	// publicRoute := r.PathPrefix("/public").Subrouter()
	appRoute := r.PathPrefix("/app").Subrouter()
	ekvstore := s.KvStore()
	eblobstore := s.BlobStore()
	docstore.New(s.Log.New("ext", "docstore"), ekvstore, eblobstore).RegisterRoute(r.PathPrefix("/api/ext/docstore/v1").Subrouter(), middlewares)
	luaExt := lua.New(s.Log.New("ext", "lua"), hawkKey, authFunc, ekvstore, eblobstore)
	luaExt.RegisterRoute(r.PathPrefix("/api/ext/lua/v1").Subrouter(), middlewares)
	luaExt.RegisterAppRoute(appRoute, middlewares)
	api.New(r.PathPrefix("/api/v1").Subrouter(), middlewares, s.wg, s.DB, s.NsDB, s.KvUpdate, s.Router, s.blobs, s.watchHub)

	s.syncer = synctable.New(s.blobs, eblobstore, s.NsDB, s.Log.New("ext", "synctable"))
	s.syncer.RegisterRoute(r.PathPrefix("/api/sync/v1").Subrouter(), middlewares)

	// TODO(tsileo) add robots.txt handler, and a 204 favicon.ico handler
	// FIXME(tsileo) a way to make an app hook the index
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		index := `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>BlobsStash</title>
</head>
<body><p>
<p>This is a private <a href="https://github.com/tsileo/blobstash">BlobStash</a> instance.</p>
</p></body></html>`
		w.Write([]byte(index))
	})

	// FIXME allowedorigins from config
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})

	secureMiddleware := secure.New(secure.Options{
		FrameDeny:             true,
		ContentTypeNosniff:    true,
		BrowserXssFilter:      true,
		ContentSecurityPolicy: "default-src 'self'",
	})
	http.Handle("/", secureMiddleware.Handler(c.Handler(r)))
	s.Log.Info(fmt.Sprintf("server: HTTP API listening on 0.0.0.0:%d", s.port))
	go func() {
		if err := http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil); err != nil {
			panic(err)
		}
	}()

	// XXX(tsileo) HTTPS version for later
	// http.Handle("/", secureMiddleware.Handler(c.Handler(r)))
	// srv := &http.Server{
	// 	Addr:    ":443",
	// 	Handler: http.DefaultServeMux,
	// }
	// s.Log.Info("server: HTTP API listening on 0.0.0.0:8050")
	// go func() {
	// 	http2.ConfigureServer(srv, &http2.Server{})
	// 	if err := srv.ListenAndServeTLS(".lego/certificates/trucsdedev.com.crt", ".lego/certificates/trucsdedev.com.key"); err != nil {
	// 		panic(err)
	// 	}
	// }()

	s.TillShutdown()
}
Exemplo n.º 11
0
func main() {
	// Define the flags
	var confPath = flag.String("conf", "", "Configuration file to use")

	// Parse the flags
	flag.Parse()

	// Read the configuration file
	var confFile ini.File
	var confErr error
	if *confPath == "" {
		log.Error("A configuration file was not defined.")
		flag.PrintDefaults()
	}
	confFile, confErr = ini.LoadFile(*confPath)

	// Build the App Controller
	var server AppController

	// Check for errors
	if confErr != nil {
		println("ERROR: Unable to " + confErr.Error())
		println("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
		return
	}

	genConf := confFile.Section("General")

	// Load the CA Certificate, Resource Key, and Resource Certificate from the config
	webRoot, ok := genConf["WebRoot"]
	if !ok {
		log.Error("The WebRoot directive was not included in the 'General' section of the configuration file.")
		log.Error("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
	}
	webRoot = common.StripQuotes(webRoot)

	// Load the CA Certificate, Resource Key, and Resource Certificate from the config
	caCertPath, ok := genConf["CACertFile"]
	if !ok {
		log.Error("The CACertFile directive was not included in the 'General' section of the configuration file.")
		log.Error("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
	}
	caCertPath = common.StripQuotes(caCertPath)

	// Load the CA Certificate, Resource Key, and Resource Certificate from the config
	caKeyPath, ok := genConf["CAKeyFile"]
	if !ok {
		log.Error("The CAKeyFile directive was not included in the 'General' section of the configuration file.")
		log.Error("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
	}
	caKeyPath = common.StripQuotes(caKeyPath)

	KeyPath, ok := genConf["KeyFile"]
	if !ok {
		log.Error("The KeyFile directive was not included in the 'General' section of the configuration file.")
		log.Error("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
	}
	KeyPath = common.StripQuotes(KeyPath)

	CertPath, ok := genConf["CertFile"]
	if !ok {
		log.Error("The KeyFile directive was not included in the 'General' section of the configuration file.")
		log.Error("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
	}
	CertPath = common.StripQuotes(CertPath)

	// Check for an API SSL/TLS key/cert pair to use
	var useSepAPITLS bool
	APICertPath, APICertOK := genConf["APICertFile"]
	APIKeyPath, APIKeyOK := genConf["APIKeyFile"]
	if APIKeyOK && APICertOK {
		// We found a key and certificate for the API to use so change our boolean marker
		useSepAPITLS = true
	}

	runIP, ok := genConf["BindIP"]
	if !ok {
		runIP = "0.0.0.0"
	} else {
		runIP = common.StripQuotes(runIP)
	}

	runPort, ok := genConf["BindPort"]
	if !ok {
		runPort = "9443"
	} else {
		runPort = common.StripQuotes(runPort)
	}

	switch common.StripQuotes(genConf["LogLevel"]) {
	case "Debug":
		log.SetLevel(log.DebugLevel)
		log.Warn("Please note the debug level logs may contain sensitive information!")
	case "Info":
		log.SetLevel(log.InfoLevel)
	case "Warn":
		log.SetLevel(log.WarnLevel)
	case "Error":
		log.SetLevel(log.ErrorLevel)
	case "Fatal":
		log.SetLevel(log.FatalLevel)
	case "Panic":
		log.SetLevel(log.PanicLevel)
	default:
		log.SetLevel(log.InfoLevel)
	}

	lf := common.StripQuotes(genConf["LogFile"])
	if lf != "" {
		hook, err := cracklog.NewFileHook(lf)
		if err != nil {
			println("ERROR: Unable to open log file: " + err.Error())
		} else {
			log.AddHook(hook)
		}
	}

	var statefile string
	statefile = common.StripQuotes(genConf["StateFile"])

	var updatetime int
	var resourcetimeout int
	utconf := common.StripQuotes(genConf["UpdateTime"])
	if utconf != "" {
		var err error
		updatetime, err = strconv.Atoi(utconf)
		if err != nil {
			log.WithField("error", err.Error()).Error("Unable to parse update time in config file.")
			updatetime = 30
		}
	} else {
		updatetime = 30
	}
	restimeconf := common.StripQuotes(genConf["ResourceTimeout"])
	if restimeconf != "" {
		var err error
		resourcetimeout, err = strconv.Atoi(restimeconf)
		if err != nil {
			log.WithField("error", err.Error()).Error("Unable to parse resource timeout in config file.")
			resourcetimeout = 5
		}
	} else {
		resourcetimeout = 5
	}

	log.WithFields(log.Fields{
		"ip":   runIP,
		"port": runPort,
	}).Info("Starting queue server up.")

	// Get the Authentication configuration
	confAuth := confFile.Section("Authentication")
	if confAuth == nil {
		println("Error: Authentication configuration is required.")
		println("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
		return
	}

	_, weberr := os.Stat(webRoot)
	if weberr != nil {
		println("Error: Public web root '" + webRoot + "' does not exist.")
		return
	}

	// Check for type of authentication and set conf
	switch confAuth["type"] {
	case "INI":
		var i INIAuth

		// Get the users
		umap := map[string]string{}

		au := common.StripQuotes(confAuth["adminuser"])
		if au == "" {
			log.Fatal("An administrative user was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		ap := common.StripQuotes(confAuth["adminpass"])
		if ap == "" {
			log.Fatal("An administrative password was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}

		su := common.StripQuotes(confAuth["standarduser"])
		if su == "" {
			log.Fatal("An standard user was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		sp := common.StripQuotes(confAuth["standarduser"])
		if sp == "" {
			log.Fatal("An standard password was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}

		ru := common.StripQuotes(confAuth["readonlyuser"])
		if ru == "" {
			log.Fatal("An read only user was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		rp := common.StripQuotes(confAuth["readonlypass"])
		if rp == "" {
			log.Fatal("An read only password was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}

		umap[au] = ap
		umap[su] = sp
		umap[ru] = rp

		// Setup group mappings
		gmap := map[string]string{}

		gmap[au] = Administrator
		gmap[su] = StandardUser
		gmap[ru] = ReadOnly

		i.Setup(umap, gmap)

		server.Auth = &i

		log.Info("INI authentication setup complete.")
	case "ActiveDirectory":
		var ad ADAuth

		realm := common.StripQuotes(confAuth["realm"])
		if realm == "" {
			log.Fatal("No Active Directory realm was configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		ad.SetRealm(realm)

		gmap := map[string]string{}
		ro := common.StripQuotes(confAuth["ReadOnlyGroup"])
		if ro == "" {
			log.Fatal("A read only group was not provided. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		st := common.StripQuotes(confAuth["StandardGroup"])
		if st == "" {
			log.Fatal("A group for standard access was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}
		admin := common.StripQuotes(confAuth["AdminGroup"])
		if admin == "" {
			log.Fatal("A group for read only access was not configured. See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files#queue-auth")
		}

		gmap[ReadOnly] = ro
		gmap[StandardUser] = st
		gmap[Administrator] = admin

		ad.Setup(gmap)

		server.Auth = &ad
		log.WithFields(log.Fields{
			"readonly": ro,
			"standard": st,
			"admin":    admin,
		}).Info("Active directory authentication configured successfully.")
	}

	// Configure the TokenStore
	server.T = NewTokenStore()

	// Configure the Queue
	server.Q = queue.NewQueue(statefile, updatetime, resourcetimeout)

	caBytes, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		println("ERROR: " + err.Error())
	}

	caPool := x509.NewCertPool()
	caPool.AppendCertsFromPEM(caBytes)

	tlscert, err := tls.LoadX509KeyPair(CertPath, KeyPath)
	if err != nil {
		log.Fatalf("Failed to load cert pair for Q and R connecton. %s\n", err.Error())
	}

	// Setup TLS connection for the Queue and Resource communication
	qandrTLSConfig := &tls.Config{}
	qandrTLSConfig.Certificates = make([]tls.Certificate, 1)
	qandrTLSConfig.Certificates[0] = tlscert
	qandrTLSConfig.RootCAs = caPool
	qandrTLSConfig.ClientCAs = caPool
	qandrTLSConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_AES_128_CBC_SHA,
		tls.TLS_RSA_WITH_AES_256_CBC_SHA,
		tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
		tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
		tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
		tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
		tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
		tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}
	qandrTLSConfig.MinVersion = tls.VersionTLS12
	qandrTLSConfig.SessionTicketsDisabled = true

	// Check if we are using a different TLS configuration for the API portion of the Queue
	if useSepAPITLS {
		apiCert, err := tls.LoadX509KeyPair(APICertPath, APIKeyPath)
		if err != nil {
			log.Fatalf("API Cert and Key set, but could not be loaded. %s\n", err.Error())
		}
		apiTLSConfig := &tls.Config{
			Certificates: []tls.Certificate{apiCert},
			CipherSuites: []uint16{tls.TLS_RSA_WITH_AES_128_CBC_SHA,
				tls.TLS_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
			MinVersion:             tls.VersionTLS12,
			SessionTicketsDisabled: true,
		}

		server.TLS = apiTLSConfig
	} else {
		// No separate API key was set so use the same we did for the internal communication
		server.TLS = qandrTLSConfig
	}

	// Add some nice security stuff
	secureMiddleware := secure.New(secure.Options{
		SSLRedirect:             true,
		FrameDeny:               true,
		CustomFrameOptionsValue: "SAMEORIGIN",
		BrowserXssFilter:        true,
		IsDevelopment:           true,
	})

	// SETUP RESOURCE MANAGERS
	// Get the Authentication configuration
	confResMgr := confFile.Section("ResourceManagers")
	if confResMgr == nil {
		println("Error: Resource manager configuration is required.")
		println("See https://github.com/jmmcatee/cracklord/src/wiki/Configuration-Files.")
		return
	}

	// First, let's setup the direct connect manager if we have anything there
	if _, ok := confResMgr["directconnect"]; ok {
		resmgr_dc := directconnectresourcemanager.Setup(&server.Q, qandrTLSConfig)
		server.Q.AddResourceManager(resmgr_dc)
	}

	// Now let's setup the AWS manager if we have a config file
	if resDC, ok := confResMgr["aws"]; ok {
		resmgr_aws, err := awsresourcemanager.Setup(resDC, &server.Q, qandrTLSConfig, caCertPath, caKeyPath)
		if err != nil {
			log.WithField("error", err.Error()).Error("Unable to setup AWS resource manager.")
		} else {
			server.Q.AddResourceManager(resmgr_aws)
		}
	}

	// Build the Negroni handler
	n := negroni.New(negroni.NewRecovery(),
		cracklog.NewNegroniLogger(),
		negroni.NewStatic(http.Dir(webRoot)))

	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
	n.UseHandler(server.Router())
	log.Debug("Negroni handler started.")

	listen, err := tls.Listen("tcp", runIP+":"+runPort, server.TLS)
	if err != nil {
		println("ERROR: Unable to bind to '" + runIP + ":" + runPort + "':" + err.Error())
		return
	}

	err = http.Serve(listen, n)
	if err != nil {
		log.Fatal("Unable to start up web server: " + err.Error())
	}
}
func server(templates string) {
	// Create router
	r := mux.NewRouter()
	admin := mux.NewRouter()

	// Public routes
	r.HandleFunc("/", controllers.ReleasesJSON).Methods("GET")
	r.HandleFunc("/", controllers.PostReleasesJSON).Methods("POST")
	r.HandleFunc("/releases.json", controllers.ReleasesJSON).Methods("GET")
	r.HandleFunc("/changelog/{incremental}.txt", controllers.ChangelogFiles).Methods("GET")
	r.HandleFunc("/builds/{name}", controllers.DownloadFiles).Methods("GET")
	r.HandleFunc("/v1/build/get_delta", controllers.GetDeltaReleases)

	// Authentication
	r.HandleFunc("/login", controllers.Login)
	r.HandleFunc("/logout", controllers.Logout)
	r.HandleFunc("/authenticate", controllers.Authenticate)

	// Static content
	data := os.Getenv("OPENSHIFT_DATA_DIR")
	challenge := http.FileServer(http.Dir(data + "acme-challenge"))
	r.PathPrefix("/.well-known/acme-challenge").Handler(http.StripPrefix("/.well-known/acme-challenge", challenge))

	// Releases
	admin.HandleFunc("/admin/releases", controllers.Releases)
	admin.HandleFunc("/admin/releases/edit/{id}", controllers.EditReleases)
	admin.HandleFunc("/admin/releases/update", controllers.UpdateReleases)
	admin.HandleFunc("/admin/releases/new", controllers.NewReleases)
	admin.HandleFunc("/admin/releases/create", controllers.CreateReleases)
	admin.HandleFunc("/admin/releases/delete", controllers.DeleteReleases)
	admin.HandleFunc("/admin/releases/changelog/{id}", controllers.ChangelogReleases)

	// Files
	admin.HandleFunc("/admin/files", controllers.Files)
	admin.HandleFunc("/admin/files/show/{id}", controllers.ShowFiles)
	admin.HandleFunc("/admin/files/delete", controllers.DeleteFiles)
	admin.HandleFunc("/admin/files/refresh", controllers.RefreshFiles)

	// Users
	admin.HandleFunc("/admin/users", controllers.Users)
	admin.HandleFunc("/admin/users/delete", controllers.DeleteUsers)

	// Negroni
	secureMiddleware := secure.New(secure.Options{
		AllowedHosts:          []string{"127.0.0.1", "localhost", "builds.copperhead.co", "builds-copperheadsec.rhcloud.com"},
		SSLRedirect:           true,
		SSLProxyHeaders:       map[string]string{"X-Forwarded-Proto": "https"},
		STSSeconds:            15552000,
		STSIncludeSubdomains:  true,
		STSPreload:            true,
		FrameDeny:             true,
		ContentTypeNosniff:    true,
		BrowserXssFilter:      true,
		ContentSecurityPolicy: "default-src 'self'; style-src 'self' https://maxcdn.bootstrapcdn.com; font-src https://maxcdn.bootstrapcdn.com;",
		IsDevelopment:         false,
	})

	// Create a new negroni for the admin middleware
	r.PathPrefix("/admin").Handler(negroni.New(
		controllers.AuthMiddleware(),
		negroni.Wrap(admin),
	))

	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(dynamicPublicCaching))
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
	n.Use(cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"GET"},
		AllowedHeaders:   []string{"Origin"},
		ExposedHeaders:   []string{"Content-Length"},
		AllowCredentials: false,
	}))
	n.UseHandler(r)
	bind := fmt.Sprintf("%s:%s", os.Getenv("OPENSHIFT_GO_IP"), os.Getenv("OPENSHIFT_GO_PORT"))
	n.Run(bind)
}
Exemplo n.º 13
0
import (
	"net/http"

	"github.com/codegangsta/negroni"
	"github.com/parisianninjas/mybudget/datastore"
	"github.com/parisianninjas/mybudget/handlers"

	"github.com/unrolled/secure"

	_ "github.com/lib/pq"
)

//create a secure middleware. see https://github.com/unrolled/secure
var secureMiddleware = secure.New(secure.Options{
	FrameDeny:             true,
	ContentTypeNosniff:    true,
	BrowserXssFilter:      true,
	ContentSecurityPolicy: "default-src 'self'",
})

func main() {

	//init datasotre
	datastore.Connect(true, false)
	defer datastore.Close()

	//define routes
	m := http.NewServeMux()
	m.Handle("/api/", http.StripPrefix("/api", handlers.HandleAPI()))
	m.Handle("/", handlers.HandleWEB())

	//create negroni middleware