diff --git a/anyconnect_auth.go b/anyconnect_auth.go index 137420e..e4628f3 100644 --- a/anyconnect_auth.go +++ b/anyconnect_auth.go @@ -17,6 +17,7 @@ import ( "sync" "time" + "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "golang.org/x/net/publicsuffix" @@ -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 @@ -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 @@ -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 @@ -308,13 +310,18 @@ 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() } @@ -322,6 +329,13 @@ 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 @@ -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 } @@ -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) @@ -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 @@ -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) } diff --git a/client_supervisor.go b/client_supervisor.go index f4788e8..6609622 100644 --- a/client_supervisor.go +++ b/client_supervisor.go @@ -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 @@ -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 { @@ -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 } @@ -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) } } } diff --git a/cstp_client.go b/cstp_client.go index 759d863..8b2b9dc 100644 --- a/cstp_client.go +++ b/cstp_client.go @@ -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 diff --git a/fortinet_auth.go b/fortinet_auth.go index ae99b26..8df7ec7 100644 --- a/fortinet_auth.go +++ b/fortinet_auth.go @@ -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 @@ -363,22 +363,6 @@ 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() @@ -386,6 +370,9 @@ func (a *fortinetAuthentication) processAuthenticationResponse( 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 @@ -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(" fortinetMaximumTokenInfoFields { @@ -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{