Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 38 additions & 17 deletions anyconnect_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"sync"
"time"

"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"

"golang.org/x/net/publicsuffix"
Expand Down Expand Up @@ -57,11 +58,11 @@ type anyConnectAuthentication struct {
authenticatedAddress netip.Addr
peerCertificate *x509.Certificate
selectedGroup string
serverGroupSelection string
clientCertificateRetried bool
clientCertificateFailureCount int
clientCertificateFailureReason string
primaryPasswordSubmitted bool
emptyForms int
tokenGenerator *softwareTokenGenerator
closed bool
advancing bool
Expand Down Expand Up @@ -135,6 +136,7 @@ func (f *anyConnectFrontend) BeginAuthentication() authContinuation {
currentURL: &serverURL,
tokenGenerator: newSoftwareTokenGenerator(f.client.options.Token),
}
authentication.selectedGroup = authentication.stableCredential(authCacheAuthGroup)
if f.client.options.XMLPostDisabled {
authentication.stage = anyConnectAuthenticationInitialLegacy
authentication.xmlPost = false
Expand Down Expand Up @@ -244,7 +246,7 @@ func (a *anyConnectAuthentication) Advance(

func (a *anyConnectAuthentication) advanceInitialXML(ctx context.Context) (obtainedSession, *authenticationRequest, error) {
a.clearWebVPNCookie()
a.selectedGroup = a.stableCredential(authCacheAuthGroup)
a.primaryPasswordSubmitted = false
body, err := buildAnyConnectInitialXML(a.frontend.client, a.currentURL, a.selectedGroup, false)
if err != nil {
return nil, nil, err
Expand Down Expand Up @@ -308,20 +310,32 @@ func (a *anyConnectAuthentication) advanceAuthGroup(
if !loaded {
return nil, nil, E.Extend(ErrProtocolNotSupported, "authgroup response selected an unknown choice: ", selectedGroup)
}
a.selectedGroup = selectedChoice.Name
groupField.Value = selectedChoice.Name
applyAnyConnectAuthGroup(&a.currentForm, selectedChoice.Name)
if a.stageUsesXMLPost() && selectedChoice.Name != a.serverGroupSelection {
return a.selectAuthGroup(ctx, selectedChoice)
}

// Upstream process_auth_form takes the form's authgroup from the last group-select request, not from the option the gateway marks selected.
func (a *anyConnectAuthentication) selectAuthGroup(ctx context.Context, choice anyConnectFormChoice) (obtainedSession, *authenticationRequest, error) {
if a.stageUsesXMLPost() && choice.Name != a.selectedGroup {
a.selectedGroup = choice.Name
a.stage = anyConnectAuthenticationInitialXML
return a.advanceInitialXML(ctx)
}
a.selectedGroup = choice.Name
applyAnyConnectAuthGroup(&a.currentForm, choice.Name)
return a.yieldAuthenticationRequest()
}

func (a *anyConnectAuthentication) advanceForm(
ctx context.Context,
response *authenticationResponse,
) (obtainedSession, *authenticationRequest, error) {
groupField := findAnyConnectAuthGroup(&a.currentForm)
if groupField != nil {
choice, found := findAnyConnectChoice(groupField, response.Values[groupField.SubmissionKey])
if found && choice.Name != a.selectedGroup {
return a.selectAuthGroup(ctx, choice)
}
}
err := a.applyAuthenticationFieldValues(response, false)
if err != nil {
return nil, nil, err
Expand Down Expand Up @@ -367,7 +381,7 @@ func (a *anyConnectAuthentication) advanceSSOBrowser(
func (a *anyConnectAuthentication) submitAuthenticationForm(ctx context.Context) (obtainedSession, *authenticationRequest, error) {
for i := range a.currentForm.Fields {
field := &a.currentForm.Fields[i]
if field.Kind == anyConnectFormFieldPassword && field.StableCredential {
if !field.Ignore && field.Kind == anyConnectFormFieldPassword && field.StableCredential {
a.primaryPasswordSubmitted = true
break
}
Expand Down Expand Up @@ -505,19 +519,11 @@ func (a *anyConnectAuthentication) processAuthenticationForm(
}
groupField := findAnyConnectAuthGroup(&a.currentForm)
if groupField != nil {
a.serverGroupSelection = groupField.Value
stableGroup := a.stableCredential(authCacheAuthGroup)
if stableGroup != "" {
choice, found := findAnyConnectChoice(groupField, stableGroup)
if found {
a.selectedGroup = choice.Name
groupField.Value = choice.Name
applyAnyConnectAuthGroup(&a.currentForm, choice.Name)
if a.stageUsesXMLPost() && choice.Name != a.serverGroupSelection {
a.stage = anyConnectAuthenticationInitialXML
return a.advanceInitialXML(ctx)
}
return a.yieldAuthenticationRequest()
return a.selectAuthGroup(ctx, choice)
}
}
request := buildAnyConnectAuthGroupRequest(a.currentForm, *groupField)
Expand Down Expand Up @@ -558,6 +564,18 @@ func (a *anyConnectAuthentication) advanceClientCertificateFailure(ctx context.C
}

func (a *anyConnectAuthentication) yieldAuthenticationRequest() (obtainedSession, *authenticationRequest, error) {
// Upstream process_auth_form_cb cancels on the third consecutive form with nothing to fill besides the authgroup and hidden fields.
emptyForm := common.All(a.currentForm.Fields, func(field anyConnectFormField) bool {
return field.Ignore || field.Kind == anyConnectFormFieldHidden || field.Kind == anyConnectFormFieldSelect && field.Name == "group_list"
})
if emptyForm {
a.emptyForms++
if a.emptyForms == 3 {
return nil, nil, E.Errors(ErrAuthenticationFailed, E.New("gateway returned 3 consecutive authentication forms without credential fields"))
}
} else {
a.emptyForms = 0
}
request, err := a.buildAuthenticationRequest()
if err != nil {
return nil, nil, err
Expand Down Expand Up @@ -638,8 +656,11 @@ func (a *anyConnectAuthentication) buildAuthenticationRequest() (*authentication
default:
return nil, E.Extend(ErrProtocolNotSupported, "unsupported AnyConnect authentication field kind: ", field.Kind)
}
if a.currentForm.Error != "" && requestField.CacheKey == authCachePassword {
if (a.currentForm.Error != "" || a.primaryPasswordSubmitted) && requestField.CacheKey == authCachePassword {
request.ClearCacheKeys = []string{authCachePassword}
if request.Error == "" {
request.Error = "gateway rejected the primary credentials"
}
}
request.Fields = append(request.Fields, requestField)
}
Expand Down
16 changes: 14 additions & 2 deletions client_supervisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,22 @@ func (c *Client) runSupervisor(ctx context.Context) {
pendingRekeyEvent := false
reconnecting := false
var reconnectTimeoutRemaining time.Duration
var publishedAt time.Time
for {
if ctx.Err() != nil || c.isClosed() {
_ = closeObtainedSession(sessionState)
return
}
reconnectDelay := clientReconnectInitialBackoff - time.Since(publishedAt)
if reconnectDelay > 0 {
if c.options.Logger != nil {
c.options.Logger.DebugContext(ctx, "previous tunnel ended right after establishment; reconnecting in ", reconnectDelay)
}
if !c.waitClientReconnectBackoff(ctx, reconnectDelay, false, &reconnectTimeoutRemaining) {
_ = closeObtainedSession(sessionState)
return
}
}
if !c.waitResumed(ctx) {
_ = closeObtainedSession(sessionState)
return
Expand Down Expand Up @@ -243,6 +254,7 @@ func (c *Client) runSupervisor(ctx context.Context) {
_ = closeObtainedSession(sessionState)
return
}
publishedAt = time.Now()
c.publishTunnelConfigurationEvent(reason, configuration)
if c.options.Logger != nil {
if reason == TunnelConfigurationEventInitial {
Expand Down Expand Up @@ -285,7 +297,7 @@ func (c *Client) runSupervisor(ctx context.Context) {
reconnectTimeoutRemaining = c.options.ReconnectTimeout
backoff = clientReconnectInitialBackoff
if c.options.Logger != nil {
c.options.Logger.DebugContext(ctx, "established tunnel session was rejected; retrying immediately: ", sessionErr)
c.options.Logger.DebugContext(ctx, "established tunnel session was rejected; retrying: ", sessionErr)
}
continue
}
Expand Down Expand Up @@ -317,7 +329,7 @@ func (c *Client) runSupervisor(ctx context.Context) {
reconnectTimeoutRemaining = c.options.ReconnectTimeout
backoff = clientReconnectInitialBackoff
if c.options.Logger != nil {
c.options.Logger.DebugContext(ctx, "tunnel ended; retrying immediately: ", sessionErr)
c.options.Logger.DebugContext(ctx, "tunnel ended; retrying: ", sessionErr)
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions cstp_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 +783,11 @@ func parsePositiveCSTPInteger(value string, name string) (int, error) {
return parsed, nil
}

// Cisco ASA sends "disabled" for a timer that is turned off, upstream parses it as zero with atol.
func parseCSTPDuration(value string, name string) (time.Duration, error) {
if strings.EqualFold(strings.TrimSpace(value), "disabled") {
return 0, nil
}
seconds, err := parsePositiveCSTPInteger(value, name)
if err != nil {
return 0, err
Expand Down
39 changes: 7 additions & 32 deletions fortinet_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,11 @@ func (a *fortinetAuthentication) processAuthenticationResponse(
previousInitial bool,
) (obtainedSession, *authenticationRequest, error) {
a.rememberHTTPResponse(httpResponse)
var rejectedCacheKeys []string
if previousInitial {
rejectedCacheKeys = []string{authCachePassword}
}
if httpResponse.statusCode == http.StatusOK {
var rejectedCacheKeys []string
if previousInitial {
rejectedCacheKeys = []string{authCachePassword}
}
authenticationResultErr := fortinetAuthenticationResultError(httpResponse.body, rejectedCacheKeys...)
if authenticationResultErr != nil {
return nil, nil, authenticationResultErr
Expand Down Expand Up @@ -363,29 +363,16 @@ func (a *fortinetAuthentication) processAuthenticationResponse(
return a.beginSAMLAuthentication(location)
}
}
if isFortinetHTMLResponse(httpResponse) {
a.access.Lock()
currentURL := cloneFortinetURL(a.currentURL)
realm := a.realm
a.access.Unlock()
if currentURL == nil {
return nil, nil, markTerminal(E.New("authentication endpoint is empty"))
}
samlURL := newFortinetEndpointURL(currentURL, "/remote/saml/start")
if realm != "" {
query := make(url.Values)
query.Set("realm", realm)
samlURL.RawQuery = query.Encode()
}
return a.beginSAMLAuthentication(samlURL)
}
a.access.Lock()
username := a.username
a.access.Unlock()
form, parseErr := parseFortinetTokenInfo(httpResponse.body, username)
if parseErr != nil {
return nil, nil, markTerminal(parseErr)
}
if form == nil {
return nil, nil, newRetryableAuthenticationError(E.New("logincheck returned neither SVPNCOOKIE nor a challenge"), rejectedCacheKeys...)
}
a.access.Lock()
a.currentForm = form
a.currentInitial = false
Expand Down Expand Up @@ -565,18 +552,6 @@ func (a *fortinetAuthentication) completeSAMLAuthentication(
return a.completeAuthenticatedResponse(ctx, httpResponse, state)
}

func isFortinetHTMLResponse(response fortinetHTTPResponse) bool {
contentType := strings.ToLower(response.header.Get("Content-Type"))
if strings.HasPrefix(contentType, "text/html") {
return true
}
trimmed := bytes.TrimSpace(response.body)
lowerContent := bytes.ToLower(trimmed)
return bytes.HasPrefix(lowerContent, []byte("<!doctype html")) ||
bytes.HasPrefix(lowerContent, []byte("<html")) ||
bytes.Contains(lowerContent, []byte("/remote/saml/"))
}

func parseFortinetSAMLCallback(callback string) (string, error) {
callbackURL, parseErr := url.Parse(callback)
if parseErr != nil {
Expand Down
4 changes: 2 additions & 2 deletions fortinet_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func parseFortinetAuthenticationResult(content []byte) (int, bool, error) {
func parseFortinetTokenInfo(content []byte, username string) (*fortinetAuthenticationForm, error) {
trimmed := strings.TrimSpace(string(content))
if !strings.HasPrefix(trimmed, "ret=") {
return nil, E.New("tokeninfo response does not begin with ret")
return nil, nil
}
segments := strings.Split(trimmed, ",")
if len(segments) > fortinetMaximumTokenInfoFields {
Expand Down Expand Up @@ -109,7 +109,7 @@ func parseFortinetTokenInfo(content []byte, username string) (*fortinetAuthentic
}
tokenInfo, loaded := values["tokeninfo"]
if !loaded {
return nil, E.New("challenge omitted tokeninfo")
return nil, nil
}
formID := "_challenge"
form := &fortinetAuthenticationForm{
Expand Down