Fix null pointer dereference in mpi_mod_int(0, 2)

Fix a null pointer dereference when performing some operations on zero
represented with 0 limbs: mbedtls_mpi_mod_int() dividing by 2, or
mbedtls_mpi_write_string() in base 2.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/ChangeLog.d/bignum-0-mod-2.txt b/ChangeLog.d/bignum-0-mod-2.txt
new file mode 100644
index 0000000..55e53e5
--- /dev/null
+++ b/ChangeLog.d/bignum-0-mod-2.txt
@@ -0,0 +1,4 @@
+Bugfix
+   * Fix a null pointer dereference when performing some operations on zero
+     represented with 0 limbs: mbedtls_mpi_mod_int() dividing by 2, or
+     mbedtls_mpi_write_string() in base 2.
diff --git a/library/bignum.c b/library/bignum.c
index db29ae5..32578e2 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -1829,7 +1829,7 @@
     /*
      * handle trivial cases
      */
-    if( b == 1 )
+    if( b == 1 || A->n == 0 )
     {
         *r = 0;
         return( 0 );
diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data
index 2addd23..f2a8656 100644
--- a/tests/suites/test_suite_mpi.data
+++ b/tests/suites/test_suite_mpi.data
@@ -73,12 +73,18 @@
 Test mpi_read_write_string #9 (Empty MPI hex -> dec)
 mpi_read_write_string:16:"":10:"0":4:0:0
 
+Test mpi_read_write_string #9 (Empty MPI hex -> base 2)
+mpi_read_write_string:16:"":2:"0":4:0:0
+
 Test mpi_read_write_string #8 (Empty MPI dec -> hex)
 mpi_read_write_string:10:"":16:"":4:0:0
 
 Test mpi_read_write_string #9 (Empty MPI dec -> dec)
 mpi_read_write_string:10:"":10:"0":4:0:0
 
+Test mpi_read_write_string #9 (Empty MPI dec -> base 2)
+mpi_read_write_string:16:"":2:"0":4:0:0
+
 Test mpi_write_string #10 (Negative hex with odd number of digits)
 mpi_read_write_string:16:"-1":16:"":3:0:MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL
 
@@ -1222,9 +1228,15 @@
 Test mbedtls_mpi_mod_int: 0 (null) % 1
 mbedtls_mpi_mod_int:16:"":1:0:0
 
+Test mbedtls_mpi_mod_int: 0 (null) % 2
+mbedtls_mpi_mod_int:16:"":2:0:0
+
 Test mbedtls_mpi_mod_int: 0 (null) % -1
 mbedtls_mpi_mod_int:16:"":-1:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
 
+Test mbedtls_mpi_mod_int: 0 (null) % -2
+mbedtls_mpi_mod_int:16:"":-2:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+
 Base test mbedtls_mpi_exp_mod #1
 mbedtls_mpi_exp_mod:10:"23":10:"13":10:"29":10:"24":0