Race condition in initialization code of ssl_PushIOLayer
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
nss (Ubuntu) |
New
|
Undecided
|
Unassigned |
Bug Description
I am working on an application that concurrently opens HTTPS connections through libcurl 7.42.1 on NSS 3.18. I checked the source code, and I believe the bug persists in the latest release of NSS, 3.23 at the time of writing.
I noticed occasional crashes during the first few HTTP connections opened by the application. The crashes happened when libcurl attempted to call function pointers that were supposed to have been initialized by ssl_SetupIOMethods.
I eventually produced a multi-threaded core dump that showed that the crashing thread had proceeded past the SSL initialization code while another thread was still inside ssl_InitIOLayer, a function that is only called by ssl_PushIOLayer, where the function call is protected by double-checked locking and PR_CallOnce.
I believe that the issue is the plain Boolean variable called ssl_inited that is used for double-checked locking. The compiler is free to reorder reads and writes to plain Boolean variables, and, alas, it makes use of that freedom in my binary. Here is proof:
(gdb) l
2729
2730 static PRStatus
2731 ssl_InitIOLayer
2732 {
2733 ssl_layer_id = PR_GetUniqueIde
2734 ssl_SetupIOMeth
2735 ssl_inited = PR_TRUE;
2736 return PR_SUCCESS;
2737 }
2738
(gdb) p ssl_inited
$2 = 1
(gdb) frame
#5 ssl_InitIOLayer () at sslsock.c:2734
(gdb) disassemble
Dump of assembler code for function ssl_InitIOLayer:
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
0x000000346f
=> 0x000000346f42881b <+59>: rep movsq %ds:(%rsi)
The assembly shows that ssl_inited is set to 1 before the call to ssl_SetupIOMethods. This causes double-checked locking to fail and allows other threads to proceed while ssl_InitIOLayer is still running.
#7 0x000000346f42c6cb in ssl_PushIOLayer (ns=0x7fd48c0dd560, stack=0x7fd48c0
2746 status = PR_CallOnce(
(gdb) l
2741 {
2742 PRFileDesc *layer = NULL;
2743 PRStatus status;
2744
2745 if (!ssl_inited) {
2746 status = PR_CallOnce(
2747 if (status != PR_SUCCESS)
2748 goto loser;
2749 }
The fix is to either remove ssl_inited and always call PR_CallOnce (at the cost of some performance), or make sure the compiler does not reorder accesses to ssl_inited. The best way to do the latter is platform dependant. I assume the Mozilla libraries have some utility code for this purpose (atomic Booleans and such).
This is a duplicate of Mozilla bug 1265127:
https:/ /bugzilla. mozilla. org/show_ bug.cgi? id=1265127
I had created the bug on launchpad before finding the more appropriate Mozilla bug tracking site for NSS. (It was rather hidden.) Sorry for that. Feel free to close here.