Add single sign-on support via SSPI on Windows (#8463)
* Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not acceptedtokarchuk/v1.17
parent
eb1b225d9a
commit
7b4d2f7a2a
@ -0,0 +1,125 @@ |
|||||||
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"strings" |
||||||
|
|
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
"code.gitea.io/gitea/modules/base" |
||||||
|
"code.gitea.io/gitea/modules/log" |
||||||
|
"code.gitea.io/gitea/modules/setting" |
||||||
|
"code.gitea.io/gitea/modules/timeutil" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
) |
||||||
|
|
||||||
|
// Ensure the struct implements the interface.
|
||||||
|
var ( |
||||||
|
_ SingleSignOn = &Basic{} |
||||||
|
) |
||||||
|
|
||||||
|
// Basic implements the SingleSignOn interface and authenticates requests (API requests
|
||||||
|
// only) by looking for Basic authentication data or "x-oauth-basic" token in the "Authorization"
|
||||||
|
// header.
|
||||||
|
type Basic struct { |
||||||
|
} |
||||||
|
|
||||||
|
// Init does nothing as the Basic implementation does not need to allocate any resources
|
||||||
|
func (b *Basic) Init() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Free does nothing as the Basic implementation does not have to release any resources
|
||||||
|
func (b *Basic) Free() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// IsEnabled returns true as this plugin is enabled by default and its not possible to disable
|
||||||
|
// it from settings.
|
||||||
|
func (b *Basic) IsEnabled() bool { |
||||||
|
return setting.Service.EnableBasicAuth |
||||||
|
} |
||||||
|
|
||||||
|
// VerifyAuthData extracts and validates Basic data (username and password/token) from the
|
||||||
|
// "Authorization" header of the request and returns the corresponding user object for that
|
||||||
|
// name/token on successful validation.
|
||||||
|
// Returns nil if header is empty or validation fails.
|
||||||
|
func (b *Basic) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User { |
||||||
|
baHead := ctx.Req.Header.Get("Authorization") |
||||||
|
if len(baHead) == 0 { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
auths := strings.Fields(baHead) |
||||||
|
if len(auths) != 2 || auths[0] != "Basic" { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
var u *models.User |
||||||
|
uname, passwd, _ := base.BasicAuthDecode(auths[1]) |
||||||
|
|
||||||
|
// Check if username or password is a token
|
||||||
|
isUsernameToken := len(passwd) == 0 || passwd == "x-oauth-basic" |
||||||
|
// Assume username is token
|
||||||
|
authToken := uname |
||||||
|
if !isUsernameToken { |
||||||
|
// Assume password is token
|
||||||
|
authToken = passwd |
||||||
|
} |
||||||
|
|
||||||
|
uid := CheckOAuthAccessToken(authToken) |
||||||
|
if uid != 0 { |
||||||
|
var err error |
||||||
|
ctx.Data["IsApiToken"] = true |
||||||
|
|
||||||
|
u, err = models.GetUserByID(uid) |
||||||
|
if err != nil { |
||||||
|
log.Error("GetUserByID: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
} |
||||||
|
token, err := models.GetAccessTokenBySHA(authToken) |
||||||
|
if err == nil { |
||||||
|
if isUsernameToken { |
||||||
|
u, err = models.GetUserByID(token.UID) |
||||||
|
if err != nil { |
||||||
|
log.Error("GetUserByID: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
} else { |
||||||
|
u, err = models.GetUserByName(uname) |
||||||
|
if err != nil { |
||||||
|
log.Error("GetUserByID: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
if u.ID != token.UID { |
||||||
|
return nil |
||||||
|
} |
||||||
|
} |
||||||
|
token.UpdatedUnix = timeutil.TimeStampNow() |
||||||
|
if err = models.UpdateAccessToken(token); err != nil { |
||||||
|
log.Error("UpdateAccessToken: %v", err) |
||||||
|
} |
||||||
|
} else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) { |
||||||
|
log.Error("GetAccessTokenBySha: %v", err) |
||||||
|
} |
||||||
|
|
||||||
|
if u == nil { |
||||||
|
u, err = models.UserSignIn(uname, passwd) |
||||||
|
if err != nil { |
||||||
|
if !models.IsErrUserNotExist(err) { |
||||||
|
log.Error("UserSignIn: %v", err) |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
} else { |
||||||
|
ctx.Data["IsApiToken"] = true |
||||||
|
} |
||||||
|
|
||||||
|
return u |
||||||
|
} |
@ -0,0 +1,33 @@ |
|||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
) |
||||||
|
|
||||||
|
// SingleSignOn represents a SSO authentication method (plugin) for HTTP requests.
|
||||||
|
type SingleSignOn interface { |
||||||
|
// Init should be called exactly once before using any of the other methods,
|
||||||
|
// in order to allow the plugin to allocate necessary resources
|
||||||
|
Init() error |
||||||
|
|
||||||
|
// Free should be called exactly once before application closes, in order to
|
||||||
|
// give chance to the plugin to free any allocated resources
|
||||||
|
Free() error |
||||||
|
|
||||||
|
// IsEnabled checks if the current SSO method has been enabled in settings.
|
||||||
|
IsEnabled() bool |
||||||
|
|
||||||
|
// VerifyAuthData tries to verify the SSO authentication data contained in the request.
|
||||||
|
// If verification is successful returns either an existing user object (with id > 0)
|
||||||
|
// or a new user object (with id = 0) populated with the information that was found
|
||||||
|
// in the authentication data (username or email).
|
||||||
|
// Returns nil if verification fails.
|
||||||
|
VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User |
||||||
|
} |
@ -0,0 +1,142 @@ |
|||||||
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"strings" |
||||||
|
"time" |
||||||
|
|
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
"code.gitea.io/gitea/modules/log" |
||||||
|
"code.gitea.io/gitea/modules/timeutil" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
) |
||||||
|
|
||||||
|
// Ensure the struct implements the interface.
|
||||||
|
var ( |
||||||
|
_ SingleSignOn = &OAuth2{} |
||||||
|
) |
||||||
|
|
||||||
|
// CheckOAuthAccessToken returns uid of user from oauth token
|
||||||
|
func CheckOAuthAccessToken(accessToken string) int64 { |
||||||
|
// JWT tokens require a "."
|
||||||
|
if !strings.Contains(accessToken, ".") { |
||||||
|
return 0 |
||||||
|
} |
||||||
|
token, err := models.ParseOAuth2Token(accessToken) |
||||||
|
if err != nil { |
||||||
|
log.Trace("ParseOAuth2Token: %v", err) |
||||||
|
return 0 |
||||||
|
} |
||||||
|
var grant *models.OAuth2Grant |
||||||
|
if grant, err = models.GetOAuth2GrantByID(token.GrantID); err != nil || grant == nil { |
||||||
|
return 0 |
||||||
|
} |
||||||
|
if token.Type != models.TypeAccessToken { |
||||||
|
return 0 |
||||||
|
} |
||||||
|
if token.ExpiresAt < time.Now().Unix() || token.IssuedAt > time.Now().Unix() { |
||||||
|
return 0 |
||||||
|
} |
||||||
|
return grant.UserID |
||||||
|
} |
||||||
|
|
||||||
|
// OAuth2 implements the SingleSignOn interface and authenticates requests
|
||||||
|
// (API requests only) by looking for an OAuth token in query parameters or the
|
||||||
|
// "Authorization" header.
|
||||||
|
type OAuth2 struct { |
||||||
|
} |
||||||
|
|
||||||
|
// Init does nothing as the OAuth2 implementation does not need to allocate any resources
|
||||||
|
func (o *OAuth2) Init() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Free does nothing as the OAuth2 implementation does not have to release any resources
|
||||||
|
func (o *OAuth2) Free() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// userIDFromToken returns the user id corresponding to the OAuth token.
|
||||||
|
func (o *OAuth2) userIDFromToken(ctx *macaron.Context) int64 { |
||||||
|
// Check access token.
|
||||||
|
tokenSHA := ctx.Query("token") |
||||||
|
if len(tokenSHA) == 0 { |
||||||
|
tokenSHA = ctx.Query("access_token") |
||||||
|
} |
||||||
|
if len(tokenSHA) == 0 { |
||||||
|
// Well, check with header again.
|
||||||
|
auHead := ctx.Req.Header.Get("Authorization") |
||||||
|
if len(auHead) > 0 { |
||||||
|
auths := strings.Fields(auHead) |
||||||
|
if len(auths) == 2 && (auths[0] == "token" || strings.ToLower(auths[0]) == "bearer") { |
||||||
|
tokenSHA = auths[1] |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
if len(tokenSHA) == 0 { |
||||||
|
return 0 |
||||||
|
} |
||||||
|
|
||||||
|
// Let's see if token is valid.
|
||||||
|
if strings.Contains(tokenSHA, ".") { |
||||||
|
uid := CheckOAuthAccessToken(tokenSHA) |
||||||
|
if uid != 0 { |
||||||
|
ctx.Data["IsApiToken"] = true |
||||||
|
} |
||||||
|
return uid |
||||||
|
} |
||||||
|
t, err := models.GetAccessTokenBySHA(tokenSHA) |
||||||
|
if err != nil { |
||||||
|
if models.IsErrAccessTokenNotExist(err) || models.IsErrAccessTokenEmpty(err) { |
||||||
|
log.Error("GetAccessTokenBySHA: %v", err) |
||||||
|
} |
||||||
|
return 0 |
||||||
|
} |
||||||
|
t.UpdatedUnix = timeutil.TimeStampNow() |
||||||
|
if err = models.UpdateAccessToken(t); err != nil { |
||||||
|
log.Error("UpdateAccessToken: %v", err) |
||||||
|
} |
||||||
|
ctx.Data["IsApiToken"] = true |
||||||
|
return t.UID |
||||||
|
} |
||||||
|
|
||||||
|
// IsEnabled returns true as this plugin is enabled by default and its not possible
|
||||||
|
// to disable it from settings.
|
||||||
|
func (o *OAuth2) IsEnabled() bool { |
||||||
|
return true |
||||||
|
} |
||||||
|
|
||||||
|
// VerifyAuthData extracts the user ID from the OAuth token in the query parameters
|
||||||
|
// or the "Authorization" header and returns the corresponding user object for that ID.
|
||||||
|
// If verification is successful returns an existing user object.
|
||||||
|
// Returns nil if verification fails.
|
||||||
|
func (o *OAuth2) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User { |
||||||
|
if !models.HasEngine { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
if !isAPIPath(ctx) && !isAttachmentDownload(ctx) { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
id := o.userIDFromToken(ctx) |
||||||
|
if id <= 0 { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
user, err := models.GetUserByID(id) |
||||||
|
if err != nil { |
||||||
|
if !models.IsErrUserNotExist(err) { |
||||||
|
log.Error("GetUserByName: %v", err) |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
return user |
||||||
|
} |
@ -0,0 +1,115 @@ |
|||||||
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"strings" |
||||||
|
|
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
"code.gitea.io/gitea/modules/log" |
||||||
|
"code.gitea.io/gitea/modules/setting" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
gouuid "github.com/satori/go.uuid" |
||||||
|
) |
||||||
|
|
||||||
|
// Ensure the struct implements the interface.
|
||||||
|
var ( |
||||||
|
_ SingleSignOn = &ReverseProxy{} |
||||||
|
) |
||||||
|
|
||||||
|
// ReverseProxy implements the SingleSignOn interface, but actually relies on
|
||||||
|
// a reverse proxy for authentication of users.
|
||||||
|
// On successful authentication the proxy is expected to populate the username in the
|
||||||
|
// "setting.ReverseProxyAuthUser" header. Optionally it can also populate the email of the
|
||||||
|
// user in the "setting.ReverseProxyAuthEmail" header.
|
||||||
|
type ReverseProxy struct { |
||||||
|
} |
||||||
|
|
||||||
|
// getUserName extracts the username from the "setting.ReverseProxyAuthUser" header
|
||||||
|
func (r *ReverseProxy) getUserName(ctx *macaron.Context) string { |
||||||
|
webAuthUser := strings.TrimSpace(ctx.Req.Header.Get(setting.ReverseProxyAuthUser)) |
||||||
|
if len(webAuthUser) == 0 { |
||||||
|
return "" |
||||||
|
} |
||||||
|
return webAuthUser |
||||||
|
} |
||||||
|
|
||||||
|
// Init does nothing as the ReverseProxy implementation does not need initialization
|
||||||
|
func (r *ReverseProxy) Init() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Free does nothing as the ReverseProxy implementation does not have to release resources
|
||||||
|
func (r *ReverseProxy) Free() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// IsEnabled checks if EnableReverseProxyAuth setting is true
|
||||||
|
func (r *ReverseProxy) IsEnabled() bool { |
||||||
|
return setting.Service.EnableReverseProxyAuth |
||||||
|
} |
||||||
|
|
||||||
|
// VerifyAuthData extracts the username from the "setting.ReverseProxyAuthUser" header
|
||||||
|
// of the request and returns the corresponding user object for that name.
|
||||||
|
// Verification of header data is not performed as it should have already been done by
|
||||||
|
// the revese proxy.
|
||||||
|
// If a username is available in the "setting.ReverseProxyAuthUser" header an existing
|
||||||
|
// user object is returned (populated with username or email found in header).
|
||||||
|
// Returns nil if header is empty.
|
||||||
|
func (r *ReverseProxy) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User { |
||||||
|
username := r.getUserName(ctx) |
||||||
|
if len(username) == 0 { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
user, err := models.GetUserByName(username) |
||||||
|
if err != nil { |
||||||
|
if models.IsErrUserNotExist(err) && r.isAutoRegisterAllowed() { |
||||||
|
return r.newUser(ctx) |
||||||
|
} |
||||||
|
log.Error("GetUserByName: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
return user |
||||||
|
} |
||||||
|
|
||||||
|
// isAutoRegisterAllowed checks if EnableReverseProxyAutoRegister setting is true
|
||||||
|
func (r *ReverseProxy) isAutoRegisterAllowed() bool { |
||||||
|
return setting.Service.EnableReverseProxyAutoRegister |
||||||
|
} |
||||||
|
|
||||||
|
// newUser creates a new user object for the purpose of automatic registration
|
||||||
|
// and populates its name and email with the information present in request headers.
|
||||||
|
func (r *ReverseProxy) newUser(ctx *macaron.Context) *models.User { |
||||||
|
username := r.getUserName(ctx) |
||||||
|
if len(username) == 0 { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
email := gouuid.NewV4().String() + "@localhost" |
||||||
|
if setting.Service.EnableReverseProxyEmail { |
||||||
|
webAuthEmail := ctx.Req.Header.Get(setting.ReverseProxyAuthEmail) |
||||||
|
if len(webAuthEmail) > 0 { |
||||||
|
email = webAuthEmail |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
user := &models.User{ |
||||||
|
Name: username, |
||||||
|
Email: email, |
||||||
|
Passwd: username, |
||||||
|
IsActive: true, |
||||||
|
} |
||||||
|
if err := models.CreateUser(user); err != nil { |
||||||
|
// FIXME: should I create a system notice?
|
||||||
|
log.Error("CreateUser: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
return user |
||||||
|
} |
@ -0,0 +1,49 @@ |
|||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
) |
||||||
|
|
||||||
|
// Ensure the struct implements the interface.
|
||||||
|
var ( |
||||||
|
_ SingleSignOn = &Session{} |
||||||
|
) |
||||||
|
|
||||||
|
// Session checks if there is a user uid stored in the session and returns the user
|
||||||
|
// object for that uid.
|
||||||
|
type Session struct { |
||||||
|
} |
||||||
|
|
||||||
|
// Init does nothing as the Session implementation does not need to allocate any resources
|
||||||
|
func (s *Session) Init() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Free does nothing as the Session implementation does not have to release any resources
|
||||||
|
func (s *Session) Free() error { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// IsEnabled returns true as this plugin is enabled by default and its not possible to disable
|
||||||
|
// it from settings.
|
||||||
|
func (s *Session) IsEnabled() bool { |
||||||
|
return true |
||||||
|
} |
||||||
|
|
||||||
|
// VerifyAuthData checks if there is a user uid stored in the session and returns the user
|
||||||
|
// object for that uid.
|
||||||
|
// Returns nil if there is no user uid stored in the session.
|
||||||
|
func (s *Session) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User { |
||||||
|
user := SessionUser(sess) |
||||||
|
if user != nil { |
||||||
|
return user |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
@ -0,0 +1,141 @@ |
|||||||
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"fmt" |
||||||
|
"reflect" |
||||||
|
"strings" |
||||||
|
|
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
"code.gitea.io/gitea/modules/log" |
||||||
|
"code.gitea.io/gitea/modules/setting" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
) |
||||||
|
|
||||||
|
// ssoMethods contains the list of SSO authentication plugins in the order they are expected to be
|
||||||
|
// executed.
|
||||||
|
//
|
||||||
|
// The OAuth2 plugin is expected to be executed first, as it must ignore the user id stored
|
||||||
|
// in the session (if there is a user id stored in session other plugins might return the user
|
||||||
|
// object for that id).
|
||||||
|
//
|
||||||
|
// The Session plugin is expected to be executed second, in order to skip authentication
|
||||||
|
// for users that have already signed in.
|
||||||
|
var ssoMethods = []SingleSignOn{ |
||||||
|
&OAuth2{}, |
||||||
|
&Session{}, |
||||||
|
&ReverseProxy{}, |
||||||
|
&Basic{}, |
||||||
|
} |
||||||
|
|
||||||
|
// The purpose of the following three function variables is to let the linter know that
|
||||||
|
// those functions are not dead code and are actually being used
|
||||||
|
var ( |
||||||
|
_ = handleSignIn |
||||||
|
) |
||||||
|
|
||||||
|
// Methods returns the instances of all registered SSO methods
|
||||||
|
func Methods() []SingleSignOn { |
||||||
|
return ssoMethods |
||||||
|
} |
||||||
|
|
||||||
|
// Register adds the specified instance to the list of available SSO methods
|
||||||
|
func Register(method SingleSignOn) { |
||||||
|
ssoMethods = append(ssoMethods, method) |
||||||
|
} |
||||||
|
|
||||||
|
// Init should be called exactly once when the application starts to allow SSO plugins
|
||||||
|
// to allocate necessary resources
|
||||||
|
func Init() { |
||||||
|
for _, method := range Methods() { |
||||||
|
err := method.Init() |
||||||
|
if err != nil { |
||||||
|
log.Error("Could not initialize '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err) |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Free should be called exactly once when the application is terminating to allow SSO plugins
|
||||||
|
// to release necessary resources
|
||||||
|
func Free() { |
||||||
|
for _, method := range Methods() { |
||||||
|
err := method.Free() |
||||||
|
if err != nil { |
||||||
|
log.Error("Could not free '%s' SSO method, error: %s", reflect.TypeOf(method).String(), err) |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// SessionUser returns the user object corresponding to the "uid" session variable.
|
||||||
|
func SessionUser(sess session.Store) *models.User { |
||||||
|
// Get user ID
|
||||||
|
uid := sess.Get("uid") |
||||||
|
if uid == nil { |
||||||
|
return nil |
||||||
|
} |
||||||
|
id, ok := uid.(int64) |
||||||
|
if !ok { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Get user object
|
||||||
|
user, err := models.GetUserByID(id) |
||||||
|
if err != nil { |
||||||
|
if !models.IsErrUserNotExist(err) { |
||||||
|
log.Error("GetUserById: %v", err) |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
return user |
||||||
|
} |
||||||
|
|
||||||
|
// isAPIPath returns true if the specified URL is an API path
|
||||||
|
func isAPIPath(ctx *macaron.Context) bool { |
||||||
|
return strings.HasPrefix(ctx.Req.URL.Path, "/api/") |
||||||
|
} |
||||||
|
|
||||||
|
// isAttachmentDownload check if request is a file download (GET) with URL to an attachment
|
||||||
|
func isAttachmentDownload(ctx *macaron.Context) bool { |
||||||
|
return strings.HasPrefix(ctx.Req.URL.Path, "/attachments/") && ctx.Req.Method == "GET" |
||||||
|
} |
||||||
|
|
||||||
|
// handleSignIn clears existing session variables and stores new ones for the specified user object
|
||||||
|
func handleSignIn(ctx *macaron.Context, sess session.Store, user *models.User) { |
||||||
|
_ = sess.Delete("openid_verified_uri") |
||||||
|
_ = sess.Delete("openid_signin_remember") |
||||||
|
_ = sess.Delete("openid_determined_email") |
||||||
|
_ = sess.Delete("openid_determined_username") |
||||||
|
_ = sess.Delete("twofaUid") |
||||||
|
_ = sess.Delete("twofaRemember") |
||||||
|
_ = sess.Delete("u2fChallenge") |
||||||
|
_ = sess.Delete("linkAccount") |
||||||
|
err := sess.Set("uid", user.ID) |
||||||
|
if err != nil { |
||||||
|
log.Error(fmt.Sprintf("Error setting session: %v", err)) |
||||||
|
} |
||||||
|
err = sess.Set("uname", user.Name) |
||||||
|
if err != nil { |
||||||
|
log.Error(fmt.Sprintf("Error setting session: %v", err)) |
||||||
|
} |
||||||
|
|
||||||
|
// Language setting of the user overwrites the one previously set
|
||||||
|
// If the user does not have a locale set, we save the current one.
|
||||||
|
if len(user.Language) == 0 { |
||||||
|
user.Language = ctx.Locale.Language() |
||||||
|
if err := models.UpdateUserCols(user, "language"); err != nil { |
||||||
|
log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", user.ID, user.Language)) |
||||||
|
return |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
ctx.SetCookie("lang", user.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) |
||||||
|
|
||||||
|
// Clear whatever CSRF has right now, force to generate a new one
|
||||||
|
ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) |
||||||
|
} |
@ -0,0 +1,237 @@ |
|||||||
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a MIT-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package sso |
||||||
|
|
||||||
|
import ( |
||||||
|
"errors" |
||||||
|
"reflect" |
||||||
|
"strings" |
||||||
|
|
||||||
|
"code.gitea.io/gitea/models" |
||||||
|
"code.gitea.io/gitea/modules/base" |
||||||
|
"code.gitea.io/gitea/modules/log" |
||||||
|
"code.gitea.io/gitea/modules/setting" |
||||||
|
|
||||||
|
"gitea.com/macaron/macaron" |
||||||
|
"gitea.com/macaron/session" |
||||||
|
|
||||||
|
"github.com/quasoft/websspi" |
||||||
|
gouuid "github.com/satori/go.uuid" |
||||||
|
) |
||||||
|
|
||||||
|
const ( |
||||||
|
tplSignIn base.TplName = "user/auth/signin" |
||||||
|
) |
||||||
|
|
||||||
|
var ( |
||||||
|
// sspiAuth is a global instance of the websspi authentication package,
|
||||||
|
// which is used to avoid acquiring the server credential handle on
|
||||||
|
// every request
|
||||||
|
sspiAuth *websspi.Authenticator |
||||||
|
|
||||||
|
// Ensure the struct implements the interface.
|
||||||
|
_ SingleSignOn = &SSPI{} |
||||||
|
) |
||||||
|
|
||||||
|
// SSPI implements the SingleSignOn interface and authenticates requests
|
||||||
|
// via the built-in SSPI module in Windows for SPNEGO authentication.
|
||||||
|
// On successful authentication returns a valid user object.
|
||||||
|
// Returns nil if authentication fails.
|
||||||
|
type SSPI struct { |
||||||
|
} |
||||||
|
|
||||||
|
// Init creates a new global websspi.Authenticator object
|
||||||
|
func (s *SSPI) Init() error { |
||||||
|
config := websspi.NewConfig() |
||||||
|
var err error |
||||||
|
sspiAuth, err = websspi.New(config) |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
// Free releases resources used by the global websspi.Authenticator object
|
||||||
|
func (s *SSPI) Free() error { |
||||||
|
return sspiAuth.Free() |
||||||
|
} |
||||||
|
|
||||||
|
// IsEnabled checks if there is an active SSPI authentication source
|
||||||
|
func (s *SSPI) IsEnabled() bool { |
||||||
|
return models.IsSSPIEnabled() |
||||||
|
} |
||||||
|
|
||||||
|
// VerifyAuthData uses SSPI (Windows implementation of SPNEGO) to authenticate the request.
|
||||||
|
// If authentication is successful, returs the corresponding user object.
|
||||||
|
// If negotiation should continue or authentication fails, immediately returns a 401 HTTP
|
||||||
|
// response code, as required by the SPNEGO protocol.
|
||||||
|
func (s *SSPI) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User { |
||||||
|
if !s.shouldAuthenticate(ctx) { |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
cfg, err := s.getConfig() |
||||||
|
if err != nil { |
||||||
|
log.Error("could not get SSPI config: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
userInfo, outToken, err := sspiAuth.Authenticate(ctx.Req.Request, ctx.Resp) |
||||||
|
if err != nil { |
||||||
|
log.Warn("Authentication failed with error: %v\n", err) |
||||||
|
sspiAuth.AppendAuthenticateHeader(ctx.Resp, outToken) |
||||||
|
|
||||||
|
// Include the user login page in the 401 response to allow the user
|
||||||
|
// to login with another authentication method if SSPI authentication
|
||||||
|
// fails
|
||||||
|
addFlashErr(ctx, ctx.Tr("auth.sspi_auth_failed")) |
||||||
|
ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn |
||||||
|
ctx.Data["EnableSSPI"] = true |
||||||
|
ctx.HTML(401, string(tplSignIn)) |
||||||
|
return nil |
||||||
|
} |
||||||
|
if outToken != "" { |
||||||
|
sspiAuth.AppendAuthenticateHeader(ctx.Resp, outToken) |
||||||
|
} |
||||||
|
|
||||||
|
username := sanitizeUsername(userInfo.Username, cfg) |
||||||
|
if len(username) == 0 { |
||||||
|
return nil |
||||||
|
} |
||||||
|
log.Info("Authenticated as %s\n", username) |
||||||
|
|
||||||
|
user, err := models.GetUserByName(username) |
||||||
|
if err != nil { |
||||||
|
if !models.IsErrUserNotExist(err) { |
||||||
|
log.Error("GetUserByName: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
if !cfg.AutoCreateUsers { |
||||||
|
log.Error("User '%s' not found", username) |
||||||
|
return nil |
||||||
|
} |
||||||
|
user, err = s.newUser(ctx, username, cfg) |
||||||
|
if err != nil { |
||||||
|
log.Error("CreateUser: %v", err) |
||||||
|
return nil |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Make sure requests to API paths and PWA resources do not create a new session
|
||||||
|
if !isAPIPath(ctx) && !isAttachmentDownload(ctx) { |
||||||
|
handleSignIn(ctx, sess, user) |
||||||
|
} |
||||||
|
|
||||||
|
return user |
||||||
|
} |
||||||
|
|
||||||
|
// getConfig retrieves the SSPI configuration from login sources
|
||||||
|
func (s *SSPI) getConfig() (*models.SSPIConfig, error) { |
||||||
|
sources, err := models.ActiveLoginSources(models.LoginSSPI) |
||||||
|
if err != nil { |
||||||
|
return nil, err |
||||||
|
} |
||||||
|
if len(sources) == 0 { |
||||||
|
return nil, errors.New("no active login sources of type SSPI found") |
||||||
|
} |
||||||
|
if len(sources) > 1 { |
||||||
|
return nil, errors.New("more than one active login source of type SSPI found") |
||||||
|
} |
||||||
|
return sources[0].SSPI(), nil |
||||||
|
} |
||||||
|
|
||||||
|
func (s *SSPI) shouldAuthenticate(ctx *macaron.Context) (shouldAuth bool) { |
||||||
|
shouldAuth = false |
||||||
|
path := strings.TrimSuffix(ctx.Req.URL.Path, "/") |
||||||
|
if path == "/user/login" { |
||||||
|
if ctx.Req.FormValue("user_name") != "" && ctx.Req.FormValue("password") != "" { |
||||||
|
shouldAuth = false |
||||||
|
} else if ctx.Req.FormValue("auth_with_sspi") == "1" { |
||||||
|
shouldAuth = true |
||||||
|
} |
||||||
|
} else if isAPIPath(ctx) || isAttachmentDownload(ctx) { |
||||||
|
shouldAuth = true |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// newUser creates a new user object for the purpose of automatic registration
|
||||||
|
// and populates its name and email with the information present in request headers.
|
||||||
|
func (s *SSPI) newUser(ctx *macaron.Context, username string, cfg *models.SSPIConfig) (*models.User, error) { |
||||||
|
email := gouuid.NewV4().String() + "@localhost.localdomain" |
||||||
|
user := &models.User{ |
||||||
|
Name: username, |
||||||
|
Email: email, |
||||||
|
KeepEmailPrivate: true, |
||||||
|
Passwd: gouuid.NewV4().String(), |
||||||
|
IsActive: cfg.AutoActivateUsers, |
||||||
|
Language: cfg.DefaultLanguage, |
||||||
|
UseCustomAvatar: true, |
||||||
|
Avatar: base.DefaultAvatarLink(), |
||||||
|
EmailNotificationsPreference: models.EmailNotificationsDisabled, |
||||||
|
} |
||||||
|
if err := models.CreateUser(user); err != nil { |
||||||
|
return nil, err |
||||||
|
} |
||||||
|
return user, nil |
||||||
|
} |
||||||
|
|
||||||
|
// stripDomainNames removes NETBIOS domain name and separator from down-level logon names
|
||||||
|
// (eg. "DOMAIN\user" becomes "user"), and removes the UPN suffix (domain name) and separator
|
||||||
|
// from UPNs (eg. "user@domain.local" becomes "user")
|
||||||
|
func stripDomainNames(username string) string { |
||||||
|
if strings.Contains(username, "\\") { |
||||||
|
parts := strings.SplitN(username, "\\", 2) |
||||||
|
if len(parts) > 1 { |
||||||
|
username = parts[1] |
||||||
|
} |
||||||
|
} else if strings.Contains(username, "@") { |
||||||
|
parts := strings.Split(username, "@") |
||||||
|
if len(parts) > 1 { |
||||||
|
username = parts[0] |
||||||
|
} |
||||||
|
} |
||||||
|
return username |
||||||
|
} |
||||||
|
|
||||||
|
func replaceSeparators(username string, cfg *models.SSPIConfig) string { |
||||||
|
newSep := cfg.SeparatorReplacement |
||||||
|
username = strings.ReplaceAll(username, "\\", newSep) |
||||||
|
username = strings.ReplaceAll(username, "/", newSep) |
||||||
|
username = strings.ReplaceAll(username, "@", newSep) |
||||||
|
return username |
||||||
|
} |
||||||
|
|
||||||
|
func sanitizeUsername(username string, cfg *models.SSPIConfig) string { |
||||||
|
if len(username) == 0 { |
||||||
|
return "" |
||||||
|
} |
||||||
|
if cfg.StripDomainNames { |
||||||
|
username = stripDomainNames(username) |
||||||
|
} |
||||||
|
// Replace separators even if we have already stripped the domain name part,
|
||||||
|
// as the username can contain several separators: eg. "MICROSOFT\useremail@live.com"
|
||||||
|
username = replaceSeparators(username, cfg) |
||||||
|
return username |
||||||
|
} |
||||||
|
|
||||||
|
// addFlashErr adds an error message to the Flash object mapped to a macaron.Context
|
||||||
|
func addFlashErr(ctx *macaron.Context, err string) { |
||||||
|
fv := ctx.GetVal(reflect.TypeOf(&session.Flash{})) |
||||||
|
if !fv.IsValid() { |
||||||
|
return |
||||||
|
} |
||||||
|
flash, ok := fv.Interface().(*session.Flash) |
||||||
|
if !ok { |
||||||
|
return |
||||||
|
} |
||||||
|
flash.Error(err) |
||||||
|
ctx.Data["Flash"] = flash |
||||||
|
} |
||||||
|
|
||||||
|
// init registers the SSPI auth method as the last method in the list.
|
||||||
|
// The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation
|
||||||
|
// fails (or if negotiation should continue), which would prevent other authentication methods
|
||||||
|
// to execute at all.
|
||||||
|
func init() { |
||||||
|
Register(&SSPI{}) |
||||||
|
} |
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,43 @@ |
|||||||
|
<div class="sspi field {{if not (eq .type 7)}}hide{{end}}"> |
||||||
|
<div class="field"> |
||||||
|
<div class="ui checkbox"> |
||||||
|
<label for="sspi_auto_create_users"><strong>{{.i18n.Tr "admin.auths.sspi_auto_create_users"}}</strong></label> |
||||||
|
<input id="sspi_auto_create_users" name="sspi_auto_create_users" class="sspi-auto-create-users" type="checkbox" {{if .SSPIAutoCreateUsers}}checked{{end}}> |
||||||
|
<p class="help">{{.i18n.Tr "admin.auths.sspi_auto_create_users_helper"}}</p> |
||||||
|
</div> |
||||||
|
</div> |
||||||
|
<div class="field"> |
||||||
|
<div class="ui checkbox"> |
||||||
|
<label for="sspi_auto_activate_users"><strong>{{.i18n.Tr "admin.auths.sspi_auto_activate_users"}}</strong></label> |
||||||
|
<input id="sspi_auto_activate_users" name="sspi_auto_activate_users" class="sspi-auto-activate-users" type="checkbox" {{if .SSPIAutoActivateUsers}}checked{{end}}> |
||||||
|
<p class="help">{{.i18n.Tr "admin.auths.sspi_auto_activate_users_helper"}}</p> |
||||||
|
</div> |
||||||
|
</div> |
||||||
|
<div class="field"> |
||||||
|
<div class="ui checkbox"> |
||||||
|
<label for="sspi_strip_domain_names"><strong>{{.i18n.Tr "admin.auths.sspi_strip_domain_names"}}</strong></label> |
||||||
|
<input id="sspi_strip_domain_names" name="sspi_strip_domain_names" class="sspi-strip-domain-names" type="checkbox" {{if .SSPIStripDomainNames}}checked{{end}}> |
||||||
|
<p class="help">{{.i18n.Tr "admin.auths.sspi_strip_domain_names_helper"}}</p> |
||||||
|
</div> |
||||||
|
</div> |
||||||
|
<div class="required field"> |
||||||
|
<label for="sspi_separator_replacement">{{.i18n.Tr "admin.auths.sspi_separator_replacement"}}</label> |
||||||
|
<input id="sspi_separator_replacement" name="sspi_separator_replacement" value="{{.SSPISeparatorReplacement}}"> |
||||||
|
<p class="help">{{.i18n.Tr "admin.auths.sspi_separator_replacement_helper"}}</p> |
||||||
|
</div> |
||||||
|
<div class="field"> |
||||||
|
<label for="sspi_default_language">{{.i18n.Tr "admin.auths.sspi_default_language"}}</label> |
||||||
|
<div class="ui language selection dropdown" id="sspi_default_language"> |
||||||
|
<input name="sspi_default_language" type="hidden" value="{{.SSPIDefaultLanguage}}"> |
||||||
|
<i class="dropdown icon"></i> |
||||||
|
<div class="text">{{range .AllLangs}}{{if eq $.SSPIDefaultLanguage .Lang}}{{.Name}}{{end}}{{end}}</div> |
||||||
|
<div class="menu"> |
||||||
|
<div class="item{{if not $.SSPIDefaultLanguage}} active selected{{end}}" data-value="">-</div> |
||||||
|
{{range .AllLangs}} |
||||||
|
<div class="item{{if eq $.SSPIDefaultLanguage .Lang}} active selected{{end}}" data-value="{{.Lang}}">{{.Name}}</div> |
||||||
|
{{end}} |
||||||
|
</div> |
||||||
|
</div> |
||||||
|
<p class="help">{{.i18n.Tr "admin.auths.sspi_default_language_helper"}}</p> |
||||||
|
</div> |
||||||
|
</div> |
@ -1,11 +1,19 @@ |
|||||||
{{if .EnableOpenIDSignIn}} |
{{if or .EnableOpenIDSignIn .EnableSSPI}} |
||||||
<div class="ui secondary pointing tabular top attached borderless menu new-menu navbar"> |
<div class="ui secondary pointing tabular top attached borderless menu new-menu navbar"> |
||||||
<a class="{{if .PageIsLogin}}active{{end}} item" rel="nofollow" href="{{AppSubUrl}}/user/login"> |
<a class="{{if .PageIsLogin}}active{{end}} item" rel="nofollow" href="{{AppSubUrl}}/user/login"> |
||||||
{{.i18n.Tr "auth.login_userpass"}} |
{{.i18n.Tr "auth.login_userpass"}} |
||||||
</a> |
</a> |
||||||
|
{{if .EnableOpenIDSignIn}} |
||||||
<a class="{{if .PageIsLoginOpenID}}active{{end}} item" rel="nofollow" href="{{AppSubUrl}}/user/login/openid"> |
<a class="{{if .PageIsLoginOpenID}}active{{end}} item" rel="nofollow" href="{{AppSubUrl}}/user/login/openid"> |
||||||
<i class="fa fa-openid"></i> |
<i class="fa fa-openid"></i> |
||||||
OpenID |
OpenID |
||||||
</a> |
</a> |
||||||
|
{{end}} |
||||||
|
{{if .EnableSSPI}} |
||||||
|
<a class="item" rel="nofollow" href="{{AppSubUrl}}/user/login?auth_with_sspi=1"> |
||||||
|
<i class="fa fa-windows"></i> |
||||||
|
SSPI |
||||||
|
</a> |
||||||
|
{{end}} |
||||||
</div> |
</div> |
||||||
{{end}} |
{{end}} |
||||||
|
@ -0,0 +1,12 @@ |
|||||||
|
# Binaries for programs and plugins |
||||||
|
*.exe |
||||||
|
*.exe~ |
||||||
|
*.dll |
||||||
|
*.so |
||||||
|
*.dylib |
||||||
|
|
||||||
|
# Test binary, build with `go test -c` |
||||||
|
*.test |
||||||
|
|
||||||
|
# Output of the go coverage tool, specifically when used with LiteIDE |
||||||
|
*.out |
@ -0,0 +1,13 @@ |
|||||||
|
jobs: |
||||||
|
include: |
||||||
|
- os: windows |
||||||
|
script: $GOPATH/bin/goveralls -service=travis-ci |
||||||
|
language: go |
||||||
|
sudo: false |
||||||
|
go: 1.13.x |
||||||
|
before_install: go get github.com/mattn/goveralls |
||||||
|
- os: linux |
||||||
|
script: go build |
||||||
|
language: go |
||||||
|
sudo: false |
||||||
|
go: 1.13.x |
@ -0,0 +1,21 @@ |
|||||||
|
MIT License |
||||||
|
|
||||||
|
Copyright (c) 2019 QuaSoft |
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy |
||||||
|
of this software and associated documentation files (the "Software"), to deal |
||||||
|
in the Software without restriction, including without limitation the rights |
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
||||||
|
copies of the Software, and to permit persons to whom the Software is |
||||||
|
furnished to do so, subject to the following conditions: |
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all |
||||||
|
copies or substantial portions of the Software. |
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
||||||
|
SOFTWARE. |
@ -0,0 +1,41 @@ |
|||||||
|
# websspi |
||||||
|
|
||||||
|
[![GoDoc](https://godoc.org/github.com/quasoft/websspi?status.svg)](https://godoc.org/github.com/quasoft/websspi) [![Build Status](https://travis-ci.org/quasoft/websspi.png?branch=master)](https://travis-ci.org/quasoft/websspi) [![Coverage Status](https://coveralls.io/repos/github/quasoft/websspi/badge.svg?branch=master)](https://coveralls.io/github/quasoft/websspi?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/quasoft/websspi)](https://goreportcard.com/report/github.com/quasoft/websspi) |
||||||
|
|
||||||
|
`websspi` will be an HTTP middleware for Golang that uses Kerberos for single sign-on (SSO) authentication of browser based clients in a Windows environment. |
||||||
|
|
||||||
|
The main goal is to create a middleware that performs authentication of HTTP requests without the need to create or use keytab files. |
||||||
|
|
||||||
|
The middleware will implement the scheme defined by RFC4559 (SPNEGO-based HTTP Authentication in Microsoft Windows) to exchange security tokens via HTTP headers and will use SSPI (Security Support Provider Interface) to authenticate HTTP requests. |
||||||
|
|
||||||
|
## How to use |
||||||
|
|
||||||
|
The examples directory contains a simple web server that demonstrates how to use the package. |
||||||
|
Before trying it, you need to prepare your environment: |
||||||
|
|
||||||
|
1. Create a separate user account in active directory, under which the web server process will be running (eg. `user` under the `domain.local` domain) |
||||||
|
|
||||||
|
2. Create a service principal name for the host with class HTTP: |
||||||
|
- Start Command prompt or PowerShell as domain administrator |
||||||
|
- Run the command below, replacing `host.domain.local` with the fully qualified domain name of the server where the web application will be running, and `domain\user` with the name of the account created in step 1.: |
||||||
|
|
||||||
|
setspn -A HTTP/host.domain.local domain\user |
||||||
|
|
||||||
|
3. Start the web server app under the account created in step 1. |
||||||
|
|
||||||
|
4. If you are using Chrome, Edge or Internet Explorer, add the URL of the web app to the Local intranet sites (`Internet Options -> Security -> Local intranet -> Sites`) |
||||||
|
|
||||||
|
5. Start Chrome, Edge or Internet Explorer and navigate to the URL of the web app (eg. `http://host.domain.local:9000`) |
||||||
|
|
||||||
|
6. The web app should greet you with the name of your AD account without asking you to login. In case it doesn't, make sure that: |
||||||
|
|
||||||
|
- You are not running the web browser on the same server where the web app is running. You should be running the web browser on a domain joined computer (client) that is different from the server |
||||||
|
- There is only one HTTP/... SPN for the host |
||||||
|
- The SPN contains only the hostname, without the port |
||||||
|
- You have added the URL of the web app to the `Local intranet` zone |
||||||
|
- The clocks of the server and client should not differ with more than 5 minutes |
||||||
|
- `Integrated Windows Authentication` should be enabled in Internet Explorer (under `Advanced settings`) |
||||||
|
|
||||||
|
## Security requirements |
||||||
|
|
||||||
|
- SPNEGO HTTP provides no facilities for protecting the HTTP headers or data including the Authorization and WWW-Authenticate headers, which means that the HTTP server **MUST** enforce use of SSL to provide confidentiality to data in these headers! |
@ -0,0 +1,9 @@ |
|||||||
|
module github.com/quasoft/websspi |
||||||
|
|
||||||
|
go 1.13 |
||||||
|
|
||||||
|
require ( |
||||||
|
github.com/gorilla/securecookie v1.1.1 |
||||||
|
github.com/gorilla/sessions v1.2.0 |
||||||
|
golang.org/x/sys v0.0.0-20191010194322-b09406accb47 |
||||||
|
) |
@ -0,0 +1,6 @@ |
|||||||
|
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= |
||||||
|
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= |
||||||
|
github.com/gorilla/sessions v1.2.0 h1:S7P+1Hm5V/AT9cjEcUD5uDaQSX0OE577aCXgoaKpYbQ= |
||||||
|
github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= |
||||||
|
golang.org/x/sys v0.0.0-20191010194322-b09406accb47 h1:/XfQ9z7ib8eEJX2hdgFTZJ/ntt0swNk5oYBziWeTCvY= |
||||||
|
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= |
@ -0,0 +1,36 @@ |
|||||||
|
package secctx |
||||||
|
|
||||||
|
import ( |
||||||
|
"net/http" |
||||||
|
|
||||||
|
"github.com/gorilla/securecookie" |
||||||
|
"github.com/gorilla/sessions" |
||||||
|
) |
||||||
|
|
||||||
|
// CookieStore can store and retrieve SSPI context handles to/from an encrypted Cookie.
|
||||||
|
type CookieStore struct { |
||||||
|
store *sessions.CookieStore |
||||||
|
} |
||||||
|
|
||||||
|
// NewCookieStore creates a new CookieStore for storing and retrieving of SSPI context handles
|
||||||
|
// to/from encrypted Cookies
|
||||||
|
func NewCookieStore() *CookieStore { |
||||||
|
s := &CookieStore{} |
||||||
|
s.store = sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(32))) |
||||||
|
return s |
||||||
|
} |
||||||
|
|
||||||
|
// GetHandle retrieves a *websspi.CtxtHandle value from the store
|
||||||
|
func (s *CookieStore) GetHandle(r *http.Request) (interface{}, error) { |
||||||
|
session, _ := s.store.Get(r, "websspi") |
||||||
|
contextHandle := session.Values["contextHandle"] |
||||||
|
return contextHandle, nil |
||||||
|
} |
||||||
|
|
||||||
|
// SetHandle saves a *websspi.CtxtHandle value to the store
|
||||||
|
func (s *CookieStore) SetHandle(r *http.Request, w http.ResponseWriter, contextHandle interface{}) error { |
||||||
|
session, _ := s.store.Get(r, "websspi") |
||||||
|
session.Values["contextHandle"] = contextHandle |
||||||
|
err := session.Save(r, w) |
||||||
|
return err |
||||||
|
} |
@ -0,0 +1,13 @@ |
|||||||
|
package secctx |
||||||
|
|
||||||
|
import "net/http" |
||||||
|
|
||||||
|
// Store is an interface for storage of SSPI context handles.
|
||||||
|
// SSPI context handles are Windows API handles and have nothing to do
|
||||||
|
// with the "context" package in Go.
|
||||||
|
type Store interface { |
||||||
|
// GetHandle retrieves a *websspi.CtxtHandle value from the store
|
||||||
|
GetHandle(r *http.Request) (interface{}, error) |
||||||
|
// SetHandle saves a *websspi.CtxtHandle value to the store
|
||||||
|
SetHandle(r *http.Request, w http.ResponseWriter, contextHandle interface{}) error |
||||||
|
} |
@ -0,0 +1,7 @@ |
|||||||
|
package websspi |
||||||
|
|
||||||
|
// UserInfo represents an authenticated user.
|
||||||
|
type UserInfo struct { |
||||||
|
Username string // Name of user, usually in the form DOMAIN\User
|
||||||
|
Groups []string // The global groups the user is a member of
|
||||||
|
} |
@ -0,0 +1,22 @@ |
|||||||
|
package websspi |
||||||
|
|
||||||
|
import ( |
||||||
|
"unicode/utf16" |
||||||
|
"unsafe" |
||||||
|
) |
||||||
|
|
||||||
|
// UTF16PtrToString converts a pointer to a UTF16 string to a string
|
||||||
|
func UTF16PtrToString(ptr *uint16, maxLen int) (s string) { |
||||||
|
if ptr == nil { |
||||||
|
return "" |
||||||
|
} |
||||||
|
buf := make([]uint16, 0, maxLen) |
||||||
|
for i, p := 0, uintptr(unsafe.Pointer(ptr)); i < maxLen; i, p = i+1, p+2 { |
||||||
|
char := *(*uint16)(unsafe.Pointer(p)) |
||||||
|
if char == 0 { |
||||||
|
return string(utf16.Decode(buf)) |
||||||
|
} |
||||||
|
buf = append(buf, char) |
||||||
|
} |
||||||
|
return "" |
||||||
|
} |
@ -0,0 +1,615 @@ |
|||||||
|
package websspi |
||||||
|
|
||||||
|
import ( |
||||||
|
"context" |
||||||
|
"encoding/base64" |
||||||
|
"encoding/gob" |
||||||
|
"errors" |
||||||
|
"fmt" |
||||||
|
"log" |
||||||
|
"net/http" |
||||||
|
"strings" |
||||||
|
"sync" |
||||||
|
"syscall" |
||||||
|
"time" |
||||||
|
"unsafe" |
||||||
|
|
||||||
|
"github.com/quasoft/websspi/secctx" |
||||||
|
) |
||||||
|
|
||||||
|
// The Config object determines the behaviour of the Authenticator.
|
||||||
|
type Config struct { |
||||||
|
contextStore secctx.Store |
||||||
|
authAPI API |
||||||
|
KrbPrincipal string // Name of Kerberos principle used by the service (optional).
|
||||||
|
AuthUserKey string // Key of header to fill with authenticated username, eg. "X-Authenticated-User" or "REMOTE_USER" (optional).
|
||||||
|
EnumerateGroups bool // If true, groups the user is a member of are enumerated and stored in request context (default false)
|
||||||
|
ServerName string // Specifies the DNS or NetBIOS name of the remote server which to query about user groups. Ignored if EnumerateGroups is false.
|
||||||
|
} |
||||||
|
|
||||||
|
// NewConfig creates a configuration object with default values.
|
||||||
|
func NewConfig() *Config { |
||||||
|
return &Config{ |
||||||
|
contextStore: secctx.NewCookieStore(), |
||||||
|
authAPI: &Win32{}, |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// Validate makes basic validation of configuration to make sure that important and required fields
|
||||||
|
// have been set with values in expected format.
|
||||||
|
func (c *Config) Validate() error { |
||||||
|
if c.contextStore == nil { |
||||||
|
return errors.New("Store for context handles not specified in Config") |
||||||
|
} |
||||||
|
if c.authAPI == nil { |
||||||
|
return errors.New("Authentication API not specified in Config") |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// contextKey represents a custom key for values stored in context.Context
|
||||||
|
type contextKey string |
||||||
|
|
||||||
|
func (c contextKey) String() string { |
||||||
|
return "websspi-key-" + string(c) |
||||||
|
} |
||||||
|
|
||||||
|
var ( |
||||||
|
UserInfoKey = contextKey("UserInfo") |
||||||
|
) |
||||||
|
|
||||||
|
// The Authenticator type provides middleware methods for authentication of http requests.
|
||||||
|
// A single authenticator object can be shared by concurrent goroutines.
|
||||||
|
type Authenticator struct { |
||||||
|
Config Config |
||||||
|
serverCred *CredHandle |
||||||
|
credExpiry *time.Time |
||||||
|
ctxList []CtxtHandle |
||||||
|
ctxListMux *sync.Mutex |
||||||
|
} |
||||||
|
|
||||||
|
// New creates a new Authenticator object with the given configuration options.
|
||||||
|
func New(config *Config) (*Authenticator, error) { |
||||||
|
err := config.Validate() |
||||||
|
if err != nil { |
||||||
|
return nil, fmt.Errorf("invalid config: %v", err) |
||||||
|
} |
||||||
|
|
||||||
|
var auth = &Authenticator{ |
||||||
|
Config: *config, |
||||||
|
ctxListMux: &sync.Mutex{}, |
||||||
|
} |
||||||
|
|
||||||
|
err = auth.PrepareCredentials(config.KrbPrincipal) |
||||||
|
if err != nil { |
||||||
|
return nil, fmt.Errorf("could not acquire credentials handle for the service: %v", err) |
||||||
|
} |
||||||
|
log.Printf("Credential handle expiry: %v\n", *auth.credExpiry) |
||||||
|
|
||||||
|
return auth, nil |
||||||
|
} |
||||||
|
|
||||||
|
// PrepareCredentials method acquires a credentials handle for the specified principal
|
||||||
|
// for use during the live of the application.
|
||||||
|
// On success stores the handle in the serverCred field and its expiry time in the
|
||||||
|
// credExpiry field.
|
||||||
|
// This method must be called once - when the application is starting or when the first
|
||||||
|
// request from a client is received.
|
||||||
|
func (a *Authenticator) PrepareCredentials(principal string) error { |
||||||
|
var principalPtr *uint16 |
||||||
|
if principal != "" { |
||||||
|
var err error |
||||||
|
principalPtr, err = syscall.UTF16PtrFromString(principal) |
||||||
|
if err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
} |
||||||
|
credentialUsePtr, err := syscall.UTF16PtrFromString(NEGOSSP_NAME) |
||||||
|
if err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
var handle CredHandle |
||||||
|
var expiry syscall.Filetime |
||||||
|
status := a.Config.authAPI.AcquireCredentialsHandle( |
||||||
|
principalPtr, |
||||||
|
credentialUsePtr, |
||||||
|
SECPKG_CRED_INBOUND, |
||||||
|
nil, // logonId
|
||||||
|
nil, // authData
|
||||||
|
0, // getKeyFn
|
||||||
|
0, // getKeyArgument
|
||||||
|
&handle, |
||||||
|
&expiry, |
||||||
|
) |
||||||
|
if status != SEC_E_OK { |
||||||
|
return fmt.Errorf("call to AcquireCredentialsHandle failed with code 0x%x", status) |
||||||
|
} |
||||||
|
expiryTime := time.Unix(0, expiry.Nanoseconds()) |
||||||
|
a.credExpiry = &expiryTime |
||||||
|
a.serverCred = &handle |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// Free method should be called before shutting down the server to let
|
||||||
|
// it release allocated Win32 resources
|
||||||
|
func (a *Authenticator) Free() error { |
||||||
|
var status SECURITY_STATUS |
||||||
|
a.ctxListMux.Lock() |
||||||
|
for _, ctx := range a.ctxList { |
||||||
|
// TODO: Also check for stale security contexts and delete them periodically
|
||||||
|
status = a.Config.authAPI.DeleteSecurityContext(&ctx) |
||||||
|
if status != SEC_E_OK { |
||||||
|
return fmt.Errorf("call to DeleteSecurityContext failed with code 0x%x", status) |
||||||
|
} |
||||||
|
} |
||||||
|
a.ctxList = nil |
||||||
|
a.ctxListMux.Unlock() |
||||||
|
if a.serverCred != nil { |
||||||
|
status = a.Config.authAPI.FreeCredentialsHandle(a.serverCred) |
||||||
|
if status != SEC_E_OK { |
||||||
|
return fmt.Errorf("call to FreeCredentialsHandle failed with code 0x%x", status) |
||||||
|
} |
||||||
|
a.serverCred = nil |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// StoreCtxHandle stores the specified context to the internal list (ctxList)
|
||||||
|
func (a *Authenticator) StoreCtxHandle(handle *CtxtHandle) { |
||||||
|
if handle == nil || *handle == (CtxtHandle{}) { |
||||||
|
// Should not add nil or empty handle
|
||||||
|
return |
||||||
|
} |
||||||
|
a.ctxListMux.Lock() |
||||||
|
defer a.ctxListMux.Unlock() |
||||||
|
a.ctxList = append(a.ctxList, *handle) |
||||||
|
} |
||||||
|
|
||||||
|
// ReleaseCtxHandle deletes a context handle and removes it from the internal list (ctxList)
|
||||||
|
func (a *Authenticator) ReleaseCtxHandle(handle *CtxtHandle) error { |
||||||
|
if handle == nil || *handle == (CtxtHandle{}) { |
||||||
|
// Removing a nil or empty handle is not an error condition
|
||||||
|
return nil |
||||||
|
} |
||||||
|
a.ctxListMux.Lock() |
||||||
|
defer a.ctxListMux.Unlock() |
||||||
|
|
||||||
|
// First, try to delete the handle
|
||||||
|
status := a.Config.authAPI.DeleteSecurityContext(handle) |
||||||
|
if status != SEC_E_OK { |
||||||
|
return fmt.Errorf("call to DeleteSecurityContext failed with code 0x%x", status) |
||||||
|
} |
||||||
|
|
||||||
|
// Then remove it from the internal list
|
||||||
|
foundAt := -1 |
||||||
|
for i, ctx := range a.ctxList { |
||||||
|
if ctx == *handle { |
||||||
|
foundAt = i |
||||||
|
break |
||||||
|
} |
||||||
|
} |
||||||
|
if foundAt > -1 { |
||||||
|
a.ctxList[foundAt] = a.ctxList[len(a.ctxList)-1] |
||||||
|
a.ctxList = a.ctxList[:len(a.ctxList)-1] |
||||||
|
} |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// AcceptOrContinue tries to validate the auth-data token by calling the AcceptSecurityContext
|
||||||
|
// function and returns and error if validation failed or continuation of the negotiation is needed.
|
||||||
|
// No error is returned if the token was validated (user was authenticated).
|
||||||
|
func (a *Authenticator) AcceptOrContinue(context *CtxtHandle, authData []byte) (newCtx *CtxtHandle, out []byte, exp *time.Time, err error) { |
||||||
|
if authData == nil { |
||||||
|
err = errors.New("input token cannot be nil") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
var inputDesc SecBufferDesc |
||||||
|
var inputBuf SecBuffer |
||||||
|
inputDesc.BuffersCount = 1 |
||||||
|
inputDesc.Version = SECBUFFER_VERSION |
||||||
|
inputDesc.Buffers = &inputBuf |
||||||
|
inputBuf.BufferSize = uint32(len(authData)) |
||||||
|
inputBuf.BufferType = SECBUFFER_TOKEN |
||||||
|
inputBuf.Buffer = &authData[0] |
||||||
|
|
||||||
|
var outputDesc SecBufferDesc |
||||||
|
var outputBuf SecBuffer |
||||||
|
outputDesc.BuffersCount = 1 |
||||||
|
outputDesc.Version = SECBUFFER_VERSION |
||||||
|
outputDesc.Buffers = &outputBuf |
||||||
|
outputBuf.BufferSize = 0 |
||||||
|
outputBuf.BufferType = SECBUFFER_TOKEN |
||||||
|
outputBuf.Buffer = nil |
||||||
|
|
||||||
|
var expiry syscall.Filetime |
||||||
|
var contextAttr uint32 |
||||||
|
var newContextHandle CtxtHandle |
||||||
|
|
||||||
|
var status = a.Config.authAPI.AcceptSecurityContext( |
||||||
|
a.serverCred, |
||||||
|
context, |
||||||
|
&inputDesc, |
||||||
|
ASC_REQ_ALLOCATE_MEMORY|ASC_REQ_MUTUAL_AUTH|ASC_REQ_CONFIDENTIALITY| |
||||||
|
ASC_REQ_INTEGRITY|ASC_REQ_REPLAY_DETECT|ASC_REQ_SEQUENCE_DETECT, // contextReq uint32,
|
||||||
|
SECURITY_NATIVE_DREP, // targDataRep uint32,
|
||||||
|
&newContextHandle, |
||||||
|
&outputDesc, // *SecBufferDesc
|
||||||
|
&contextAttr, // contextAttr *uint32,
|
||||||
|
&expiry, // *syscall.Filetime
|
||||||
|
) |
||||||
|
if newContextHandle.Lower != 0 || newContextHandle.Upper != 0 { |
||||||
|
newCtx = &newContextHandle |
||||||
|
} |
||||||
|
tm := time.Unix(0, expiry.Nanoseconds()) |
||||||
|
exp = &tm |
||||||
|
if status == SEC_E_OK || status == SEC_I_CONTINUE_NEEDED { |
||||||
|
// Copy outputBuf.Buffer to out and free the outputBuf.Buffer
|
||||||
|
out = make([]byte, outputBuf.BufferSize) |
||||||
|
var bufPtr = uintptr(unsafe.Pointer(outputBuf.Buffer)) |
||||||
|
for i := 0; i < len(out); i++ { |
||||||
|
out[i] = *(*byte)(unsafe.Pointer(bufPtr)) |
||||||
|
bufPtr++ |
||||||
|
} |
||||||
|
} |
||||||
|
if outputBuf.Buffer != nil { |
||||||
|
freeStatus := a.Config.authAPI.FreeContextBuffer(outputBuf.Buffer) |
||||||
|
if freeStatus != SEC_E_OK { |
||||||
|
status = freeStatus |
||||||
|
err = fmt.Errorf("could not free output buffer; FreeContextBuffer() failed with code: 0x%x", freeStatus) |
||||||
|
return |
||||||
|
} |
||||||
|
} |
||||||
|
if status == SEC_I_CONTINUE_NEEDED { |
||||||
|
err = errors.New("Negotiation should continue") |
||||||
|
return |
||||||
|
} else if status != SEC_E_OK { |
||||||
|
err = fmt.Errorf("call to AcceptSecurityContext failed with code 0x%x", status) |
||||||
|
return |
||||||
|
} |
||||||
|
// TODO: Check contextAttr?
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// GetCtxHandle retrieves the context handle for this client from request's cookies
|
||||||
|
func (a *Authenticator) GetCtxHandle(r *http.Request) (*CtxtHandle, error) { |
||||||
|
sessionHandle, err := a.Config.contextStore.GetHandle(r) |
||||||
|
if err != nil { |
||||||
|
return nil, fmt.Errorf("could not get context handle from session: %s", err) |
||||||
|
} |
||||||
|
if contextHandle, ok := sessionHandle.(*CtxtHandle); ok { |
||||||
|
log.Printf("CtxHandle: 0x%x\n", *contextHandle) |
||||||
|
if contextHandle.Lower == 0 && contextHandle.Upper == 0 { |
||||||
|
return nil, nil |
||||||
|
} |
||||||
|
return contextHandle, nil |
||||||
|
} |
||||||
|
log.Printf("CtxHandle: nil\n") |
||||||
|
return nil, nil |
||||||
|
} |
||||||
|
|
||||||
|
// SetCtxHandle stores the context handle for this client to cookie of response
|
||||||
|
func (a *Authenticator) SetCtxHandle(r *http.Request, w http.ResponseWriter, newContext *CtxtHandle) error { |
||||||
|
// Store can't store nil value, so if newContext is nil, store an empty CtxHandle
|
||||||
|
ctx := &CtxtHandle{} |
||||||
|
if newContext != nil { |
||||||
|
ctx = newContext |
||||||
|
} |
||||||
|
err := a.Config.contextStore.SetHandle(r, w, ctx) |
||||||
|
if err != nil { |
||||||
|
return fmt.Errorf("could not save context to cookie: %s", err) |
||||||
|
} |
||||||
|
log.Printf("New context: 0x%x\n", *ctx) |
||||||
|
return nil |
||||||
|
} |
||||||
|
|
||||||
|
// GetFlags returns the negotiated context flags
|
||||||
|
func (a *Authenticator) GetFlags(context *CtxtHandle) (uint32, error) { |
||||||
|
var flags SecPkgContext_Flags |
||||||
|
status := a.Config.authAPI.QueryContextAttributes(context, SECPKG_ATTR_FLAGS, (*byte)(unsafe.Pointer(&flags))) |
||||||
|
if status != SEC_E_OK { |
||||||
|
return 0, fmt.Errorf("QueryContextAttributes failed with status 0x%x", status) |
||||||
|
} |
||||||
|
return flags.Flags, nil |
||||||
|
} |
||||||
|
|
||||||
|
// GetUsername returns the name of the user associated with the specified security context
|
||||||
|
func (a *Authenticator) GetUsername(context *CtxtHandle) (username string, err error) { |
||||||
|
var names SecPkgContext_Names |
||||||
|
status := a.Config.authAPI.QueryContextAttributes(context, SECPKG_ATTR_NAMES, (*byte)(unsafe.Pointer(&names))) |
||||||
|
if status != SEC_E_OK { |
||||||
|
err = fmt.Errorf("QueryContextAttributes failed with status 0x%x", status) |
||||||
|
return |
||||||
|
} |
||||||
|
if names.UserName != nil { |
||||||
|
username = UTF16PtrToString(names.UserName, 2048) |
||||||
|
status = a.Config.authAPI.FreeContextBuffer((*byte)(unsafe.Pointer(names.UserName))) |
||||||
|
if status != SEC_E_OK { |
||||||
|
err = fmt.Errorf("FreeContextBuffer failed with status 0x%x", status) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
err = errors.New("QueryContextAttributes returned empty name") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// GetUserGroups returns the groups the user is a member of
|
||||||
|
func (a *Authenticator) GetUserGroups(userName string) (groups []string, err error) { |
||||||
|
var serverNamePtr *uint16 |
||||||
|
if a.Config.ServerName != "" { |
||||||
|
serverNamePtr, err = syscall.UTF16PtrFromString(a.Config.ServerName) |
||||||
|
if err != nil { |
||||||
|
return |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
userNamePtr, err := syscall.UTF16PtrFromString(userName) |
||||||
|
if err != nil { |
||||||
|
return |
||||||
|
} |
||||||
|
var buf *byte |
||||||
|
var entriesRead uint32 |
||||||
|
var totalEntries uint32 |
||||||
|
err = a.Config.authAPI.NetUserGetGroups( |
||||||
|
serverNamePtr, |
||||||
|
userNamePtr, |
||||||
|
0, |
||||||
|
&buf, |
||||||
|
MAX_PREFERRED_LENGTH, |
||||||
|
&entriesRead, |
||||||
|
&totalEntries, |
||||||
|
) |
||||||
|
if buf == nil { |
||||||
|
err = fmt.Errorf("NetUserGetGroups(): returned nil buffer, error: %s", err) |
||||||
|
return |
||||||
|
} |
||||||
|
defer func() { |
||||||
|
freeErr := a.Config.authAPI.NetApiBufferFree(buf) |
||||||
|
if freeErr != nil { |
||||||
|
err = freeErr |
||||||
|
} |
||||||
|
}() |
||||||
|
if err != nil { |
||||||
|
return |
||||||
|
} |
||||||
|
if entriesRead < totalEntries { |
||||||
|
err = fmt.Errorf("NetUserGetGroups(): could not read all entries, read only %d entries of %d", entriesRead, totalEntries) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
ptr := uintptr(unsafe.Pointer(buf)) |
||||||
|
for i := uint32(0); i < entriesRead; i++ { |
||||||
|
groupInfo := (*GroupUsersInfo0)(unsafe.Pointer(ptr)) |
||||||
|
groupName := UTF16PtrToString(groupInfo.Grui0_name, MAX_GROUP_NAME_LENGTH) |
||||||
|
if groupName != "" { |
||||||
|
groups = append(groups, groupName) |
||||||
|
} |
||||||
|
ptr += unsafe.Sizeof(GroupUsersInfo0{}) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// GetUserInfo returns a structure containing the name of the user associated with the
|
||||||
|
// specified security context and the groups to which they are a member of (if Config.EnumerateGroups)
|
||||||
|
// is enabled
|
||||||
|
func (a *Authenticator) GetUserInfo(context *CtxtHandle) (*UserInfo, error) { |
||||||
|
// Get username
|
||||||
|
username, err := a.GetUsername(context) |
||||||
|
if err != nil { |
||||||
|
return nil, err |
||||||
|
} |
||||||
|
info := UserInfo{ |
||||||
|
Username: username, |
||||||
|
} |
||||||
|
|
||||||
|
// Get groups
|
||||||
|
if a.Config.EnumerateGroups { |
||||||
|
info.Groups, err = a.GetUserGroups(username) |
||||||
|
if err != nil { |
||||||
|
return nil, err |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
return &info, nil |
||||||
|
} |
||||||
|
|
||||||
|
// GetAuthData parses the "Authorization" header received from the client,
|
||||||
|
// extracts the auth-data token (input token) and decodes it to []byte
|
||||||
|
func (a *Authenticator) GetAuthData(r *http.Request, w http.ResponseWriter) (authData []byte, err error) { |
||||||
|
// 1. Check if Authorization header is present
|
||||||
|
headers := r.Header["Authorization"] |
||||||
|
if len(headers) == 0 { |
||||||
|
err = errors.New("the Authorization header is not provided") |
||||||
|
return |
||||||
|
} |
||||||
|
if len(headers) > 1 { |
||||||
|
err = errors.New("received multiple Authorization headers, but expected only one") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
authzHeader := strings.TrimSpace(headers[0]) |
||||||
|
if authzHeader == "" { |
||||||
|
err = errors.New("the Authorization header is empty") |
||||||
|
return |
||||||
|
} |
||||||
|
// 1.1. Make sure header starts with "Negotiate"
|
||||||
|
if !strings.HasPrefix(strings.ToLower(authzHeader), "negotiate") { |
||||||
|
err = errors.New("the Authorization header does not start with 'Negotiate'") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// 2. Extract token from Authorization header
|
||||||
|
authzParts := strings.Split(authzHeader, " ") |
||||||
|
if len(authzParts) < 2 { |
||||||
|
err = errors.New("the Authorization header does not contain token (gssapi-data)") |
||||||
|
return |
||||||
|
} |
||||||
|
token := authzParts[len(authzParts)-1] |
||||||
|
if token == "" { |
||||||
|
err = errors.New("the token (gssapi-data) in the Authorization header is empty") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// 3. Decode token
|
||||||
|
authData, err = base64.StdEncoding.DecodeString(token) |
||||||
|
if err != nil { |
||||||
|
err = errors.New("could not decode token as base64 string") |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// Authenticate tries to authenticate the HTTP request and returns nil
|
||||||
|
// if authentication was successful.
|
||||||
|
// Returns error and data for continuation if authentication was not successful.
|
||||||
|
func (a *Authenticator) Authenticate(r *http.Request, w http.ResponseWriter) (userInfo *UserInfo, outToken string, err error) { |
||||||
|
// 1. Extract auth-data from Authorization header
|
||||||
|
authData, err := a.GetAuthData(r, w) |
||||||
|
if err != nil { |
||||||
|
err = fmt.Errorf("could not get auth data: %s", err) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// 2. Authenticate user with provided token
|
||||||
|
contextHandle, err := a.GetCtxHandle(r) |
||||||
|
if err != nil { |
||||||
|
return |
||||||
|
} |
||||||
|
newCtx, output, _, err := a.AcceptOrContinue(contextHandle, authData) |
||||||
|
|
||||||
|
// If a new context was created, make sure to delete it or store it
|
||||||
|
// both in internal list and response Cookie
|
||||||
|
defer func() { |
||||||
|
// Negotiation is ending if we don't expect further responses from the client
|
||||||
|
// (authentication was successful or no output token is going to be sent back),
|
||||||
|
// clear client cookie
|
||||||
|
endOfNegotiation := err == nil || len(output) == 0 |
||||||
|
|
||||||
|
// Current context (contextHandle) is not needed anymore and should be deleted if:
|
||||||
|
// - we don't expect further responses from the client
|
||||||
|
// - a new context has been returned by AcceptSecurityContext
|
||||||
|
currCtxNotNeeded := endOfNegotiation || newCtx != nil |
||||||
|
if !currCtxNotNeeded { |
||||||
|
// Release current context only if its different than the new context
|
||||||
|
if contextHandle != nil && *contextHandle != *newCtx { |
||||||
|
remErr := a.ReleaseCtxHandle(contextHandle) |
||||||
|
if remErr != nil { |
||||||
|
err = remErr |
||||||
|
return |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
if endOfNegotiation { |
||||||
|
// Clear client cookie
|
||||||
|
setErr := a.SetCtxHandle(r, w, nil) |
||||||
|
if setErr != nil { |
||||||
|
err = fmt.Errorf("could not clear context, error: %s", setErr) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// Delete any new context handle
|
||||||
|
remErr := a.ReleaseCtxHandle(newCtx) |
||||||
|
if remErr != nil { |
||||||
|
err = remErr |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// Exit defer func
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
if newCtx != nil { |
||||||
|
// Store new context handle to internal list and response Cookie
|
||||||
|
a.StoreCtxHandle(newCtx) |
||||||
|
setErr := a.SetCtxHandle(r, w, newCtx) |
||||||
|
if setErr != nil { |
||||||
|
err = setErr |
||||||
|
return |
||||||
|
} |
||||||
|
} |
||||||
|
}() |
||||||
|
|
||||||
|
outToken = base64.StdEncoding.EncodeToString(output) |
||||||
|
if err != nil { |
||||||
|
err = fmt.Errorf("AcceptOrContinue failed: %s", err) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// 3. Get username and user groups
|
||||||
|
currentCtx := newCtx |
||||||
|
if currentCtx == nil { |
||||||
|
currentCtx = contextHandle |
||||||
|
} |
||||||
|
userInfo, err = a.GetUserInfo(currentCtx) |
||||||
|
if err != nil { |
||||||
|
err = fmt.Errorf("could not get username, error: %s", err) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
// AppendAuthenticateHeader populates WWW-Authenticate header,
|
||||||
|
// indicating to client that authentication is required and returns a 401 (Unauthorized)
|
||||||
|
// response code.
|
||||||
|
// The data parameter can be empty for the first 401 response from the server.
|
||||||
|
// For subsequent 401 responses the data parameter should contain the gssapi-data,
|
||||||
|
// which is required for continuation of the negotiation.
|
||||||
|
func (a *Authenticator) AppendAuthenticateHeader(w http.ResponseWriter, data string) { |
||||||
|
value := "Negotiate" |
||||||
|
if data != "" { |
||||||
|
value += " " + data |
||||||
|
} |
||||||
|
w.Header().Set("WWW-Authenticate", value) |
||||||
|
} |
||||||
|
|
||||||
|
// Return401 populates WWW-Authenticate header, indicating to client that authentication
|
||||||
|
// is required and returns a 401 (Unauthorized) response code.
|
||||||
|
// The data parameter can be empty for the first 401 response from the server.
|
||||||
|
// For subsequent 401 responses the data parameter should contain the gssapi-data,
|
||||||
|
// which is required for continuation of the negotiation.
|
||||||
|
func (a *Authenticator) Return401(w http.ResponseWriter, data string) { |
||||||
|
a.AppendAuthenticateHeader(w, data) |
||||||
|
http.Error(w, "Error!", http.StatusUnauthorized) |
||||||
|
} |
||||||
|
|
||||||
|
// WithAuth authenticates the request. On successful authentication the request
|
||||||
|
// is passed down to the next http handler. The next handler can access information
|
||||||
|
// about the authenticated user via the GetUserName method.
|
||||||
|
// If authentication was not successful, the server returns 401 response code with
|
||||||
|
// a WWW-Authenticate, indicating that authentication is required.
|
||||||
|
func (a *Authenticator) WithAuth(next http.Handler) http.Handler { |
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||||
|
log.Printf("Authenticating request to %s\n", r.RequestURI) |
||||||
|
|
||||||
|
user, data, err := a.Authenticate(r, w) |
||||||
|
if err != nil { |
||||||
|
log.Printf("Authentication failed with error: %v\n", err) |
||||||
|
a.Return401(w, data) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
log.Print("Authenticated\n") |
||||||
|
// Add the UserInfo value to the reqest's context
|
||||||
|
r = r.WithContext(context.WithValue(r.Context(), UserInfoKey, user)) |
||||||
|
// and to the request header with key Config.AuthUserKey
|
||||||
|
if a.Config.AuthUserKey != "" { |
||||||
|
r.Header.Set(a.Config.AuthUserKey, user.Username) |
||||||
|
} |
||||||
|
|
||||||
|
// The WWW-Authenticate header might need to be sent back even
|
||||||
|
// on successful authentication (eg. in order to let the client complete
|
||||||
|
// mutual authentication).
|
||||||
|
if data != "" { |
||||||
|
a.AppendAuthenticateHeader(w, data) |
||||||
|
} |
||||||
|
next.ServeHTTP(w, r) |
||||||
|
}) |
||||||
|
} |
||||||
|
|
||||||
|
func init() { |
||||||
|
gob.Register(&CtxtHandle{}) |
||||||
|
gob.Register(&UserInfo{}) |
||||||
|
} |
@ -0,0 +1,312 @@ |
|||||||
|
package websspi |
||||||
|
|
||||||
|
import ( |
||||||
|
"syscall" |
||||||
|
"unsafe" |
||||||
|
|
||||||
|
"golang.org/x/sys/windows" |
||||||
|
) |
||||||
|
|
||||||
|
// secur32.dll
|
||||||
|
|
||||||
|
type SECURITY_STATUS syscall.Errno |
||||||
|
|
||||||
|
const ( |
||||||
|
SEC_E_OK = SECURITY_STATUS(0) |
||||||
|
|
||||||
|
SEC_E_INCOMPLETE_MESSAGE = SECURITY_STATUS(0x80090318) |
||||||
|
SEC_E_INSUFFICIENT_MEMORY = SECURITY_STATUS(0x80090300) |
||||||
|
SEC_E_INTERNAL_ERROR = SECURITY_STATUS(0x80090304) |
||||||
|
SEC_E_INVALID_HANDLE = SECURITY_STATUS(0x80090301) |
||||||
|
SEC_E_INVALID_TOKEN = SECURITY_STATUS(0x80090308) |
||||||
|
SEC_E_LOGON_DENIED = SECURITY_STATUS(0x8009030C) |
||||||
|
SEC_E_NO_AUTHENTICATING_AUTHORITY = SECURITY_STATUS(0x80090311) |
||||||
|
SEC_E_NO_CREDENTIALS = SECURITY_STATUS(0x8009030E) |
||||||
|
SEC_E_UNSUPPORTED_FUNCTION = SECURITY_STATUS(0x80090302) |
||||||
|
SEC_I_COMPLETE_AND_CONTINUE = SECURITY_STATUS(0x00090314) |
||||||
|
SEC_I_COMPLETE_NEEDED = SECURITY_STATUS(0x00090313) |
||||||
|
SEC_I_CONTINUE_NEEDED = SECURITY_STATUS(0x00090312) |
||||||
|
SEC_E_NOT_OWNER = SECURITY_STATUS(0x80090306) |
||||||
|
SEC_E_SECPKG_NOT_FOUND = SECURITY_STATUS(0x80090305) |
||||||
|
SEC_E_UNKNOWN_CREDENTIALS = SECURITY_STATUS(0x8009030D) |
||||||
|
|
||||||
|
NEGOSSP_NAME = "Negotiate" |
||||||
|
SECPKG_CRED_INBOUND = 1 |
||||||
|
SECURITY_NATIVE_DREP = 16 |
||||||
|
|
||||||
|
ASC_REQ_DELEGATE = 1 |
||||||
|
ASC_REQ_MUTUAL_AUTH = 2 |
||||||
|
ASC_REQ_REPLAY_DETECT = 4 |
||||||
|
ASC_REQ_SEQUENCE_DETECT = 8 |
||||||
|
ASC_REQ_CONFIDENTIALITY = 16 |
||||||
|
ASC_REQ_USE_SESSION_KEY = 32 |
||||||
|
ASC_REQ_ALLOCATE_MEMORY = 256 |
||||||
|
ASC_REQ_USE_DCE_STYLE = 512 |
||||||
|
ASC_REQ_DATAGRAM = 1024 |
||||||
|
ASC_REQ_CONNECTION = 2048 |
||||||
|
ASC_REQ_EXTENDED_ERROR = 32768 |
||||||
|
ASC_REQ_STREAM = 65536 |
||||||
|
ASC_REQ_INTEGRITY = 131072 |
||||||
|
|
||||||
|
SECPKG_ATTR_SIZES = 0 |
||||||
|
SECPKG_ATTR_NAMES = 1 |
||||||
|
SECPKG_ATTR_LIFESPAN = 2 |
||||||
|
SECPKG_ATTR_DCE_INFO = 3 |
||||||
|
SECPKG_ATTR_STREAM_SIZES = 4 |
||||||
|
SECPKG_ATTR_KEY_INFO = 5 |
||||||
|
SECPKG_ATTR_AUTHORITY = 6 |
||||||
|
SECPKG_ATTR_PROTO_INFO = 7 |
||||||
|
SECPKG_ATTR_PASSWORD_EXPIRY = 8 |
||||||
|
SECPKG_ATTR_SESSION_KEY = 9 |
||||||
|
SECPKG_ATTR_PACKAGE_INFO = 10 |
||||||
|
SECPKG_ATTR_USER_FLAGS = 11 |
||||||
|
SECPKG_ATTR_NEGOTIATION_INFO = 12 |
||||||
|
SECPKG_ATTR_NATIVE_NAMES = 13 |
||||||
|
SECPKG_ATTR_FLAGS = 14 |
||||||
|
|
||||||
|
SECBUFFER_VERSION = 0 |
||||||
|
SECBUFFER_TOKEN = 2 |
||||||
|
) |
||||||
|
|
||||||
|
type CredHandle struct { |
||||||
|
Lower uintptr |
||||||
|
Upper uintptr |
||||||
|
} |
||||||
|
|
||||||
|
type CtxtHandle struct { |
||||||
|
Lower uintptr |
||||||
|
Upper uintptr |
||||||
|
} |
||||||
|
|
||||||
|
type SecBuffer struct { |
||||||
|
BufferSize uint32 |
||||||
|
BufferType uint32 |
||||||
|
Buffer *byte |
||||||
|
} |
||||||
|
|
||||||
|
type SecBufferDesc struct { |
||||||
|
Version uint32 |
||||||
|
BuffersCount uint32 |
||||||
|
Buffers *SecBuffer |
||||||
|
} |
||||||
|
|
||||||
|
type LUID struct { |
||||||
|
LowPart uint32 |
||||||
|
HighPart int32 |
||||||
|
} |
||||||
|
|
||||||
|
type SecPkgContext_Names struct { |
||||||
|
UserName *uint16 |
||||||
|
} |
||||||
|
|
||||||
|
type SecPkgContext_Flags struct { |
||||||
|
Flags uint32 |
||||||
|
} |
||||||
|
|
||||||
|
// netapi32.dll
|
||||||
|
|
||||||
|
const ( |
||||||
|
NERR_Success = 0x0 |
||||||
|
NERR_InternalError = 0x85C |
||||||
|
NERR_UserNotFound = 0x8AD |
||||||
|
|
||||||
|
ERROR_ACCESS_DENIED = 0x5 |
||||||
|
ERROR_BAD_NETPATH = 0x35 |
||||||
|
ERROR_INVALID_LEVEL = 0x7C |
||||||
|
ERROR_INVALID_NAME = 0x7B |
||||||
|
ERROR_MORE_DATA = 0xEA |
||||||
|
ERROR_NOT_ENOUGH_MEMORY = 0x8 |
||||||
|
|
||||||
|
MAX_PREFERRED_LENGTH = 0xFFFFFFFF |
||||||
|
MAX_GROUP_NAME_LENGTH = 256 |
||||||
|
|
||||||
|
SE_GROUP_MANDATORY = 0x1 |
||||||
|
SE_GROUP_ENABLED_BY_DEFAULT = 0x2 |
||||||
|
SE_GROUP_ENABLED = 0x4 |
||||||
|
SE_GROUP_OWNER = 0x8 |
||||||
|
SE_GROUP_USE_FOR_DENY_ONLY = 0x10 |
||||||
|
SE_GROUP_INTEGRITY = 0x20 |
||||||
|
SE_GROUP_INTEGRITY_ENABLED = 0x40 |
||||||
|
SE_GROUP_LOGON_ID = 0xC0000000 |
||||||
|
SE_GROUP_RESOURCE = 0x20000000 |
||||||
|
) |
||||||
|
|
||||||
|
type GroupUsersInfo0 struct { |
||||||
|
Grui0_name *uint16 |
||||||
|
} |
||||||
|
|
||||||
|
type GroupUsersInfo1 struct { |
||||||
|
Grui1_name *uint16 |
||||||
|
Grui1_attributes uint32 |
||||||
|
} |
||||||
|
|
||||||
|
// The API interface describes the Win32 functions used in this package and
|
||||||
|
// its primary purpose is to allow replacing them with stub functions in unit tests.
|
||||||
|
type API interface { |
||||||
|
AcquireCredentialsHandle( |
||||||
|
principal *uint16, |
||||||
|
_package *uint16, |
||||||
|
credentialUse uint32, |
||||||
|
logonID *LUID, |
||||||
|
authData *byte, |
||||||
|
getKeyFn uintptr, |
||||||
|
getKeyArgument uintptr, |
||||||
|
credHandle *CredHandle, |
||||||
|
expiry *syscall.Filetime, |
||||||
|
) SECURITY_STATUS |
||||||
|
AcceptSecurityContext( |
||||||
|
credential *CredHandle, |
||||||
|
context *CtxtHandle, |
||||||
|
input *SecBufferDesc, |
||||||
|
contextReq uint32, |
||||||
|
targDataRep uint32, |
||||||
|
newContext *CtxtHandle, |
||||||
|
output *SecBufferDesc, |
||||||
|
contextAttr *uint32, |
||||||
|
expiry *syscall.Filetime, |
||||||
|
) SECURITY_STATUS |
||||||
|
QueryContextAttributes(context *CtxtHandle, attribute uint32, buffer *byte) SECURITY_STATUS |
||||||
|
DeleteSecurityContext(context *CtxtHandle) SECURITY_STATUS |
||||||
|
FreeContextBuffer(buffer *byte) SECURITY_STATUS |
||||||
|
FreeCredentialsHandle(handle *CredHandle) SECURITY_STATUS |
||||||
|
NetUserGetGroups( |
||||||
|
serverName *uint16, |
||||||
|
userName *uint16, |
||||||
|
level uint32, |
||||||
|
buf **byte, |
||||||
|
prefmaxlen uint32, |
||||||
|
entriesread *uint32, |
||||||
|
totalentries *uint32, |
||||||
|
) (neterr error) |
||||||
|
NetApiBufferFree(buf *byte) (neterr error) |
||||||
|
} |
||||||
|
|
||||||
|
// Win32 implements the API interface by calling the relevant system functions
|
||||||
|
// from secur32.dll and netapi32.dll
|
||||||
|
type Win32 struct{} |
||||||
|
|
||||||
|
var ( |
||||||
|
secur32dll = windows.NewLazySystemDLL("secur32.dll") |
||||||
|
netapi32dll = windows.NewLazySystemDLL("netapi32.dll") |
||||||
|
|
||||||
|
procAcquireCredentialsHandleW = secur32dll.NewProc("AcquireCredentialsHandleW") |
||||||
|
procAcceptSecurityContext = secur32dll.NewProc("AcceptSecurityContext") |
||||||
|
procQueryContextAttributesW = secur32dll.NewProc("QueryContextAttributesW") |
||||||
|
procDeleteSecurityContext = secur32dll.NewProc("DeleteSecurityContext") |
||||||
|
procFreeContextBuffer = secur32dll.NewProc("FreeContextBuffer") |
||||||
|
procFreeCredentialsHandle = secur32dll.NewProc("FreeCredentialsHandle") |
||||||
|
procNetUserGetGroups = netapi32dll.NewProc("NetUserGetGroups") |
||||||
|
) |
||||||
|
|
||||||
|
func (w *Win32) AcquireCredentialsHandle( |
||||||
|
principal *uint16, |
||||||
|
_package *uint16, |
||||||
|
credentialUse uint32, |
||||||
|
logonId *LUID, |
||||||
|
authData *byte, |
||||||
|
getKeyFn uintptr, |
||||||
|
getKeyArgument uintptr, |
||||||
|
credHandle *CredHandle, |
||||||
|
expiry *syscall.Filetime, |
||||||
|
) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall9( |
||||||
|
procAcquireCredentialsHandleW.Addr(), 9, |
||||||
|
uintptr(unsafe.Pointer(principal)), |
||||||
|
uintptr(unsafe.Pointer(_package)), |
||||||
|
uintptr(credentialUse), |
||||||
|
uintptr(unsafe.Pointer(logonId)), |
||||||
|
uintptr(unsafe.Pointer(authData)), |
||||||
|
uintptr(getKeyFn), |
||||||
|
uintptr(getKeyArgument), |
||||||
|
uintptr(unsafe.Pointer(credHandle)), |
||||||
|
uintptr(unsafe.Pointer(expiry)), |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) AcceptSecurityContext( |
||||||
|
credential *CredHandle, |
||||||
|
context *CtxtHandle, |
||||||
|
input *SecBufferDesc, |
||||||
|
contextReq uint32, |
||||||
|
targDataRep uint32, |
||||||
|
newContext *CtxtHandle, |
||||||
|
output *SecBufferDesc, |
||||||
|
contextAttr *uint32, |
||||||
|
expiry *syscall.Filetime, |
||||||
|
) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall9( |
||||||
|
procAcceptSecurityContext.Addr(), 9, |
||||||
|
uintptr(unsafe.Pointer(credential)), |
||||||
|
uintptr(unsafe.Pointer(context)), |
||||||
|
uintptr(unsafe.Pointer(input)), |
||||||
|
uintptr(contextReq), |
||||||
|
uintptr(targDataRep), |
||||||
|
uintptr(unsafe.Pointer(newContext)), |
||||||
|
uintptr(unsafe.Pointer(output)), |
||||||
|
uintptr(unsafe.Pointer(contextAttr)), |
||||||
|
uintptr(unsafe.Pointer(expiry)), |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) QueryContextAttributes( |
||||||
|
context *CtxtHandle, |
||||||
|
attribute uint32, |
||||||
|
buffer *byte, |
||||||
|
) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall( |
||||||
|
procQueryContextAttributesW.Addr(), 3, |
||||||
|
uintptr(unsafe.Pointer(context)), |
||||||
|
uintptr(attribute), |
||||||
|
uintptr(unsafe.Pointer(buffer)), |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) DeleteSecurityContext(context *CtxtHandle) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall( |
||||||
|
procDeleteSecurityContext.Addr(), 1, |
||||||
|
uintptr(unsafe.Pointer(context)), |
||||||
|
0, 0, |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) FreeContextBuffer(buffer *byte) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall( |
||||||
|
procFreeContextBuffer.Addr(), 1, |
||||||
|
uintptr(unsafe.Pointer(buffer)), |
||||||
|
0, 0, |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) FreeCredentialsHandle(handle *CredHandle) SECURITY_STATUS { |
||||||
|
r1, _, _ := syscall.Syscall( |
||||||
|
procFreeCredentialsHandle.Addr(), 1, |
||||||
|
uintptr(unsafe.Pointer(handle)), |
||||||
|
0, 0, |
||||||
|
) |
||||||
|
return SECURITY_STATUS(r1) |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) NetUserGetGroups( |
||||||
|
serverName *uint16, |
||||||
|
userName *uint16, |
||||||
|
level uint32, |
||||||
|
buf **byte, |
||||||
|
prefmaxlen uint32, |
||||||
|
entriesread *uint32, |
||||||
|
totalentries *uint32, |
||||||
|
) (neterr error) { |
||||||
|
r0, _, _ := syscall.Syscall9(procNetUserGetGroups.Addr(), 7, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), uintptr(prefmaxlen), uintptr(unsafe.Pointer(entriesread)), uintptr(unsafe.Pointer(totalentries)), 0, 0) |
||||||
|
if r0 != 0 { |
||||||
|
neterr = syscall.Errno(r0) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func (w *Win32) NetApiBufferFree(buf *byte) (neterr error) { |
||||||
|
return syscall.NetApiBufferFree(buf) |
||||||
|
} |
@ -0,0 +1,39 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package cpu |
||||||
|
|
||||||
|
func doinit() { |
||||||
|
ARM.HasSWP = isSet(hwCap, hwcap_SWP) |
||||||
|
ARM.HasHALF = isSet(hwCap, hwcap_HALF) |
||||||
|
ARM.HasTHUMB = isSet(hwCap, hwcap_THUMB) |
||||||
|
ARM.Has26BIT = isSet(hwCap, hwcap_26BIT) |
||||||
|
ARM.HasFASTMUL = isSet(hwCap, hwcap_FAST_MULT) |
||||||
|
ARM.HasFPA = isSet(hwCap, hwcap_FPA) |
||||||
|
ARM.HasVFP = isSet(hwCap, hwcap_VFP) |
||||||
|
ARM.HasEDSP = isSet(hwCap, hwcap_EDSP) |
||||||
|
ARM.HasJAVA = isSet(hwCap, hwcap_JAVA) |
||||||
|
ARM.HasIWMMXT = isSet(hwCap, hwcap_IWMMXT) |
||||||
|
ARM.HasCRUNCH = isSet(hwCap, hwcap_CRUNCH) |
||||||
|
ARM.HasTHUMBEE = isSet(hwCap, hwcap_THUMBEE) |
||||||
|
ARM.HasNEON = isSet(hwCap, hwcap_NEON) |
||||||
|
ARM.HasVFPv3 = isSet(hwCap, hwcap_VFPv3) |
||||||
|
ARM.HasVFPv3D16 = isSet(hwCap, hwcap_VFPv3D16) |
||||||
|
ARM.HasTLS = isSet(hwCap, hwcap_TLS) |
||||||
|
ARM.HasVFPv4 = isSet(hwCap, hwcap_VFPv4) |
||||||
|
ARM.HasIDIVA = isSet(hwCap, hwcap_IDIVA) |
||||||
|
ARM.HasIDIVT = isSet(hwCap, hwcap_IDIVT) |
||||||
|
ARM.HasVFPD32 = isSet(hwCap, hwcap_VFPD32) |
||||||
|
ARM.HasLPAE = isSet(hwCap, hwcap_LPAE) |
||||||
|
ARM.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) |
||||||
|
ARM.HasAES = isSet(hwCap2, hwcap2_AES) |
||||||
|
ARM.HasPMULL = isSet(hwCap2, hwcap2_PMULL) |
||||||
|
ARM.HasSHA1 = isSet(hwCap2, hwcap2_SHA1) |
||||||
|
ARM.HasSHA2 = isSet(hwCap2, hwcap2_SHA2) |
||||||
|
ARM.HasCRC32 = isSet(hwCap2, hwcap2_CRC32) |
||||||
|
} |
||||||
|
|
||||||
|
func isSet(hwc uint, value uint) bool { |
||||||
|
return hwc&value != 0 |
||||||
|
} |
@ -0,0 +1,29 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,go1.12,!go1.13
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
import ( |
||||||
|
"unsafe" |
||||||
|
) |
||||||
|
|
||||||
|
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { |
||||||
|
// To implement this using libSystem we'd need syscall_syscallPtr for
|
||||||
|
// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
|
||||||
|
// back to raw syscalls for this func on Go 1.12.
|
||||||
|
var p unsafe.Pointer |
||||||
|
if len(buf) > 0 { |
||||||
|
p = unsafe.Pointer(&buf[0]) |
||||||
|
} else { |
||||||
|
p = unsafe.Pointer(&_zero) |
||||||
|
} |
||||||
|
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) |
||||||
|
n = int(r0) |
||||||
|
if e1 != 0 { |
||||||
|
return n, errnoErr(e1) |
||||||
|
} |
||||||
|
return n, nil |
||||||
|
} |
@ -0,0 +1,103 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,go1.13
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
import "unsafe" |
||||||
|
|
||||||
|
//sys closedir(dir uintptr) (err error)
|
||||||
|
//sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
|
||||||
|
|
||||||
|
func fdopendir(fd int) (dir uintptr, err error) { |
||||||
|
r0, _, e1 := syscall_syscallPtr(funcPC(libc_fdopendir_trampoline), uintptr(fd), 0, 0) |
||||||
|
dir = uintptr(r0) |
||||||
|
if e1 != 0 { |
||||||
|
err = errnoErr(e1) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func libc_fdopendir_trampoline() |
||||||
|
|
||||||
|
//go:linkname libc_fdopendir libc_fdopendir
|
||||||
|
//go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
|
||||||
|
|
||||||
|
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { |
||||||
|
// Simulate Getdirentries using fdopendir/readdir_r/closedir.
|
||||||
|
const ptrSize = unsafe.Sizeof(uintptr(0)) |
||||||
|
|
||||||
|
// We store the number of entries to skip in the seek
|
||||||
|
// offset of fd. See issue #31368.
|
||||||
|
// It's not the full required semantics, but should handle the case
|
||||||
|
// of calling Getdirentries or ReadDirent repeatedly.
|
||||||
|
// It won't handle assigning the results of lseek to *basep, or handle
|
||||||
|
// the directory being edited underfoot.
|
||||||
|
skip, err := Seek(fd, 0, 1 /* SEEK_CUR */) |
||||||
|
if err != nil { |
||||||
|
return 0, err |
||||||
|
} |
||||||
|
|
||||||
|
// We need to duplicate the incoming file descriptor
|
||||||
|
// because the caller expects to retain control of it, but
|
||||||
|
// fdopendir expects to take control of its argument.
|
||||||
|
// Just Dup'ing the file descriptor is not enough, as the
|
||||||
|
// result shares underlying state. Use Openat to make a really
|
||||||
|
// new file descriptor referring to the same directory.
|
||||||
|
fd2, err := Openat(fd, ".", O_RDONLY, 0) |
||||||
|
if err != nil { |
||||||
|
return 0, err |
||||||
|
} |
||||||
|
d, err := fdopendir(fd2) |
||||||
|
if err != nil { |
||||||
|
Close(fd2) |
||||||
|
return 0, err |
||||||
|
} |
||||||
|
defer closedir(d) |
||||||
|
|
||||||
|
var cnt int64 |
||||||
|
for { |
||||||
|
var entry Dirent |
||||||
|
var entryp *Dirent |
||||||
|
e := readdir_r(d, &entry, &entryp) |
||||||
|
if e != 0 { |
||||||
|
return n, errnoErr(e) |
||||||
|
} |
||||||
|
if entryp == nil { |
||||||
|
break |
||||||
|
} |
||||||
|
if skip > 0 { |
||||||
|
skip-- |
||||||
|
cnt++ |
||||||
|
continue |
||||||
|
} |
||||||
|
reclen := int(entry.Reclen) |
||||||
|
if reclen > len(buf) { |
||||||
|
// Not enough room. Return for now.
|
||||||
|
// The counter will let us know where we should start up again.
|
||||||
|
// Note: this strategy for suspending in the middle and
|
||||||
|
// restarting is O(n^2) in the length of the directory. Oh well.
|
||||||
|
break |
||||||
|
} |
||||||
|
// Copy entry into return buffer.
|
||||||
|
s := struct { |
||||||
|
ptr unsafe.Pointer |
||||||
|
siz int |
||||||
|
cap int |
||||||
|
}{ptr: unsafe.Pointer(&entry), siz: reclen, cap: reclen} |
||||||
|
copy(buf, *(*[]byte)(unsafe.Pointer(&s))) |
||||||
|
buf = buf[reclen:] |
||||||
|
n += reclen |
||||||
|
cnt++ |
||||||
|
} |
||||||
|
// Set the seek offset of the input fd to record
|
||||||
|
// how many files we've already returned.
|
||||||
|
_, err = Seek(fd, cnt, 0 /* SEEK_SET */) |
||||||
|
if err != nil { |
||||||
|
return n, err |
||||||
|
} |
||||||
|
|
||||||
|
return n, nil |
||||||
|
} |
@ -0,0 +1,9 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,386,!go1.12
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
|
@ -0,0 +1,9 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,amd64,!go1.12
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
|
@ -0,0 +1,11 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,386,!go1.12
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { |
||||||
|
return 0, ENOSYS |
||||||
|
} |
@ -0,0 +1,11 @@ |
|||||||
|
// Copyright 2019 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build darwin,arm64,!go1.12
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { |
||||||
|
return 0, ENOSYS |
||||||
|
} |
@ -0,0 +1,41 @@ |
|||||||
|
// go run mksyscall.go -l32 -tags darwin,386,go1.13 syscall_darwin.1_13.go
|
||||||
|
// Code generated by the command above; see README.md. DO NOT EDIT.
|
||||||
|
|
||||||
|
// +build darwin,386,go1.13
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
import ( |
||||||
|
"syscall" |
||||||
|
"unsafe" |
||||||
|
) |
||||||
|
|
||||||
|
var _ syscall.Errno |
||||||
|
|
||||||
|
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
|
||||||
|
|
||||||
|
func closedir(dir uintptr) (err error) { |
||||||
|
_, _, e1 := syscall_syscall(funcPC(libc_closedir_trampoline), uintptr(dir), 0, 0) |
||||||
|
if e1 != 0 { |
||||||
|
err = errnoErr(e1) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func libc_closedir_trampoline() |
||||||
|
|
||||||
|
//go:linkname libc_closedir libc_closedir
|
||||||
|
//go:cgo_import_dynamic libc_closedir closedir "/usr/lib/libSystem.B.dylib"
|
||||||
|
|
||||||
|
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
|
||||||
|
|
||||||
|
func readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) { |
||||||
|
r0, _, _ := syscall_syscall(funcPC(libc_readdir_r_trampoline), uintptr(dir), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) |
||||||
|
res = Errno(r0) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func libc_readdir_r_trampoline() |
||||||
|
|
||||||
|
//go:linkname libc_readdir_r libc_readdir_r
|
||||||
|
//go:cgo_import_dynamic libc_readdir_r readdir_r "/usr/lib/libSystem.B.dylib"
|
@ -0,0 +1,12 @@ |
|||||||
|
// go run mkasm_darwin.go 386 |
||||||
|
// Code generated by the command above; DO NOT EDIT.
|
||||||
|
|
||||||
|
// +build go1.13 |
||||||
|
|
||||||
|
#include "textflag.h" |
||||||
|
TEXT ·libc_fdopendir_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_fdopendir(SB) |
||||||
|
TEXT ·libc_closedir_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_closedir(SB) |
||||||
|
TEXT ·libc_readdir_r_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_readdir_r(SB) |
@ -0,0 +1,41 @@ |
|||||||
|
// go run mksyscall.go -tags darwin,amd64,go1.13 syscall_darwin.1_13.go
|
||||||
|
// Code generated by the command above; see README.md. DO NOT EDIT.
|
||||||
|
|
||||||
|
// +build darwin,amd64,go1.13
|
||||||
|
|
||||||
|
package unix |
||||||
|
|
||||||
|
import ( |
||||||
|
"syscall" |
||||||
|
"unsafe" |
||||||
|
) |
||||||
|
|
||||||
|
var _ syscall.Errno |
||||||
|
|
||||||
|
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
|
||||||
|
|
||||||
|
func closedir(dir uintptr) (err error) { |
||||||
|
_, _, e1 := syscall_syscall(funcPC(libc_closedir_trampoline), uintptr(dir), 0, 0) |
||||||
|
if e1 != 0 { |
||||||
|
err = errnoErr(e1) |
||||||
|
} |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func libc_closedir_trampoline() |
||||||
|
|
||||||
|
//go:linkname libc_closedir libc_closedir
|
||||||
|
//go:cgo_import_dynamic libc_closedir closedir "/usr/lib/libSystem.B.dylib"
|
||||||
|
|
||||||
|
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
|
||||||
|
|
||||||
|
func readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) { |
||||||
|
r0, _, _ := syscall_syscall(funcPC(libc_readdir_r_trampoline), uintptr(dir), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) |
||||||
|
res = Errno(r0) |
||||||
|
return |
||||||
|
} |
||||||
|
|
||||||
|
func libc_readdir_r_trampoline() |
||||||
|
|
||||||
|
//go:linkname libc_readdir_r libc_readdir_r
|
||||||
|
//go:cgo_import_dynamic libc_readdir_r readdir_r "/usr/lib/libSystem.B.dylib"
|
@ -0,0 +1,12 @@ |
|||||||
|
// go run mkasm_darwin.go amd64 |
||||||
|
// Code generated by the command above; DO NOT EDIT.
|
||||||
|
|
||||||
|
// +build go1.13 |
||||||
|
|
||||||
|
#include "textflag.h" |
||||||
|
TEXT ·libc_fdopendir_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_fdopendir(SB) |
||||||
|
TEXT ·libc_closedir_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_closedir(SB) |
||||||
|
TEXT ·libc_readdir_r_trampoline(SB),NOSPLIT,$0-0 |
||||||
|
JMP libc_readdir_r(SB) |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue