Exemple #1
0
// standardHttp starts serving standard HTTP (api/web) requests, to be used by normal clients
func standardHttp(discovery bool) {
	m := martini.Classic()

	switch strings.ToLower(config.Config.AuthenticationMethod) {
	case "basic":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Warning("AuthenticationMethod is configured as 'basic' but HTTPAuthUser undefined. Running without authentication.")
			}
			m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
		}
	case "multi":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Fatal("AuthenticationMethod is configured as 'multi' but HTTPAuthUser undefined")
			}

			m.Use(auth.BasicFunc(func(username, password string) bool {
				if username == "readonly" {
					// Will be treated as "read-only"
					return true
				}
				return auth.SecureCompare(username, config.Config.HTTPAuthUser) && auth.SecureCompare(password, config.Config.HTTPAuthPassword)
			}))
		}
	default:
		{
			// We inject a dummy User object because we have function signatures with User argument in api.go
			m.Map(auth.User(""))
		}
	}

	m.Use(gzip.All())
	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:       "resources",
		Layout:          "templates/layout",
		HTMLContentType: "text/html",
	}))
	m.Use(martini.Static("resources/public"))

	inst.SetMaintenanceOwner(logic.ThisHostname)

	log.Info("Starting HTTP")

	if discovery {
		go logic.ContinuousDiscovery()
	}
	inst.ReadClusterAliases()

	http.API.RegisterRequests(m)
	http.Web.RegisterRequests(m)

	// Serve
	if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil {
		log.Fatale(err)
	}
}
Exemple #2
0
func main() {
	fmt.Println("Hello, let's go!")

	//	aaa := base64.StdEncoding.EncodeToString([]byte("admin:guessme"))
	//	fmt.Println(aaa)

	mongodb.Init()

	m := martini.Classic()

	m.Use(auth.BasicFunc(func(username, password string) bool {
		fmt.Println("username = "******"password = "******"admin") && auth.SecureCompare(password, "guessme")
	}))

	m.Use(martini.Static("client"))
	m.Use(martini.Static("static"))

	fileServer := http.FileServer(http.Dir("./static"))
	m.Any("/apk/**", func(res http.ResponseWriter, req *http.Request) {
		fmt.Println("/apk/")
		fileServer.ServeHTTP(res, req)
	})

	m.Use(render.Renderer(render.Options{
		Directory:  "templates",
		Layout:     "layout",
		Extensions: []string{".tmpl", ".html"},
	}))

	route.Route(m)

	appmanager.Init()
	appmanager.RouteApi(m)

	m.Run()
}
Exemple #3
0
// Basic returns a Handler that authenticates via Basic Auth. Writes a http.StatusUnauthorized
// if authentication fails
func SpecAuth(username string, password string, apiPath string) http.HandlerFunc {
	var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
	return func(res http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/"+apiPath {
			return
		}

		authHeader := req.Header.Get("Authorization")
		if !auth.SecureCompare(authHeader, "Basic "+siteAuth) {
			res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		}
	}
}
Exemple #4
0
func CreateNewToken(tr *TokenRequest) (token string, err error) {
	sig := tr.Signature           // signature passed in
	csig := tr.ComputeSignature() // computed signature based on what was passed
	log.Println("supplied signature:", sig)
	log.Println("computed signature:", csig)
	if !auth.SecureCompare(csig, sig) {
		// provided signature doesn't match what was computed
		log.Printf("client supplied:%+v\n", tr)
		err = errors.New("Invalid Token Request Signature")
		return
	}
	chash := tr.ComputeHash(tr.UserKey, getUserSecret(tr.UserKey))
	hash := tr.UserHash
	if !auth.SecureCompare(chash, hash) {
		// provided userhash doesn't match what was computed
		log.Printf("client supplied:%+v\n", tr)
		err = errors.New("Invalid Token Request User Hash")
		return
	}
	chash = tr.ComputeHash(tr.AppKey, getAppSecret(tr.AppKey))
	hash = tr.AppHash
	if !auth.SecureCompare(chash, hash) {
		// provided userhash doesn't match what was computed
		log.Printf("client supplied:%+v\n", tr)
		err = errors.New("Invalid Token Request App Hash")
		return
	}
	if !appAuthHandler(tr.AppKey, tr.UserKey) {
		// provided userhash doesn't match what was computed
		log.Printf("client supplied:%+v\n", tr)
		err = errors.New("User has not authorized this App")
		return
	}
	token = saveToken(tr.AppKey, tr.UserKey, genRandomToken())
	return
}
Exemple #5
0
func TokenAuthHandler(h http.Handler) http.Handler {
	token := getAuthToken()
	handler := func(res http.ResponseWriter, req *http.Request) {
		err := req.ParseForm()
		if err != nil {
			log.Println("Error processing the form:", err)
		}
		givenToken := req.Form.Get("access_token")
		if req.URL.Path != "/" && !auth.SecureCompare(givenToken, token) {
			res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		} else {
			h.ServeHTTP(res, req)
		}
	}
	return http.HandlerFunc(handler)
}
Exemple #6
0
func AuthRequired(res http.ResponseWriter, req *http.Request) {
	fmt.Println("AUTH REQUIRED")
	authHdr := req.Header.Get("X-Authorization")
	fmt.Println("Ahdr:", authHdr)

	patt := regexp.MustCompile(`(\S+) (\S+);(\d+):(\S+)`)
	m := patt.FindSubmatch([]byte(authHdr))
	if len(m) == 0 {
		http.Error(res, "Not Authorized - Invalid Authorization Header", http.StatusUnauthorized)
		return
	}

	authType := string(m[1])
	token := string(m[2])
	nonce := atoi(string(m[3]))
	sig := string(m[4])
	fmt.Println("T:", authType, "t:", token, "n:", nonce, "s:", sig)

	fmt.Println("token=", token)
	lastTokenData := getTokenData(token)
	if lastTokenData == nil || authType != lastTokenData.Response.AuthType {
		http.Error(res, "Not Authorized - Invalid Token or AuthType", http.StatusUnauthorized)
		return
	}
	if nonce <= lastTokenData.Nonce {
		http.Error(res, "Not Authorized - Invalid Nonce", http.StatusUnauthorized)
		return
	}

	secret := getAppSecret(lastTokenData.Request.AppKey)
	cHdr := lastTokenData.Response.AuthHeaderString(secret, fmt.Sprintf("%d", nonce))
	//computedSig := ComputeHmacSHA1(msg, secret)
	if !auth.SecureCompare(authHdr, cHdr) {
		http.Error(res, "Not Authorized - Invalid Header/Sig", http.StatusUnauthorized)
		return
	}

	lastTokenData.Nonce = nonce
	saveTokenData(token, lastTokenData)
}
Exemple #7
0
// standardHttp starts serving HTTP or HTTPS (api/web) requests, to be used by normal clients
func standardHttp(discovery bool) {
	m := martini.Classic()

	switch strings.ToLower(config.Config.AuthenticationMethod) {
	case "basic":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Warning("AuthenticationMethod is configured as 'basic' but HTTPAuthUser undefined. Running without authentication.")
			}
			m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword))
		}
	case "multi":
		{
			if config.Config.HTTPAuthUser == "" {
				// Still allowed; may be disallowed in future versions
				log.Fatal("AuthenticationMethod is configured as 'multi' but HTTPAuthUser undefined")
			}

			m.Use(auth.BasicFunc(func(username, password string) bool {
				if username == "readonly" {
					// Will be treated as "read-only"
					return true
				}
				return auth.SecureCompare(username, config.Config.HTTPAuthUser) && auth.SecureCompare(password, config.Config.HTTPAuthPassword)
			}))
		}
	default:
		{
			// We inject a dummy User object because we have function signatures with User argument in api.go
			m.Map(auth.User(""))
		}
	}

	m.Use(gzip.All())
	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Directory:       "resources",
		Layout:          "templates/layout",
		HTMLContentType: "text/html",
	}))
	m.Use(martini.Static("resources/public"))
	if config.Config.UseMutualTLS {
		m.Use(ssl.VerifyOUs(config.Config.SSLValidOUs))
	}

	inst.SetMaintenanceOwner(process.ThisHostname)

	if discovery {
		log.Info("Starting Discovery")
		go logic.ContinuousDiscovery()
	}
	log.Info("Registering endpoints")
	http.API.RegisterRequests(m)
	http.Web.RegisterRequests(m)

	// Serve
	if config.Config.ListenSocket != "" {
		log.Infof("Starting HTTP listener on unix socket %v", config.Config.ListenSocket)
		unixListener, err := net.Listen("unix", config.Config.ListenSocket)
		if err != nil {
			log.Fatale(err)
		}
		defer unixListener.Close()
		if err := nethttp.Serve(unixListener, m); err != nil {
			log.Fatale(err)
		}
	} else if config.Config.UseSSL {
		log.Info("Starting HTTPS listener")
		tlsConfig, err := ssl.NewTLSConfig(config.Config.SSLCAFile, config.Config.UseMutualTLS)
		if err != nil {
			log.Fatale(err)
		}
		tlsConfig.InsecureSkipVerify = config.Config.SSLSkipVerify
		if err = ssl.AppendKeyPairWithPassword(tlsConfig, config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, sslPEMPassword); err != nil {
			log.Fatale(err)
		}
		if err = ssl.ListenAndServeTLS(config.Config.ListenAddress, m, tlsConfig); err != nil {
			log.Fatale(err)
		}
	} else {
		log.Infof("Starting HTTP listener on %+v", config.Config.ListenAddress)
		if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil {
			log.Fatale(err)
		}
	}
	log.Info("Web server started")
}
Exemple #8
0
func Auth(res http.ResponseWriter, req *http.Request) {
	secret := "abc123"
	if auth.SecureCompare(req.Header.Get("Validation"), secret) != true {
		http.Error(res, "Unauthorized", 401)
	}
}
Exemple #9
0
func authFunc(username, password string) bool {
	return (auth.SecureCompare(username, "admin") && auth.SecureCompare(password, "!!!!VVjhsdsajdbabjd1")) || (auth.SecureCompare(username, "mars") && auth.SecureCompare(password, "Verbat1mert")) || (auth.SecureCompare(username, "oilnur") && auth.SecureCompare(password, "Verbat1mqwe"))
}