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
2 changes: 1 addition & 1 deletion AdminPortal/src/app/appointment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class AppointmentService {

confirmAppointment(id: number) {
let url = "http://localhost:8080/api/appointment/"+id+"/confirm";
return this.http.get(url, { withCredentials: true });
return this.http.post(url, null, { withCredentials: true });
}

}
6 changes: 4 additions & 2 deletions AdminPortal/src/app/appointment/appointment.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ export class AppointmentComponent implements OnInit {
}

confirmAppointment(id: number) {
this.appointmentService.confirmAppointment(id).subscribe();
location.reload();
this.appointmentService.confirmAppointment(id).subscribe(
res => location.reload(),
error => console.log(error)
);
}

ngOnInit() {}
Expand Down
9 changes: 7 additions & 2 deletions AdminPortal/src/app/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class LoginService {
Expand All @@ -15,12 +16,16 @@ export class LoginService {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Access-Control-Allow-Credentials' : true
});
return this.http.post(url, params, {headers: headers, withCredentials : true});
// Fetch the XSRF-TOKEN cookie first; Http sends it back as the X-XSRF-TOKEN header.
return this.http.get('http://localhost:8080/api/csrf', { withCredentials: true })
.mergeMap(() => this.http.post(url, params, {headers: headers, withCredentials : true}));
}

logout() {
let url = 'http://localhost:8080/logout';
return this.http.get(url, { withCredentials: true });
// Login rotates the CSRF token, so fetch the current XSRF-TOKEN cookie before posting.
return this.http.get('http://localhost:8080/api/csrf', { withCredentials: true })
.mergeMap(() => this.http.post(url, null, { withCredentials: true }));
}

}
4 changes: 2 additions & 2 deletions AdminPortal/src/app/navbar/navbar.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ export class NavbarComponent implements OnInit {
this.loginService.logout().subscribe(
res => {
localStorage.setItem('PortalAdminHasLoggedIn', '');
location.reload();
this.router.navigate(['/login']);
},
err => console.log(err)
);
location.reload();
this.router.navigate(['/login']);
}

getDisplay() {
Expand Down
12 changes: 8 additions & 4 deletions AdminPortal/src/app/user-account/user-account.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,17 @@ export class UserAccountComponent implements OnInit {
}

enableUser(username: string) {
this.userService.enableUser(username).subscribe();
location.reload();
this.userService.enableUser(username).subscribe(
res => location.reload(),
error => console.log(error)
);
}

disableUser(username: string) {
this.userService.disableUser(username).subscribe();
location.reload();
this.userService.disableUser(username).subscribe(
res => location.reload(),
error => console.log(error)
);
}


Expand Down
4 changes: 2 additions & 2 deletions AdminPortal/src/app/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ export class UserService {

enableUser (username: string) {
let url = "http://localhost:8080/api/user/"+username+"/enable";
return this.http.get(url, { withCredentials: true });
return this.http.post(url, null, { withCredentials: true });
}

disableUser (username: string) {
let url = "http://localhost:8080/api/user/"+username+"/disable";
return this.http.get(url, { withCredentials: true });
return this.http.post(url, null, { withCredentials: true });
}

}
6 changes: 6 additions & 0 deletions UserFront/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); //8081
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-xsrf-token");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");

Expand All @@ -37,7 +37,7 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type," +
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,x-xsrf-token");
response.setStatus(HttpServletResponse.SC_OK);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.userFront.config;

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SameSiteCookieConfig {

@Bean
public EmbeddedServletContainerCustomizer sameSiteCookieCustomizer() {
return container -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
((TomcatEmbeddedServletContainerFactory) container).addContextCustomizers(
context -> context.setCookieProcessor(new SameSiteCookieProcessor("Lax")));
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.userFront.config;

import java.nio.charset.Charset;
import java.util.Locale;

import javax.servlet.http.Cookie;

import org.apache.tomcat.util.http.CookieProcessor;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.Rfc6265CookieProcessor;
import org.apache.tomcat.util.http.ServerCookies;

/**
* Adds a SameSite attribute to every cookie Tomcat writes (JSESSIONID, remember-me, XSRF-TOKEN).
* The bundled Tomcat predates Rfc6265CookieProcessor#setSameSiteCookies, so the header is appended here.
*/
public class SameSiteCookieProcessor implements CookieProcessor {

private final CookieProcessor delegate;
private final String sameSite;

public SameSiteCookieProcessor(String sameSite) {
this(new Rfc6265CookieProcessor(), sameSite);
}

SameSiteCookieProcessor(CookieProcessor delegate, String sameSite) {
this.delegate = delegate;
this.sameSite = sameSite;
}

@Override
public void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies) {
delegate.parseCookieHeader(headers, serverCookies);
}

@Override
public String generateHeader(Cookie cookie) {
String header = delegate.generateHeader(cookie);
if (header.toLowerCase(Locale.ROOT).contains("; samesite=")) {
return header;
}
return header + "; SameSite=" + sameSite;
}

@Override
public Charset getCharset() {
return delegate.getCharset();
}
}
10 changes: 7 additions & 3 deletions UserFront/src/main/java/com/userFront/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.userFront.service.UserServiceImpl.UserSecurityService;
Expand Down Expand Up @@ -45,7 +46,8 @@ public BCryptPasswordEncoder passwordEncoder() {
"/contact/**",
"/error/**/*",
"/console/**",
"/signup"
"/signup",
"/api/csrf"
};

@Override
Expand All @@ -57,10 +59,12 @@ protected void configure(HttpSecurity http) throws Exception {
permitAll().anyRequest().authenticated();

http
.csrf().disable().cors().disable()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 Localhost pages can forge administrator actions

When an administrator visits another localhost page, XSRF-TOKEN remains readable across ports. That page can send credentialed POSTs with the token and change customer accounts or appointments.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed that this is possible, but I don't think it's a regression this PR introduces. Here's my analysis.

Why it happens

  • Browser cookies are not separated by port. Any page on localhost:* can read document.cookie, including the non-HttpOnly XSRF-TOKEN.
  • localhost:3000 and localhost:8080 count as the same site, so SameSite=Lax still sends the session cookie on that page's POSTs.
  • A header-based request (X-XSRF-TOKEN) from that page fails CORS preflight, because RequestFilter only allows http://localhost:4200. A plain form POST with _csrf=<token> doesn't need preflight, so it would get through.

Why I'm treating it as residual risk

  • The attacker must already be serving a page on the [REDACTED SECRET]'s own host. On master, any website anywhere can do this with a single GET.
  • The finding's recommendation names CookieCsrfTokenRepository.withHttpOnlyFalse() specifically. This is also Spring's standard SPA pattern, where the token is readable by design.
  • The localhost:4200 → localhost:8080 URLs are the project's dev layout. A real deployment would put the portal and API on their own origins.

Option if you want this closed too
Store the token server-side (HttpSessionCsrfTokenRepository). Return it from GET /api/csrf in a response header that only the allowed CORS origin can read. Have AdminPortal attach X-XSRF-TOKEN to each POST itself, instead of relying on Angular's cookie strategy.

That changes the approach the finding asked for, so I've left it for the requester to decide rather than changing it in this PR.

Written by Devin

.and()
.cors().disable()
.formLogin().failureUrl("/index?error").defaultSuccessUrl("/userFront").loginPage("/index").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public String recipientEdit(@RequestParam(value = "recipientName") String recipi
return "recipient";
}

@RequestMapping(value = "/recipient/delete", method = RequestMethod.GET)
@RequestMapping(value = "/recipient/delete", method = RequestMethod.POST)
@Transactional
public String recipientDelete(@RequestParam(value = "recipientName") String recipientName, Model model,
Principal principal) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.userFront.domain.Appointment;
Expand All @@ -26,7 +27,7 @@ public List<Appointment> findAppointmentList() {
return appointmentList;
}

@RequestMapping("/{id}/confirm")
@RequestMapping(value = "/{id}/confirm", method = RequestMethod.POST)
public void confirmAppointment(@PathVariable("id") Long id) {
appointmentService.confirmAppointment(id);
}
Expand Down
18 changes: 18 additions & 0 deletions UserFront/src/main/java/com/userFront/resource/CsrfResource.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.userFront.resource;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
* Lets the AdminPortal SPA obtain the XSRF-TOKEN cookie (issued by the CSRF filter) before its first POST.
*/
@RestController
public class CsrfResource {

@RequestMapping(value = "/api/csrf", method = RequestMethod.GET)
public ResponseEntity<Void> csrf() {
return ResponseEntity.noContent().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ public List<SavingsTransaction> getSavingsTransactionList(@RequestParam("usernam
return transactionService.findSavingsTransactionList(username);
}

@RequestMapping("/user/{username}/enable")
@RequestMapping(value = "/user/{username}/enable", method = RequestMethod.POST)
public void enableUser(@PathVariable("username") String username) {
userService.enableUser(username);
}

@RequestMapping("/user/{username}/disable")
@RequestMapping(value = "/user/{username}/disable", method = RequestMethod.POST)
public void diableUser(@PathVariable("username") String username) {
userService.disableUser(username);
}
Expand Down
3 changes: 0 additions & 3 deletions UserFront/src/main/resources/templates/appointment.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ <h3>Schedule An Appointment</h3>
</div>


<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<a class="btn btn-primary" id="submitAppointment">Submit Scheduling</a>
</form>
Expand Down
3 changes: 0 additions & 3 deletions UserFront/src/main/resources/templates/betweenAccounts.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@
<input th:value="${amount}" type="text" name="amount" id="amount" class="form-control" aria-label="Amount (to the nearest dollar)"/>
</div>

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<button class="btn btn-lg btn-primary btn-block" type="submit">Transfer</button>
</form>
Expand Down
6 changes: 5 additions & 1 deletion UserFront/src/main/resources/templates/common/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@
<ul class="dropdown-menu">
<li><a th:href="@{/user/profile}">Profile</a></li>
<li role="separator" class="divider"></li>
<li><a th:href="@{/logout}">Logout</a></li>
<li>
<form th:action="@{/logout}" method="post" class="navbar-form">
<button type="submit" class="btn btn-link">Logout</button>
</form>
</li>
</ul></li>
</ul>
</div>
Expand Down
3 changes: 0 additions & 3 deletions UserFront/src/main/resources/templates/deposit.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
<input th:value="${amount}" type="text" name="amount" id="amount" class="form-control" aria-label="Amount (to the nearest dollar)"/>
</div>

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<button class="btn btn-lg btn-primary btn-block" type="submit">Deposit</button>
</form>
Expand Down
10 changes: 6 additions & 4 deletions UserFront/src/main/resources/templates/recipient.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ <h3>Recipient Information</h3>
id="recipientDescription" placeholder="Description" th:text="${recipient.description}"></textarea>
</div>

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<button class="btn btn-primary" type="submit">Add/Edit Recipient</button>
</form>
Expand Down Expand Up @@ -69,7 +66,12 @@ <h3>List of Recipients</h3>
<td data-th-text="${eachRecipient.phone}">...</td>
<td data-th-text="${eachRecipient.accountNumber}">...</td>
<td data-th-text="${eachRecipient.description}">...</td>
<td><a th:href="@{/transfer/recipient/delete?recipientName=}+${eachRecipient.name}">delete</a></td>
<td>
<form th:action="@{/transfer/recipient/delete}" method="post">
<input type="hidden" name="recipientName" th:value="${eachRecipient.name}"/>
<button type="submit" class="btn btn-link">delete</button>
</form>
</td>
</tr>
</tbody>
</table>
Expand Down
3 changes: 0 additions & 3 deletions UserFront/src/main/resources/templates/toSomeoneElse.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@
<input th:value="${amount}" type="text" name="amount" id="amount" class="form-control" aria-label="Amount (to the nearest dollar)"/>
</div>

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<button class="btn btn-lg btn-primary btn-block" type="submit">Transfer</button>
</form>
Expand Down
3 changes: 0 additions & 3 deletions UserFront/src/main/resources/templates/withdraw.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
<input th:value="${amount}" type="text" name="amount" id="amount" class="form-control" aria-label="Amount (to the nearest dollar)"/>
</div>

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

<button class="btn btn-lg btn-primary btn-block" type="submit">Withdraw</button>
</form>
Expand Down
Loading