Introducing Qwiet AI AutoFix! Reduce the time to secure code by 95% Read More

# Authentication Bypass

All sensitive actions on your website should require the user to be *authenticated* (i.e. to have identified who they are) and to be *authorized* (i.e. to have sufficient permissions to perform that action). If web routes fail to check the user identity, attackers will be able to access sensitive resources.

JavaScript frameworks typically uses a routing library that updates the browser URL and the page contents in response to user actions. You should check whether the user has been authenticated before permitting them access to sensitive routes. Here’s some examples.

=== Angular

Routing in Angular is usually done with the `AppRoutingModule`:

“`typescript
@NgModule({
imports: [RouterModule.forRoot([// These paths are available to all users.
{ path: ”, component: HomeComponent },
{ path: ‘features’, component: FeaturesComponent },
{ path: ‘login’, component: LoginComponent },

// These routes are only available to users after logging in.
{ path: ‘feed’, component: FeedComponent, canActivate: [ AuthGuard ]},
{ path: ‘profile’, component: ProfileComponent, canActivate: [ AuthGuard ]},

// This is the fall-through component when the route is not recognized.
{ path: ‘**’, component: PageNotFoundComponent}

])],
exports: [RouterModule]
})
export class AppRoutingModule {}
“`

=== React

Routing in React is usually done with the `react-router` library:

“`jsx
function Routes(props) {
return (
<Router>
<Switch><!– These routes are publicly available. –>
<Route path=”/login”>
<Login/>
</Route>
<Route path=”/news”>
<News/>
</Route>
<Route path=”/about”>
<About/>
</Route>

<!– These routes are only available to authenticated user. –>
<AuthenticatedRoute path=”/feed” loggedIn={props.loggedIn}>
<Feed/>
</AuthenticatedRoute>

<AuthenticatedRoute path=”/profile” loggedIn={props.loggedIn}>
<Profile/>
</AuthenticatedRoute>

<Route path=”*”>
<NotFound/>
</Route>

</Switch>
</Router>
)
}

/**
* A wrapper for <Route> that redirects to the login screen if the user is not yet authenticated.
*/
function AuthenticatedRoute(props) {
if (props.loggedIn) {
return <Route {…props} />
}

return <Redirect to={{ pathname: `/login` }} />
}
“`

Authorization checks on the client-side can be overridden by an attacker, however, so it is important to check whether
the user is logged in when you load the data into your application. These authorization checks **must be performed in
server-side code**, and your client-side code should handful an authentication failure gracefully:

=== Angular

“`typescript
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<true | UrlTree> {

// Check the user is logged in, redirect them to the login screen if they are not.
return this.authService.isLoggedIn().pipe(
map(isLoggedIn => {
if (!isLoggedIn) {
return this.router.parseUrl(‘/login’)
}

return true
})
);
}
}
“`

“`typescript
export class AuthService {
constructor(private http: HttpClient) {}

// Whether the user is currently logged in.
loggedIn: boolean | null = null

// The user object.
user: User | null = null

// Check whether the user is logged in.
isLoggedIn(): Observable<boolean> {
return this.getCurrentUser().pipe(map(user => {
return user != null
}))
}

// Get the user definition from local state, or the server (if this is the first time we are checking).
getCurrentUser(): Observable<User | null> {
if (this.loggedIn !== null) {
return of(this.user)
}

return this.http.get<User>(‘/api/auth’, {
responseType: ‘json’
}).pipe(
tap({
next: user => {
// If we get a user definition from the server it indicates this user is logged in.
this.user = user
this.loggedIn = true
},
error: error => {
// A 401 response from the server indicates this user is not logged in.
this.user = null
this.loggedIn = false
}
}),
catchError(() => {
return of(null)
})
)
}
}

export interface User {
username: string;
}
“`

=== React

“`jsx
class Feed extends React.Component {
constructor(props) {
super(props)this.state = {
loading : true,
posts : [],
error : null
}
}

async componentDidMount() {

// Load the data for this component.
const response = await fetch(‘/api/feed’)
const data = await response.json()

if (response.ok && data.success) {

// Set the data in the component state.
this.setState({
loading : false,
posts : data.posts
})
}
else {

// Shown an error message if the feed cannot be loaded – for instance,
// if the user is not authenticated.
this.setState({
loading : false,
error : data.error || ‘There was a problem loading your feed.’
})
}
}

render() {
const error = this.state.error ? <div className=”error”>{this.state.error}</div> : null

let body
if (this.state.loading) {
body = <div className=”loading”>Loading…</div>
}
else {
// Render the component based on the data returned from the server.
body = this.state.posts.map(post => {
return <Post post={post}/>
})
}

return (
<div>
{error}
{body}
</div>
)
}
}
“`

 

## Further Considerations

Authentication bypass vulnerabilities tend to occur when mistakes are made during the design phase. To avoid this, make
sure you:

* Design your access control upfront and document it.
* Write unit tests to validate that unauthenticated users cannot access sensitive resources. These unit tests should
cover client-side routes *and* server-side logic.
* Think like an attacker: focus on the biggest risks your organization faces and prioritize securing those.
* Record user activity in server-side logs, so you have audit trails of who did what and when.

## CWEs

* [CWE-288](https://cwe.mitre.org/data/definitions/288.html)

About ShiftLeft

ShiftLeft empowers developers and AppSec teams to dramatically reduce risk by quickly finding and fixing the vulnerabilities most likely to reach their applications and ignoring reported vulnerabilities that pose little risk. Industry-leading accuracy allows developers to focus on security fixes that matter and improve code velocity while enabling AppSec engineers to shift security left.

A unified code security platform, ShiftLeft CORE scans for attack context across custom code, APIs, OSS, containers, internal microservices, and first-party business logic by combining results of the company’s and Intelligent Software Composition Analysis (SCA). Using its unique graph database that combines code attributes and analyzes actual attack paths based on real application architecture, ShiftLeft then provides detailed guidance on risk remediation within existing development workflows and tooling. Teams that use ShiftLeft ship more secure code, faster. Backed by SYN Ventures, Bain Capital Ventures, Blackstone, Mayfield, Thomvest Ventures, and SineWave Ventures, ShiftLeft is based in Santa Clara, California. For information, visit: www.shiftleft.io.

Share

See for yourself – run a scan on your code right now