micromdm / scep

Go SCEP server
MIT License
310 stars 121 forks source link

Fix data races in SignCSR #185

Closed korylprince closed 2 years ago

korylprince commented 2 years ago

This addresses the data race problems mentioned #184 by protecting the depot in SignCSR with a mutex. Currently if SignCSR gets overloaded it can break the whole depot by not correctly incrementing the serial (multiple concurrent requests can get the same serial), or checking the CN database can be inconsistent (multiple concurrent requests can cause errors because of concurrent file access or possibly return bad data).

It might be that mutexes could be added to the depot itself, but this could get much more complex without getting many (or any) speed gains. SignCSR calls depot.Serial near the top, then calls depot.Put at the bottom which internally calls depot.Serial, and both depot.Serial calls should return the same serial, so the serial should be locked for the length of SignCSR anyways.

klubi commented 2 years ago

@jessepeterson @groob Would you mind taking a look at this PR? Thanks!

jessepeterson commented 2 years ago

Sorry, I hadn't had a chance to look at this.

I really think this should be solved in the depot. Blocking the generic SignCSR service I don't think makes sense because there are depots that simply don't require it. For example:

https://github.com/jessepeterson/mysqlscepserver/blob/596b5de2ba4e1c3e4834b7a11f4e0e95a7aa6e4e/depot.go#L185-L192

As for the Bolt depot also calling Serial() — I think is a bug? Serial() is intended to generate a new unique serial number from the CA for a new certificate. The Depot should not be calling Serial for an existing cert to be written to the depot — that seems odd.

That's here:

https://github.com/micromdm/scep/blob/6dcd663818d9ddf15a372621ad07f54012e990c8/depot/bolt/depot.go#L96

This should be reading the serial from the supplied crt, I'd think.

korylprince commented 2 years ago

Yeah, both the file and bolt depots get the serial again in Put. The nice thing about MySQL is you get transactions for free. For the bolt and file depots, you definitely need locking on Serial at least. I think removing the Serial calls in Put would fix the data race, or at least make it much less likely.