# Elliptic Curves in Continuous-Variable Quantum Systems

Maxwell Aifer  Department of Physics, University of Maryland, Baltimore
County, Baltimore, MD 21250, USA  Evan Sheldon  Department of Physics,
University of Maryland, Baltimore County, Baltimore, MD 21250, USA

(September 2022)

###### Abstract

Elliptic curves are planar curves which can be used to define an abelian
group. The efficient computation of discrete logarithms over this group is a
longstanding problem relevant to cryptography. It may be possible to
efficiently compute these logarithms using a quantum computer, assuming that
the group addition operation can be computed efficiently on a quantum device.
Currently, however, thousands of logical qubits are required for elliptic
curve group addition, putting this application out of reach for near-term
quantum hardware. Here we give an algorithm for computing elliptic curve group
addition using a single continuous-variable mode, based on weak measurements
of a system with a cubic potential energy. This result could lead to
improvements in the efficiency of elliptic curve discrete logarithms using a
quantum device.

_Introduction.—_ Elliptic curves have a prominent role in number theory, and
are of great practical importance in modern cryptography, as they provide an
alternative to the RSA algorithm bernstein2017post ; washington2008elliptic ;
koblitz1993introduction . This makes the efficient computation of the elliptic
curve group operation (and the discrete logarithm over this group) a question
of great importance. As alternative computing paradigms can in some cases
provide speed-ups over classical digital computers, it is of interest to
explore the computation of elliptic curve group operations in different
paradigms.

Previous work has explored the use of discrete-variable and quantum computers
to evaluate the elliptic curve group operation and take discrete logarithms
over this group; however, to use these results in practical scenarios requires
thousands of logical qubits haner2020improved , placing it beyond NISQ-era
capabilities. Continuous-variable quantum information is seen as a promising
approach to realizing cryptographic protocols like quantum key distribution
jain2022practical ; weedbrook2012gaussian , as continuous-variable states are
compatible with existing telecom infrastructure; however, to our knowledge, no
attempt has been made to evaluate the elliptic curve group using continuous
variable quantum systems. There has also been significant effort to design
classical computing hardware for elliptic curve group addition verri2020review
.

In this work, we propose a method for evaluating the group operation of an
elliptic curve (over the reals) using a continuous-variable quantum system. As
is well known, the elliptic curve group addition operation can be cast as a
geometric relationship between points in the plane, in particular by
identifying points of intersection between a straight line and an elliptic
curve washington2008elliptic ; koblitz1993introduction . We show that a
continuous-variable quantum system can be designed whose energy eigenstates
have Wigner functions resembling elliptic curves, by implementing a
Hamiltonian with a cubic potential energy function. Moreover, weak quantum
measurements of quadrature operators can effectively project this Wigner
function onto a straight line in the plane, resulting in a method for elliptic
curve point addition.

Interestingly, this algorithm is entirely based on the geometric properties of
a quantum system’s Wigner function, and those of the weak measurement
operation. We note that existing algorithms of elliptic curve group addition
work by operating on binary encodings of elliptic curves, and these encodings
do not readily exhibit the geometry of the problem. In contrast, our algorithm
operates directly on an object that geometrically embodies the elliptic curve,
namely the Wigner function of a continuous-variable mode. We therefore
consider this algorithm exemplary of a novel ”geometric computing” paradigm,
which may be applicable both in classical and quantum settings.

It is also shown that a superconducting nonlinear asymmetric inductive element
(SNAIL) device PhysRevLett.125.160501 ; frattini20173  can be used to realize
the necessary cubic potential physically, suggesting a path to the
experimental implementation of our algorithm.

_Elliptic Curves in a Continuous Variable Quantum System.—_ A real elliptic
curve is the set of points $(x,y)\in\mathbb{R}^{2}$ defined by the equation
koblitz1993introduction

$y^{2}=ax^{3}+bx+c,$ (1)

for some $a,b,c\neq 0$. A group can be defined over the points of an elliptic
curve. Let $A=(x_{A},y_{A})$ and $B=(x_{B},y_{B})$ be two points belonging to
an elliptic curve, as in Fig. 1a. We denote the slope of the line connecting
$A$ and $B$ by $s=(y_{B}-y_{A})/(x_{B}-x_{A})$. We may compute a third point
$C=(x_{C},y_{C})$ from $A$ and $B$ as follows

$x_{C}=s^{2}-x_{A}-x_{B},$ (2) $y_{C}=-y_{A}+s(x_{A}-x_{B}).$ (3)

Then we may define a binary operation ($+$) acting on points of the curve by

$A+B=-C$ (4)

where $-C=(x_{C},-y_{C})$ is the reflection of $C$ over the $x$ axis. It can
be shown that the points of the curve form a group under the operation $(+)$.
Graphically, we can interpret the group addition rule in the following way: to
obtain the point $C$, take points $A$ and $B$, draw a line that intersects the
2 points and also a third point $-C$ on the curve (See Fig. 1a). Finally, $-C$
is reflected over the $x$ axis to obtain $C$. We also define coordinates $r$
and $\theta$ as an alternative way to specify the line between $A$ and $B$.
Namely,

$\theta=\arctan(s),\>\>\>r=(y_{A}-sx_{A})\cos(\theta)$ (5)

Elliptic curves appear naturally as the characteristic phase-space curves of a
system with a cubic potential energy. Suppose that a classical system has a
potential energy

$V(x)=-ax^{3}-bx,$ (6)

with real constants $a,b>0$. Then the classical Hamiltonian is given by

$H(x,p)=-ax^{3}-bx+\frac{1}{2m}p^{2},$ (7)

where $m$ is the mass. Consider the constant energy set obtained by setting
$H(x,p)=E$. If we make the identifications $E=c$ and $y=p/\sqrt{2m}$, then Eq.
(7) is equivalent to Eq. (1), so the equal-energy curves are elliptic curves
as shown in Fig. 1(a). A corresponding quantum Hamiltonian can be defined by
replacing the variables $x$ and $p$ with the dimensionless quadrature
operators $\hat{x}=(\hat{a}^{\dagger}+\hat{a})/\sqrt{2}$ and
$\hat{p}=i(\hat{a}^{\dagger}-\hat{a})/\sqrt{2}$, where $\hat{a}^{\dagger}$ and
$\hat{a}$ are respectively the creation and annihilation operators for a
single bosonic mode serafini2017quantum ; schleich2011quantum . That is, we
define

$\hat{H}=-a\hat{X}^{3}-b\hat{X}+\frac{1}{2m}\hat{P}^{2}.$ (8)

A Hamiltonian of this form can be realized physically using a SNAIL device
PhysRevLett.125.160501  with the correct choice of parameters. Note that the
SNAIL device can interpolate between quadratic and cubic Hamiltonians;
therefore one can begin with an eigenstate of the harmonic oscillator
Hamiltonian, and then adiabatically deform the Hamiltonian into the the form
of Eq. (8), which will result in an energy eigenstate of the latter
kato1950adiabatic . We now consider an eigenstate of the elliptic curve
Hamiltonian, that is a wavefunction $\ket{\Psi}$ satisfying the time-
independent Schrödinger equation

$\hat{H}\ket{\Psi}=E\ket{\Psi},$ (9)

where we have set $\hbar=1$. In particular, we consider the Wigner function of
such an energy eigenstate, defined as schleich2011quantum

$W(x,p)=\int_{-\infty}^{\infty}dye^{ipy}\Braket{x-\frac{y}{2}}{\Psi}\Braket{\Psi}{x+\frac{y}{2}}.$
(10)

Figure 1: (a) The elliptic curve corresponding to the classical Hamiltonian
(7) with parameters $a=0.075$ and $b=-1$, and $m=1$, and $E=1.62$ (arbitrary
units). (b) The Wigner function derived from the Eigenvector of the quantum
Hamiltonian (9) with the same parameters and $\hbar=0.1$. In some places,
there were values of the Wigner function as large as $W=1.53$, but to make the
form of the function easily visible, values of the Wigner function are cut off
at $\pm 0.75$.

The Wigner function is a quasiprobability distribution which shares certain
features with classical phase space probability density function, notably that
integrating it in any direction results in a valid marginal probability
density function. We therefore intuitively expect that the Wigner function
$W(x,p)$ of the energy eigenstate $\ket{\Psi}$ will be concentrated around the
classical phase-space orbit corresponding to energy $E$. In Fig. 1, we see
that this is in fact the case; we have plotted both the classical phase space
orbit in panel (a), and the Wigner function of the quantum Hamiltonian in
panel (b), and remark that the Wigner function of the classical system shows
high concentration around the classical phase space orbit. There are also
regions where the Wigner function has support that are distant from the
classical phase space orbit. However, one notices that in these regions the
Wigner function oscillates rapidly, meaning that they will often be eliminated
from the marginal distributions due to destructive interference. The Wigner
function was obtained in two steps. First, the eigenstate $\ket{\Psi}$ was
constructed in the position basis by discretizing the Hamiltonian operator and
then numerically performing an eigendecomposition. Then the Wigner function
was evaluated on a grid via straightforward numerical integration of Eq. (10)
using methods similar to those described in Stack_Exchange . We also adapted
code from Stack_Exchange  for generating plots of the Wigner function.

Having found a way to realize quantum states that are representative of
elliptic curves, we next will turn to the problem of approximately evaluating
the elliptic curve group addition operation using this state.

_Evaluation of the Elliptic Curve Group Operation.—_ The problem we would like
to solve is as follows: given two points $A=(x_{A},y_{A})$ and
$B=(x_{B},y_{B})$, evaluate the coordinates of the point $C=A+B$, where
addition is understood as defined in equations (2) and (3). Graphically, the
addition operation can be carried out by drawing a line through the points $A$
and $B$, then finding the third point where this line intersects the elliptic
curve, and finally reflecting the point thus obtained over the $x$ axis. After
a measurement of a quadrature operator (that is, a linear combination of the
$\hat{X}$ and $\hat{P}$ operators), the Wigner function will “collapse” so
that its support is a line in the phase space. However, performing such a
measurement on the elliptic curve state described earlier would leave none of
the structure of that state, making it impossible to extract the result of the
group addition operation. Alternatively, we can consider weak measurements of
a quadrature operator on an elliptic curve state nielsen2010quantum ;
wiseman2009quantum . Such a weak measurement can be seen as a kind of
interpolation between the identity operation (leaving the elliptic curve state
unchanged) and a projective quadrature measurement (completely collapsing the
wavefunction). This can be accomplished using weak measurements of a quantum
system with the cubic potential energy in Eq. (6). Specifically, define a
basis of quadrature states $\ket{\psi_{\theta}}$ as the eigenvectors of the
quadrature operator $x_{\theta}$

$\hat{X}_{\theta}\ket{x_{\theta}}=x_{\theta}\ket{x_{\theta}},$ (11)

where

$\hat{X}_{\theta}=\cos(\theta)\hat{X}+\sin(\theta)\hat{P}.$ (12)

To define a weak measurement of quadrature $\hat{X}_{\theta}$ having outcome
$\mu$ and width parameter $w$, we define the Krauss operator

$K_{\theta}=\frac{2^{1/4}}{(\pi
w^{2})^{1/4}}\int_{-\infty}^{\infty}dx_{\theta}e^{-(x_{\theta}-\mu)^{2}/w^{2}}\ket{x_{\theta}}\bra{x_{\theta}}$
(13)

For a system initialized in the state $\ket{\psi_{0}}$, the Krauss operator
can be used to determine the post-measurement state $\ket{\psi_{\text{pm}}}$
as follows

$\ket{\psi_{\text{pm}}}=\frac{K_{\theta}\ket{\psi_{0}}}{\sqrt{\braket{\psi_{0}}{K_{\theta}^{\dagger}K_{\theta}}{\psi_{0}}}}.$
(14)

Figure 2: (a) The post-measurement state after a weak measurement of a
quadrature operator $\hat{X}_{\theta}$, with $\theta=\pi/12$ and $r=1.5$.
Similarly to Fig.1, the range of values for the Wigner function has been
restricted, in this case to the interval $\pm 1.42$. In some places, there
were values of the Wigner function as large as $W=2.84$. (b) Marginal
distribution for the second quadrature measurement (of the operator
$\hat{X}_{\theta+\pi/2}$). The blue curve $f(x)$ is the probability density
function for the marginal distribution, and the orange curve $F(x)$ is the
cumulative distribution function, where the three peaks correspond to the
three blue regions of concentration in phase space of the Wigner function in
Fig. 2a. In Fig. 2a we also see two regions of concentration with wavelike
patterns in between these, which are not present in the marginal due to
destructive interference. Figure 3: (a) The post-measurement state after a
weak measurement of a quadrature operator $\hat{X}_{\theta}$, with
$\theta=\pi/12$ and $r=0.07$. Similarly to Fig.1, the range of values for the
Wigner function has been restricted, in this case to the interval $\pm 1.31$.
In some places, there were values of the Wigner function as large as $W=2.61$.
(b) Marginal distribution for the second quadrature measurement (of the
operator $\hat{X}_{\theta+\pi/2}$). The blue curve $f(x)$ is the probability
density function for the marginal distribution, and the orange curve $F(x)$ is
the cumulative distribution function, where the peaks correspond to the blue
regions of concentration in phase space of the Wigner function in Fig. 3a.

In Figs. 2 and 3 we see the effect of a weak quadrature measurement on the
Wigner function of our system, initially prepared in an eigenstate of the
Hamiltonian (8).

  1. 1.

Prepare an energy eigenstate $\ket{\psi_{n}}$ of the cubic Hamiltonian.

  2. 2.

Compute the polar coordinates $r,\theta$ from Eq. (5), and make a weak
measurement of the quadrature $x_{\theta}$.

  3. 3.

Choose some tolerance $\delta_{r}$. If $|x_{\theta}-r|>\delta_{r}$, repeat
steps 1 and 2 until $|x_{\theta}-r|\leq\delta_{r}$. This will require
$O(1/\delta_{r})$ trials on average.

  4. 4.

Take a projective measurement of the quadrature $x_{\theta+\pi/2}$, and
compute $x$ and $y$.

  5. 5.

Make sure that the computed $x$ and $y$ are not the points $A$ or $B$, and if
so, repeat steps 1-4

_Discussion.—_ In summary, we have demonstrated the ability to perform the
group addition operation over an elliptic curve group by performing weak
measurements on elliptic curve-shaped Wigner functions, which could be
realized experimentally using a quantum SNAIL device PhysRevLett.125.160501 .
Once the validity of our method has been demonstrated through experiments, the
algorithm can be modified and extended to accomplish more complex tasks. In
particular, it is desirable to extend this method to perform elliptic curve
exponentiation Exponentiation ; if an elliptic curve exponentiation can be
performed that preserves a coherent superposition, then Shor’s algorithm may
be applied to achieve efficient computation of the discrete logarithm, which
would have far-reaching impacts in cryptography.

Further investigations into this topic include implementing quantum error-
correcting procedures for this continuous variable state. Given that this
protocol will be affected by environmental decoherence, the experimental
realization of this algorithm would require a protocol for continuous-variable
error correction, which has been investigated to some extent van2010note ;
dias2018quantum ; barnes2004stabilizer .

It is also important to estimate the resource costs of our quantum algorithm,
especially the time and energy needed to evaluate the elliptic curve group
addition operation. Analyses of the time and energy costs of discrete-variable
quantum computations have been carried out ikonen2017energy ;
deffner2021energetic ; aifer2022quantum ; auffeves2022quantum , and a similar
method could be adapted to continuous-variable systems to address our
algorithm.

## References

  * [1] Daniel J Bernstein and Tanja Lange.  Post-quantum cryptography.  Nature, 549(7671):188–194, 2017.
  * [2] Lawrence C Washington.  Elliptic curves: number theory and cryptography.  CRC press, 2008.
  * [3] Neal Koblitz.  Introduction to elliptic curves and modular forms, volume 97.  Springer Science & Business Media, 1993.
  * [4] Thomas Häner, Samuel Jaques, Michael Naehrig, Martin Roetteler, and Mathias Soeken.  Improved quantum circuits for elliptic curve discrete logarithms.  In Post-Quantum Cryptography: 11th International Conference, PQCrypto 2020, Paris, France, April 15–17, 2020, Proceedings 11, pages 425–444. Springer, 2020.
  * [5] Nitin Jain, Hou-Man Chin, Hossein Mani, Cosmo Lupo, Dino Solar Nikolic, Arne Kordts, Stefano Pirandola, Thomas Brochmann Pedersen, Matthias Kolb, Bernhard Ömer, et al.  Practical continuous-variable quantum key distribution with composable security.  Nature communications, 13(1):4740, 2022.
  * [6] Christian Weedbrook, Stefano Pirandola, Raúl García-Patrón, Nicolas J Cerf, Timothy C Ralph, Jeffrey H Shapiro, and Seth Lloyd.  Gaussian quantum information.  Reviews of Modern Physics, 84(2):621, 2012.
  * [7] Arielle Verri Lucca, Guilherme Augusto Mariano Sborz, Valderi Reis Quietinho Leithardt, Marko Beko, Cesar Albenes Zeferino, and Wemerson Delcio Parreira.  A review of techniques for implementing elliptic curve point multiplication on hardware.  Journal of Sensor and Actuator Networks, 10(1):3, 2020.
  * [8] Timo Hillmann, Fernando Quijandría, Göran Johansson, Alessandro Ferraro, Simone Gasparinetti, and Giulia Ferrini.  Universal gate set for continuous-variable quantum computation with microwave circuits.  Phys. Rev. Lett., 125:160501, Oct 2020.
  * [9] NE Frattini, U Vool, S Shankar, A Narla, KM Sliwa, and MH Devoret.  3-wave mixing josephson dipole element.  Applied Physics Letters, 110(22), 2017.
  * [10] Alessio Serafini.  Quantum continuous variables: a primer of theoretical methods.  CRC press, 2017.
  * [11] Wolfgang P Schleich.  Quantum optics in phase space.  John Wiley & Sons, 2011.
  * [12] Tosio Kato.  On the adiabatic theorem of quantum mechanics.  Journal of the Physical Society of Japan, 5(6):435–439, 1950.
  * [13] Nanite.  Efficient numerical evaluation of wigner function.  Physics Stack Exchange, Jul 2020.
  * [14] Michael A Nielsen and Isaac L Chuang.  Quantum computation and quantum information.  Cambridge university press, 2010.
  * [15] Howard M Wiseman and Gerard J Milburn.  Quantum measurement and control.  Cambridge university press, 2009.
  * [16] Kirsten Eisenträger, Kristin Lauter, and Peter L. Montgomery.  Fast elliptic curve arithmetic and improved weil pairing evaluation.  In Marc Joye, editor, Topics in Cryptology — CT-RSA 2003, pages 343–354, Berlin, Heidelberg, 2003. Springer Berlin Heidelberg.
  * [17] Peter van Loock.  A note on quantum error correction with continuous variables.  Journal of Modern Optics, 57(19):1965–1971, 2010.
  * [18] Josephine Dias and Timothy C Ralph.  Quantum error correction of continuous-variable states with realistic resources.  Physical Review A, 97(3):032335, 2018.
  * [19] Richard L Barnes.  Stabilizer codes for continuous-variable quantum error correction.  arXiv preprint quant-ph/0405064, 2004.
  * [20] Joni Ikonen, Juha Salmilehto, and Mikko Möttönen.  Energy-efficient quantum computing.  npj Quantum Information, 3(1):17, 2017.
  * [21] Sebastian Deffner.  Energetic cost of hamiltonian quantum gates.  Europhysics Letters, 134(4):40002, 2021.
  * [22] Maxwell Aifer and Sebastian Deffner.  From quantum speed limits to energy-efficient quantum gates.  New Journal of Physics, 24(5):055002, 2022.
  * [23] Alexia Auffeves.  Quantum technologies need a quantum energy initiative.  PRX Quantum, 3(2):020101, 2022.

##  Appendix A Elliptic Curves

The material on elliptic curves here is taken from references [3] and [2].

An elliptic curve is a curve that is defined by the equation

$y^{2}=ax^{3}+bx+c$ (15)

If we want to represent the points on an elliptic curve as a group, we can
take points A and B, draw a line that intersects the 2 points, and also a
third point C on the curve; as displayed in (a). We can then define

$A+B=-C$ (16)

where $-C$ is a reflection of $C$ across the x-axis.

In the case of (b), the third intersection point C approaches B, and the line
becomes tangent to the curve at B. As a result, the tangent point, $B$ is also
the intersection point so we can define

$A+B=-B$ (17)

In the case of $B=-A$ as seen in (c), we encounter a vertical intersection
line through the curve. An issue in this case is that we don’t have a third
point on the curve our line intersects. Our solution is to define an
additional point $\mathcal{O}$ at infinity. An important property is that
$\mathcal{O}$ exists on all vertical lines.

$A+B=A+(-A)=\mathcal{O}$ (18)

The last case (d) we will look over is a vertical line with one point of
intersection on the curve, $B=A$. Since our intersection line is vertical, we
can represent this case as

$A+A=\mathcal{O}$ (19)

##  Appendix B Phase Space Description

The material on the quantum phase space formalism is taken from references
[10] and [11]. The state of a quantum system is, in general, represented by a
density operator $\hat{\rho}$, which may be expanded in an eigenbasis of pure
states as

$\hat{\rho}=\sum_{n}p_{n}\ket{\psi_{n}}\bra{\psi_{n}}.$ (20)

Absent from this description is any concept of the phase space, which is
prominent in the corresponding classical theory. However, quantum systems also
admit a phase-space description, which can be found using the Weyl
transformation. An operator $\hat{A}$ acting on the quantum Hilbert space can
be mapped to a phase-space function $\tilde{A}(x,p)$ via

$\tilde{A}(x,p)=\int_{-\infty}^{\infty}dye^{ipy/\hbar}\Braket{x-\frac{y}{2}}{\hat{A}}{x+\frac{y}{2}}$
(21)

So, if we want to be able to map the action of the density matrix in phase
space, we should perform a Weyl transformation on the density matrix, and in
doing so we can derive the Wigner function.

$W(x,p)=\tilde{\rho}/h=\frac{1}{h}\int_{-\infty}^{\infty}dye^{ipy/\hbar}\Braket{x-\frac{y}{2}}{\hat{\rho}}{x+\frac{y}{2}}$
(22)

One of the key properties of the Wigner function is that we can calculate the
probability distribution in space or momentum of the state by integrating
along $p$ or $x$ respectively.

$\displaystyle\int_{-\infty}^{\infty}W(x,p)dp=\braket{x}{\hat{\rho}}{x}=\rho(x,x)=P(x)$
(23)
$\displaystyle\int_{-\infty}^{\infty}W(x,p)dx=\braket{p}{\hat{\rho}}{p}=P(p)$
(24)

In fact, the Wigner function can be marginalized over an arbitrary axis in the
$x$-$p$ plane to yield a probability distribution for the perpendicular
coordinate. That is, if we define the variables $x_{\theta}$ and $p_{\theta}$
(called quadratures)

$x_{\theta}=\cos(\theta)x+\sin(\theta)p,\>\>\>\>p_{\theta}=-\sin(\theta)x+\cos(\theta)p.$
(25)

Integrating the Wigner function with respect to one of these quadratures gives
the probability density function for the perpendicular one

$\displaystyle\int_{-\infty}^{\infty}W(x_{\theta},p_{\theta})dp_{\theta}=\braket{x}{\hat{\rho}}{x}=P(x_{\theta})$
(26)
$\displaystyle\int_{-\infty}^{\infty}W(x_{\theta},p_{\theta})dx=P(p_{\theta}).$
(27)

Importantly, the Wigner function is not quite a probability distribution, as
it can have negative values, and in fact the negativity of the Wigner function
characterizes the quantum behavior of a system. For this reason the Wigner
function is often referred to as a quasi-probability distribution.

Although typically a continuous-variable quantum state is expressed in the
position or momentum basis, we may also use the basis corresponding to the
quadrature variables $x_{\theta}$ or $p_{\theta}$. To this end, we define a
quadrature operator $\hat{X}_{\theta}$

$\hat{X}_{\theta}=\cos(\theta)\hat{x}+\sin(\theta)\hat{p},$ (28)

where we restrict the region of theta to $0\leq\theta\leq\pi$. The basis
associated with this operator is determined by the eigenvalue equation

$\hat{X}_{\theta}\ket{X_{\theta}}=X_{\theta}\ket{X_{\theta}}.$ (29)

Multiply both sides by $\bra{x}$ to achieve

$\displaystyle\braket{x}{\hat{X}_{\theta}}{X_{\theta}}=\braket{x}{X_{\theta}}{X_{\theta}}$
(30) $\displaystyle\rightarrow\hat{X}_{\theta}\psi(x)=X_{\theta}\psi(x)$ (31)

where $\psi(x)=\braket{x}{X_{\theta}}$.

$\displaystyle\rightarrow(\cos(\theta)\hat{x}+\sin(\theta)\hat{p})\psi(x)=X_{\theta}\psi(x)$
(32)
$\displaystyle\rightarrow\cos(\theta)x\psi(x)-i\hbar\sin(\theta)\partial_{x}\psi(x)=X_{\theta}\psi(x)$
(33)

The solution to this eigenvalue problem is

$\psi(x)=C_{\theta}\exp\left[\frac{-ix(-2X_{\theta}+x\cos(\theta))}{2\hbar\sin(\theta)}\right]$
(34)

Since this wavefunction is imaginary, we need to normalize it in reference to
delta functions. By projecting onto the completeness relation and utilizing
orthogonality, we yield the normalization constant

$|C_{\theta}|^{2}=\frac{1}{2\pi\hbar\sin(\theta)}$ (35)

This gives our rotated quadrature eigenstate wavefunction of

$\psi(x)=\sqrt{\frac{1}{2\pi\hbar\sin(\theta)}}\exp\left[\frac{-ix(-2X_{\theta}+x\cos(\theta))}{2\hbar\sin(\theta)}\right]$
(36)

##  Appendix C Weak Measurements

This treatment of weak measurements is based on references [14] and [15]. If
we want to take a weak measurement of a system, we must take the system’s
initial quantum state $\ket{\psi}$, and couple it with an ancilla state
$\ket{\varphi}$. This gives us the combined initial system of
$\ket{\Psi}=\ket{\psi}\otimes\ket{\varphi}$. The entire system evolves in time
through the time evolution operator, represented by $U(t)$.

$\ket{\Psi_{t}}=U(t)\ket{\Psi_{0}}$ (37)

We can solve for $U(t)$ by plugging it into the Schrodinger Equation.

$\displaystyle\frac{dU(t)}{dt}=\frac{-i}{\hbar}HU(t)$ (38) $\displaystyle
U(t)=e^{\frac{-itH}{\hbar}}$ (39)

$H=H_{S}\otimes H_{A}$ where $H$ is the Hamiltonian of the whole system,
$H_{S}$ is the Hamiltonian of the quantum state, and $H_{A}$ is the
Hamiltonian of the ancilla state. We can also represent $U(t)$ with a Taylor
series expansion. Assume $t$ is small such that $t^{3}\approx 0$

$\displaystyle U(t)=I\otimes I-itH-\frac{1}{2}t^{2}H^{2}+O(t^{3})$ (40)
$\displaystyle\approx I\otimes I-itH_{S}\otimes
H_{A}-\frac{1}{2}t^{2}H_{S}^{2}\otimes H_{A}^{2}$ (41)

This allows us to rewrite the time evolved combined system as follows,

$\ket{\Psi_{t}}=(I\otimes I-itH_{S}\otimes
H_{A}-\frac{1}{2}t^{2}H_{S}^{2}\otimes H_{A}^{2})\ket{\Psi_{0}}$ (42)

When evaluating the effects of taking a quantum measurement, it’s important to
remember these following properties:

  1. 1.

Quantum measurements can be described by a set of quantum operators
$\\{M_{q}\\}$

  2. 2.

If the initial state of a quantum system is $\ket{\psi}$, then the probability
that result $q$ occurs is: $p(q)=\braket{\psi}{M_{q}^{\dagger}M_{q}}{\psi}$

  3. 3.

the state of the system after the quantum measurement will become:
$\frac{M_{q}\ket{\psi}}{\sqrt{\braket{\psi}{M_{q}^{\dagger}M_{q}}{\psi}}}$

In order for us to properly take a weak measurement of the system, we want to
take a specific projective measurement that only acts on the ancilla state.
Such a measurement can be described by

$E_{q}=I\otimes\ket{q}\bra{q}$ (43)

Projective measurements have the property that when applied to a composite
system $\ket{\psi}$: $p(q)=\braket{\psi}{E_{q}}{\psi}$ and the post-
measurement system becomes

$\frac{E_{q}\ket{\psi}}{\sqrt{p(m)}}$ (44)

Applying this measurement operator to our time evolved state, the post
measurement state becomes:

$\displaystyle\ket{\Psi_{q}}=\frac{E_{q}\ket{\Psi_{t}}}{\sqrt{\bra{\Psi_{t}}{E_{q}\ket{\Psi_{t}}}}}$
(45)
$\displaystyle=\frac{I\braket{\varphi}{q}-itH_{S}\braket{q}{H_{A}}{\varphi}-\frac{1}{2}t^{2}H_{S}^{2}\braket{q}{H_{A}^{2}}{\varphi}}{\sqrt{\bra{\Psi_{t}}{E_{q}\ket{\Psi_{t}}}}}\ket{\psi}\otimes\ket{q}$
(46)

What we can do now is set

$M_{q}:=I\braket{\varphi}{q}-itH_{S}\braket{q}{H_{A}}{\varphi}-\frac{1}{2}t^{2}H_{S}^{2}\braket{q}{H_{A}^{2}}{\varphi}$
(47)

where $M_{q}$ is called a Kraus operator. Returning back to deriving the weak
measurement, we can describe our time evolved state with our Kraus operator
below

$\ket{\Psi_{q}}=\frac{E_{q}\ket{\Psi_{t}}}{\sqrt{\bra{\Psi_{t}}{E_{q}\ket{\Psi_{t}}}}}=\frac{M_{k}\ket{\psi}}{\sqrt{\bra{\psi}M_{k}^{\dagger}M_{k}\ket{\psi}}}\otimes\ket{\varphi}$
(48)

Note that the above postmeasurement state is a tensor product state, and
therefore we may consider the state of the system alone, which is

$\ket{\psi_{q}}=\frac{M_{k}\ket{\psi}}{\sqrt{\bra{\psi}M_{k}^{\dagger}M_{k}\ket{\psi}}}.$
(49)

By using the unitary evolution of the joint Hilbert space, we see that
projective measurements can satisfy the properties of quantum measurements as
we’ve previously established.

We use a Krauss operator of the form

$K_{\theta}=k\int_{-\infty}^{\infty}dX_{\theta}e^{-(X_{\theta}-\mu)^{2}/w^{2}}\ket{X_{\theta}}\bra{X_{\theta}},$
(50)

where $k$ is a normalization constant that will not appear in the
postmeasurement state. We apply the resolution of identity,

$\mathbb{I}=\int dx\ket{x}\bra{x}$ (51)

To represent the Kraus operator in the position basis:

$\braket{x}{K_{\theta}}{x^{\prime}}=k\int_{-\infty}^{\infty}dX_{\theta}e^{-(X_{\theta}-\mu)^{2}/w^{2}}\braket{x}{X_{\theta}}\braket{X_{\theta}}{x^{\prime}}.$
(52)

From 36 we can express this as,

$\displaystyle\braket{x}{K_{\theta}}{x^{\prime}}=\frac{k}{2\pi\hbar\sin\theta}\int_{-\infty}^{\infty}dX_{\theta}e^{-(X_{\theta}-\mu)^{2}/w^{2}}\exp\left(-\frac{i}{2\hbar}(x^{2}-x^{\prime
2})\cot(\theta)+\frac{i}{\hbar}(x-x^{\prime})X_{\theta}\csc(\theta)\right)$
(53)
$\displaystyle=\frac{k}{2\pi\hbar\sin\theta}w\sqrt{\pi}\exp\left(\frac{1}{4\hbar^{2}}(x-x^{\prime})\csc(\theta)[4i\mu\hbar-2i(x+x^{\prime})\hbar\cos(\theta)+w^{2}(x^{\prime}-x)\csc(\theta)]\right)$
(54)

Kraus operators are useful in scenarios such that if a coupled or joined
system undergoes unitary evolution, we can use Kraus operators to describe how
a specific subset of the system evolves in time. For example, if we take an
initial system $\ket{\psi}\otimes\ket{\varphi}$, it will evolve as follows

$\ket{\psi}\otimes\ket{\varphi}\rightarrow\frac{M_{k}\ket{\psi}}{\sqrt{\bra{\psi}M_{k}^{\dagger}M_{k}\ket{\psi}}}\otimes\ket{\varphi}$
(55)

If we now want to analyze just $\ket{\psi}$, we can represent the initial
state through density matrices.

$\ket{\psi}\bra{\psi}\otimes\ket{\varphi}\bra{\varphi}\rightarrow\sum_{k,l}M_{k}\ket{\psi}\bra{\psi}M_{l}^{\dagger}\otimes\ket{\varphi_{k}}\bra{\varphi_{l}}$
(56)

By performing a partial trace with respect to $\varphi$,

$\displaystyle\ket{\psi}\bra{\psi}\rightarrow\sum_{k,l}M_{k}\ket{\psi}\bra{\psi}M_{l}^{\dagger}\braket{\varphi_{l}}{\varphi_{k}}$
(57) $\displaystyle=\sum_{k}M_{k}\ket{\psi}\bra{\psi}M_{k}^{\dagger}$ (58)

Unlike the combined system which evolves under unitary transformation, a
subsystem evolution can be described as

$\rho\rightarrow\sum_{k}M_{k}\rho M_{k}^{\dagger}$ (59)


# Unsafe Impedance: Safe Languages and Safe by Design Software

Lee Barney  Brigham Young University-Idaho, Rexburg, USA
<EMAIL_ADDRESS>Adolfo Neto  Universidade Tecnológica Federal do Paraná,
Curitiba, Brazil
<EMAIL_ADDRESS>
###### Abstract

In December 2023, security agencies from five countries in North America,
Europe, and the south Pacific produced a document encouraging senior
executives in all software producing organizations to take responsibility for
and oversight of the security of the software their organizations produce. In
February 2024, the White House released a cybersecurity outline, highlighting
the December document. In this work we review the safe languages listed in
these documents, and compare the safety of those languages with Erlang and
Elixir, two BEAM languages.

These security agencies’ declaration of some languages as safe is necessary
but insufficient to make wise decisions regarding what language to use when
creating code. We propose an additional way of looking at languages and the
ease with which unsafe code can be written and used. We call this new
perspective unsafe impedance. We then go on to use unsafe impedance to examine
nine languages that are considered to be safe. Finally, we suggest that
business processes include what we refer to as an Unsafe Acceptance Process.
This Unsafe Acceptance Process can be used as part of the memory safe roadmaps
suggested by these agencies. Unsafe Acceptance Processes can aid organizations
in their production of safe by design software.

Keywords: Memory Safe Languages, Functional Programming, Secure By Design,
Secure By Default

##  1 Introduction

Computers connected to networks exist in a dangerous space. From viruses to
bots [15], bad actors are constantly looking for weaknesses they can exploit.
In response to this, a group of national security agencies stated that C-Suite
executives have a responsibility along with technical experts to reduce the
attack surface of software over which they have responsibility [11]. The
proposal they make is to migrate systems from being written in what they refer
to as memory unsafe languages to Memory Safe Languages (MSLs).

In their mitigations, these agencies state,

“Even the most experienced developers write bugs that can introduce
significant vulnerabilities. Training should be a bridge while an organization
implements more robust technical controls, such as memory safe languages.”
[11]

They also suggest several other activities, from implementing and enforcing
coding guidelines to hardware changes, that may mitigate memory based Common
Vulnerability and Exposure (CVE) Types when using memory unsafe languages. All
of this is done as a preamble to the major suggestions of the publication, the
use of and transition to MSLs.

As part of a move to a more secure future, these agencies urge all software
manufacturers, not just those that sell or give away software, to produce and
publish “memory safe roadmaps” indicating how they are going to take ownership
of the “security outcomes” [11] of their software and develop secure products.
All of this to promulgate understanding amongst all producers of software that
“the software industry needs more secure products, not more security
products.” [10]

All of the MSLs mentioned in the articles published by these security agencies
allow memory unsafe code to be directly written in the language or loaded from
libraries. If unsafe code is written or loaded to produce a product, the
product is then is written using unsafe code. This implies that moving to MSLs
is necessary but insufficient. Unsafe impedance, as we shall define it, is an
additional way to aid technical experts and C-suite executives to choose
languages and build their memory safe roadmaps. It is also a way to aid
creators of MSLs as they contemplate the design of their new language.

The contributions of this paper are:

  * •

Introduction of the concept of “unsafe impedance” as a novel perspective for
evaluating the safety of programming languages in the context of software
security.

  * •

Review and comparison of safe languages listed in cybersecurity documents from
security agencies with Erlang and Elixir, two BEAM languages.

  * •

Proposal for an Unsafe Acceptance Process (UAP) to enhance software security
by evaluating the necessity and risks associated with incorporating Native
Implemented Functions (NIFs) in Erlang or Elixir applications.

##  2 Secure by Design and Secure by Default

In 2023, thirteen security agencies from various nations around the world
described technology products that are “secure by design” and “secure by
default” [10]. They define secure by design as it relates to technology
products as meaning these products “are built in a way that reasonably
protects against malicious cyber actors successfully gaining access to
devices, data, and connected infrastructure” [10].

These same agencies define secure by default as “products are resilient
against prevalent exploitation techniques out of the box without added charge”
[10].

Considering a programming language as a product, we build upon these
definitions and define secure by default languages.

Languages are secure by default if they are created in a way that protects
against the production of all types of Common Vulnerability and Exposures
(CVEs).

We will focus our assessments of languages in regard to being secure by
default with regard to the languages’ ability to create memory CVEs. If a
language is not secure by default, we define it to be unsecure by default.

While all categorization schemes are flawed, we categorize memory CVEs into
spacial and temporal groupings. Spacial memory CVEs being those where memory
locations and their use cause vulnerabilities and exposures and temporal
memory CVEs being those where time differences cause memory vulnerabilities
and exposures.

Table 1: Examples of Spacial and Temporal Memory CVEs Spacial Memory CVEs |  Temporal Memory CVEs
---|---
Buffer overflow [22], |  Use after free [29],
Buffer underflow [17], |  Double free [8],
Array index out-of-bounds [11], |  Dangling pointers [8],
Pointer arithmetic errors [6], |  Memory leaks [24],
Uninitialized memory reads [7] |  Data race conditions [2]

The CVEs in Table 1 and their mitigations are commonly taught in undergraduate
computer science courses, and commonly dealt with when hardening software
against attack.

##  3 Memory Safe Languages and Unsafe Code

In their December 2023 report [11], eight security agencies list six languages
as being memory safe, C#, Go, Java, Python, Rust, and Swift. However, none of
these languages are secure by default. Each of these languages, regardless of
their safety declarations, allow unsafe code to be written and used within the
languages’ safe code. It is true, however, that each language has its own
requirements that are enforced when unsafe code is used.

We define the difficulty experienced by programmers when when complying with
these requirements as unsafe impedance. Choosing languages with a high unsafe
impedance as part of the product design makes it easier to claim that the
product is secure by design.

For each language listed in the December 2023 report, we give one or more
examples of how to use unsafe code. The examples are not intended to indicate
how to safely use unsafe code in that language. Neither do we claim these code
snippets to be common uses of unsafe code in these languages since the common
uses of unsafe code in these languages vary widely. The purpose of these code
snippets is to allow the reader to assess the amount of unsafe impedance
programmers in each language experience.

Also, we are not implying that any programmer or engineer would purposefully
write the code in these snippets.

We define languages as having no unsafe impedance when they have no
syntactical or other impediments to writing unsafe code. Commonly known
examples of this language grouping are C and C++. Also, these two languages
are unsecure by default.

Languages that have few syntactical or other impediments to writing unsafe
code we define as having low unsafe impedance.

Languages that have many syntactical or other impediments to writing unsafe
code we define as having high unsafe impedance.

Languages that do not allow any writing, loading, or use of unsafe code we
define as having infinite unsafe impedance. At this time we offer no rubric to
rank languages with regards to unsafe impedance.

###  3.1 C#

The C# [19] language uses a static method of the Marshall class to allocate an
unsafe array of specified types, int in the snippet below. Notice that
Marshal.AllocHGlobal does not initialize the allocated memory. Any old data
stored in the memory remains. This can cause an uninitialized memory read
spacial memory issue unless the applications’ programmers are sufficiently
experienced so that they are aware of the need to write extra code to
initialize the memory with some set of default values.

Additionally, there is no verbiage or any other indicator stating that this
code, and code using the results of this code, are unsafe. Instead, the
programmers creating this code and those who latter read and debug this code
are required to gather the knowledge that this code is unsafe from external
sources.

⬇

IntPtr pointer = Marshal.AllocHGlobal(5 * sizeof(int));

When memory is allocated using Marshal.AllocHGlobal, it is required of the
programmers to use the unsafe static method, Marshal.FreeHGlobal (see code
snippet below). If this function is called at the wrong time, the application
will experience temporal memory issues such as a dangling pointers, use after
free, and double free. if the programmers fail to call this function in an
appropriate location in their codebase, the memory leak temporal memory issue
is created. In non-simple applications it can be difficult for programmers to
know the correct or even a good location to call Marshal.FreeHGlobal.

⬇

Marshal.FreeHGlobal(pointer);

In addition to the allocate and free issues already described, unsafe pointers
can be created, manipulated, and possibly misused. For these reasons, we
classify C# as being unsecure by default.

Also, C# allows programmers to execute unsafe code from within their safe code
with no syntactical or other indication that the code they are writing is
unsafe. For this reason, we would categorize C# as having no unsafe impedance.

###  3.2 Go

In Go [13], an unsafe pointer can be created with no visual indicator that the
pointer is unsafe.

⬇

var ptrToUint32 *uint32 = nil

fmt.Println(“Value:”, *ptrToUint32)

As in C, any nil pointer in Go can be dereferenced causing undefined behavior.
Since Go allows the creation, manipulation, and possible misuse of pointers,
we classify Go as unsecure by default.

It is true that users of the Go language can choose to include the name of the
unsafe package from Go’s standard library in their code. This is a visual
indicator that the result is unsafe to use.

⬇

var num uint32 = 200

var ptrToUint32 *uint32 = (*uint32)(unsafe.Pointer(&num))

*ptrToUint32 = 300

However, the use of this unsafe indicator is not required.

⬇

var num uint32 = 200

var ptrToUint32 *uint32 = &num

*ptrToUint32 = 300

There is no requirement enforced by the Go language’s syntax to indicate that
a variable is unsafe. For programmers with limited understanding of unsafe
code’s behaviors, this lack of visual indicators can lead to security
vulnerabilities. For this reason we would categorize Go as having low unsafe
impedance.

###  3.3 Java

In Java [26], any library that can be accessed using a C-style header can be
loaded and run via Java Native Interface (JNI) functions. There are no
constraints on what unsafe code can do in those non-Java native functions.
Anything that is unsafe in that library becomes a hidden unsafe behavior in
the encapsulating Java code which can then be used in any number of places in
the Java application.

Here is the Java side of the JNI relationship of a simple function that adds
two ints.

⬇

public class AdditionExample {

// Declare the native method

public native int add(int x, int y);

// Load the native library

static {

System.loadLibrary(“addition”);

}

}

Notice there is no explicit visual indicator that unsafe code may be executed.
The native keyword is insufficient in that a novice reading the code is not
directly told the code may be unsafe.

While it is true that several steps are required to complete the library, the
impedance generated by these steps is reduced by the Java system providing
tools to make it easier to execute unsafe JNI functions. For this reason, we
also are categorizing JNI interactions as having a low unsafe impedance.

Foreign Function and Memory (FFM) has been introduced as part of Project
Panama [21] and is scheduled for release as part of Java 22. FFM allows direct
direct memory manipulation and is designed to replace JNI. Based on the FFM
documentation, FFM uses sandboxes, referred to as arenas, to try to contain
and constrain the behaviors of unsafe code executed via the FFM API. In a
presentation regarding FFM, it was stated that FFM attempts to “find a
balance” [9] between safety and flexibility.

The lack of visual unsafe cues in code examples using FFM and the balance
between safety and ease of use lead us to categorize this type of Java code as
having a low unsafe impedance. We also categorize Java as being unsecure by
default because of the safety/flexibility tradeoff of FFM.

###  3.4 Python

Python [23] programmers can use the ctypes library to interact with
dynamically loaded libraries. These libraries can be written in any language
that can produce libraries “which export functions using the standard cdecl
calling convention” [16]. This includes languages such as C, Rust, and Swift.

Compilation and testing of these libraries is done external to the Python
language and its standard toolset. There are non-standard toolsets designed to
ease the creation and integration of these compiled libraries.

When a Python application loads a dynamically linked library using
ctypes.CDLL, the library uses the memory space of the Python REPL. This gives
any security vulnerability access to any data and code in the REPL’s memory
space. This means there is no additional safety for code and data run in the
REPL compared to if the code were written in the language of the library. It
is true that if the library were loaded by an additional Python REPL, the new
REPL’s memory space would only include the data used and created by the loaded
library. However, this does not provide any additional safety.

Notice that the use of the dynamically loaded library in the example below
does not include any direct indicators that the code being used is unsafe.

⬇

import ctypes

libc = ctypes.CDLL(’libc.dylib’)

libc.malloc.argtypes = [ctypes.c_size_t]

libc.malloc.restype = ctypes.c_void_p

libc.free.argtypes = [ctypes.c_void_p]

num_elements = 10

element_size = ctypes.sizeof(ctypes.c_int)

array_ptr = libc.malloc(num_elements * element_size)

Python’s wrapping of unsafe arrays in Python types for access and modification
does add some security when manipulating them within Python. However, this
does not preclude their misuse within the library itself. Untrustworthy actors
could still leverage weaknesses in the library.

Because Python requires unsafe code to be compiled outside of its language,
runtime, and tools, we claim Python has a high unsafe impedance. This,
however, is tempered by the lack of indicators for unaware and unknowledgeable
programmers or engineers that the code being executed is unsafe.

A version of Python with an infinite unsafe impedance could be created. It
would require that no externally compiled code would be allowed to be loaded.
This version of Python would, unfortunately, be unavailable for use by the
machine learning community since a great deal of the code used by Python
machine learning modules is found in dynamically loaded libraries written in
unsafe languages.

We do categorize Python as a secure by default language as long as no unsafe
code is loaded and used.

###  3.5 Rust

Rust [20] includes the keyword unsafe. It is used along with scope indicators
to specify a block of code where all Rust’s safety rules are ignored by the
compiler. Use of the unsafe keyword and code blocks does not add any
additional safety to the code or the applications. It is strictly there to
indicate to programmers and engineers that CVE’s can be executed in the
blocks.

Therefore, any unsafe behavior such as use-after-free, dangling pointers, and
the other CVEs are purposefully placed inside of these blocks. The intention
is that by localizing places where CVEs can exist, they will be easier to
manage. These unsafe code blocks also are used to leverage code written in
unsafe languages.

It is common to hide the use of unsafe code in Rust by writing functions that
show themselves as being safe and following the compiler’s safety rules yet
those functions contain unsafe code blocks. This is so common that when
discussing using libraries written in unsafe languages, the Rust documentation
states that one of these unsafe libraries “can choose to expose only the safe,
high-level interface and hide the unsafe internal details” [12].

Notice the use of unsafe Rust code in this example. Unsafe behaviors are not
limited to libraries written in other languages. Rust itself eases the
creation of unsafe code through its own syntax.

⬇

use std::alloc::{alloc, dealloc, Layout};

unsafe {

let layout = Layout::new::<u16>();

let ptr = alloc(layout);

}

.

.

.

unsafe {

dealloc(ptr, layout);

}

When a Rust application loads a library, the library shares the same memory
space with the rest of the application. This causes any Rust application that
loads libraries to have the same kind of vulnerabilities as a Python
application with loaded unsafe libraries. Because of this and the inclusion of
Rust syntax for creating unsafe code, we categorize Rust as having low unsafe
impedance. The unsafe keyword and the requirement that the mut keyword be used
for mutable variables would, in our opinion, place Rust in the upper portion
of low unsafe impedance category.

Because of Rust’s ability to create, manipulate, and possibly misuse pointers,
we categorize Rust as being an unsecure by default language.

###  3.6 Swift

When a Swift [3] programmer is considering writing unsafe Swift code, Swift’s
syntax enforces the use of an unsafe indicator. This is found in the names of
the initialization functions for UnsafePointer, UnsafeMutablePointer, and
UnsafeRawPointer. These types map to various C-style pointers and, when
included in Swift code, are often used to increase speed or interact with
libraries in other languages. The Swift documentation states that “Swift
imports any function declared in a C header as a Swift global function” [4].
Swift also enables interactions with C macros [4], structures, and unions [4].

The C header declaration implies that any library written in any language that
can expose its functionality as if it was written in C is interoperable with
Swift. Like Rust and Python, any such library shares the same memory space as
the rest of the Swift application. As with those languages, this opens up the
possibility of bad actors gaining access to data in the application and
executing nefarious code within the Swift portion of the application.

Below is an example of unsafe code written in Swift.

⬇

var pointer = UnsafeMutablePointer<UInt16> .allocate(capacity: count)

.

.

.

pointer.deinitialize(count: count)

pointer.deallocate()

The first line indicates that the pointer created is unsafe. This unsafe code
can be wrapped in Swift code that appears to be safe, hiding unsafe code in
what appears to be safe code. Swift’s use of unsafe in the initialization
functions for unsafe types in our opinion places Swift in the upper portion of
low unsafe impedance category.

Swift’s native ability to create, manipulate, and possibly misuse pointers
causes us to categorize Swift as an unsecure by default language.

###  3.7 Erlang, Elixir, and other BEAM Languages

Erlang [5], Elixir [25], and other programming languages run on the BEAM
virtual machine [28] which is often referred to as ’the BEAM’. The BEAM allows
unsafe functions to be loaded into its memory and execution space. Like Rust,
Swift, and the other languages described as safe in the December 2023 report
[11], this means any unsafe, loaded code may be leveraged by bad actors and
give the bad actors access to data in the application and executing nefarious
code within the BEAM.

Because of this, the Erlang documentation includes this warning, “An
erroneously implemented native function can cause a VM internal state
inconsistency, which can cause a crash of the VM, or miscellaneous
misbehaviors of the VM at any point after the call to the native function”
[14].

Unlike Swift, the libraries containing unsafe code, one or more Native
Interface Functions (NIFs), have to include a specific header and deal with
some Erlang terminology. Below is a small example.

⬇

// example_nif.c

#include “erl_nif.h”

static ERL_NIF_TERM create_array(ErlNifEnv* env, int argc, const ERL_NIF_TERM
argv[]) {

// Example function that allocates an array and returns a pointer as an
integer

unsigned int* array = malloc(sizeof(unsigned int) * 10);

if(array == NULL) {

return enif_make_badarg(env);

}

// Just an example: initializing array with arbitrary values

for(int i = 0; i < 10; i++) {

array[i] = i;

}

return enif_make_uint64(env, (ErlNifUInt64)array);

}

static ERL_NIF_TERM free_array(ErlNifEnv* env, int argc, const ERL_NIF_TERM
argv[]) {

// Expects a pointer as an unsigned integer

ErlNifUInt64 ptr;

if(!enif_get_uint64(env, argv[0], &ptr)) {

return enif_make_badarg(env);

}

free((void*)ptr);

return enif_make_atom(env, “ok”);

}

static ErlNifFunc nif_funcs[] = {

{“create_array”, 0, create_array},

{“free_array”, 1, free_array}

};

ERL_NIF_INIT(example_nif, nif_funcs, NULL, NULL, NULL, NULL)

It is possible to use the create_array function from Erlang code without
knowing it is unsafe. BEAM languages such as Erlang and Elixir can hide unsafe
code in much the same way Rust, Swift, and the other languages mentioned do.

The Erlang and Elixir languages are functional, declarative, and “secure by
default” [10]. As part of this secure by default approach, the creators of
Erlang and Elixir have not included the ability to create or use pointers in
the languages, unlike Rust and Swift. Therefore nine of the ten common CVEs
listed in Table 1 are irrelevant assuming no NIFs are used in the creation of
the Erlang library, application, or system. The tenth CVE from Table 1, data
race conditions, cannot occur when using variables since all Erlang and Elixir
variables, tuples, lists, maps, etc. are immutable.

This is not to say that there are no poor programming practices in Erlang and
Elixir that can be problematic. The Erlang Ecosystem Foundation’s Security
Working Group provides guidance for avoiding these poor practices [18]. As an
example, in large, long-running systems, it is possible to exceed the the
number of atoms available since atoms are not garbage collected. The number of
available atoms for a node is determined at startup. The default value is
1,048,576, which can by increased by using the +t flag.

It is unwise to accept large amounts of arbitrary data that is converted to
atoms. When data must be converted to atoms, the application of other
interventions such as using list_to_existing_atom/1 and then using
list_to_atom/1 if list_to_existing_atom/1 fails is indicated. This type of
practice preserves the limited atom table resource.

The awkwardness of the creation of NIFs, the requirement that they be compiled
outside of the standard build environment, and the inherent safety of Erlang
and Elixir code in our opinion places Erlang and Elixir in the high unsafe
impedance category. We believe it is in the lower end of this category due to
the ability to hide the execution of unsafe code.

We do categorize Erlang and Elixir as a secure by default languages as long as
no unsafe code is loaded and used.

Table 2: The Unsafe Impedance and Security Defaults for Several Languages | Unsafe Impedance
---|---
|  none |  low |  high |  infinite
Secure by Default |  |  |  Python, Erlang, Elixir |
Insecure by Default |  C, C++,C# |  Go, Java, Swift, Rust |  |

##  4 Secure By Design Software Using Erlang and Elixir

To achieve secure by default behavior in an application written using secure
by default languages such as Erlang and Elixir, business processes must be
implemented and enforced that strongly discourage the use of NIFs. We propose
that any group producing software in any safe by default language create what
we refer to as an Unsafe Acceptance Process (UAP). The purpose of any UAP is
to increase unsafe impedance. The UAP must impose a significant barrier to the
loading and use of potentially unsafe code.

We also propose that to be of most use, any UAP must include a required,
measurable proof that only a NIF can solve the problem presented.

We propose this proof should include at least these items in a proposal to
include a NIF in an application:

  1. 1.

a statement that by the lack of a NIF implementation one or more existing
consumers/users of the software are being damaged and how,

  2. 2.

a statement of the security risks any NIF brings, along with a statement of
the potential security risks posed by the NIFs code,

  3. 3.

the source code for the proposed NIF,

  4. 4.

the source code for unit tests, when unit testing is possible, or other
extensive proofs that the NIF exhibits no unsafe behavior for all conceivable
edge cases,

  5. 5.

measured speed increases presented by using the NIF, and

  6. 6.

an alternative solution, if possible, in Erlang or Elixir that improves on the
current solution, but is insufficient.

As part of any UAP developed by software producing organizations, no
programmer or software engineer should be able to independently add
potentially unsafe code to a library, application, or system. The NIF proposal
should be evaluated by technological and business persons responsible for the
software. Such an evaluation must be skeptical, and adverse to the addition of
any NIF in its initial perspective. This implies that the addition of a NIF
must be supported by compelling and overwhelming evidence of its necessity.

In our opinion, if a business process like the one described here is
implemented for Erlang or Elixir applications, the resulting code would fall
into the middle of the high unsafe impedance classification.

##  5 Conclusions

It is possible for any system written in safe languages to use unsafe code and
unwittingly expose the system to attack. For some of the languages described
as safe by United States Cybersecurity and Infrastructure Security Agency, et.
al. [11], the unsafe code can be written in the language itself and hidden.
For other languages declared to be safe, the unsafe code can be written in
other languages and loaded separately. This also hides the unsafe code.

In the past and currently, decisions are and were made to value ease of using
unsafe code. These decisions were made to overcome potential or real speed
restrictions in the languages and for code reuse reasons. Such decisions tend
to encourage the use of unsafe code and encourage programmers and engineers to
overlook potential code safety issues found in unsafe code. Heartbleed in
OpenSSL [27] is an example of reuse of unsafe code causing vulnerability in
large numbers of systems. We question whether these speed and reuse decisions
are still relevant.

In a time of increased and increasing connectivity, increased attacks of
various kinds, and increased size of the code bases being created, it is time
to value safety over speed and reuse. Unintended consequences of unsafe code
are used by intruders to gain unwarranted access to gather data and access or
damage computing systems. To reduce these unintended consequences, secure by
default and an infinite unsafe impedance should be the goal of every language
creator and maintainer. Business practices such as UAPs can not guarantee code
safety, only reduce the probability that unsafe code exists in any software
product.

We also propose that speed improvements can happen within safe code and in
hardware that can mitigate the need for using purposefully written code that
may be unsafe. We also propose that using any secure by default language, such
as Erlang and Elixir, along with business processes that include an Unsafe
Acceptance Process (UAP) aid organizations in producing software that is
secure by design [10]. These applications, however, are not secure by default
since it appears there are no secure by default languages that have infinite
unsafe impedance.

Further research can and should be done to expand the assessment of commonly
used programming languages with regard to being fully secure by default, i.e.
expanding upon the memory CVEs from Table 1 used in our assessment. Further
research should also be done to define a rubric that can be used to rank
languages’ unsafe impedance.

## References

  * [1]
  * Alsharhan et al. [2024] Rahaf Alsharhan, Areej Muheef, Yasmin Al Ibrahim, Afnan Rayyani, and Yasir Alguwaifli. 2024\.  Parallel Technologies with Image Processing Using Inverse Filter.  _Journal of Computer and Communications_ 12, 1 (2024), 110–119.
  * Apple Inc. [2022] Apple Inc. 2022\.  _The Swift Programming Language (Swift 5.7)_.  Apple Inc.  https://books.apple.com/us/book/the-swift-programming-language-swift-5-7/id881256329
  * Apple Inc. [nd] Apple Inc. n.d..  _Using Imported C Functions in Swift_.  https://developer.apple.com/documentation/swift/using-imported-c-functions-in-swift Retrieved April 01, 2024.
  * Armstrong [2007] Joe Armstrong. 2007\.  _Programming Erlang: Software for a Concurrent World_.  Addison-Wesley Professional.
  * Bojanova et al. [2022] Irena Bojanova, Carlos Eduardo Galhardo, and Sara Moshtari. 2022.  Data type bugs taxonomy: Integer overflow, juggling, and pointer arithmetics in spotlight. In _2022 IEEE 29th Annual Software Technology Conference (STC)_. IEEE, 192–205.
  * Bruening and Zhao [2011] Derek Bruening and Qin Zhao. 2011.  Practical memory checking with Dr. Memory. In _International Symposium on Code Generation and Optimization (CGO 2011)_. IEEE, 213–223.
  * Caballero et al. [2012] Juan Caballero, Gustavo Grieco, Mark Marron, and Antonio Nappa. 2012.  Undangle: early detection of dangling pointers in use-after-free and double-free vulnerabilities. In _Proceedings of the 2012 International Symposium on Software Testing and Analysis_. 133–143.
  * Cimadamore [2023] Maurizio Cimadamore. 2023\.  _Project Panama: Foreign Function & Memory API_.  https://youtu.be/kUFysMkMS00?si=GBMMZtRRg5QykGat Presentation at the JVM Language Summit 2023.
  * Cybersecurity and [CISA] Cybersecurity and Infrastructure Security Agency (CISA). 2023\.  _Secure by Design: Shifting the Balance of Cybersecurity Risk_.  https://www.cisa.gov/sites/default/files/2023-10/SecureByDesign_1025_508c.pdf Retrieved June 25, 2024.
  * Cybersecurity et al. [2023] US Cybersecurity et al. 2023\.  _The Case for Memory Safe Roadmaps: Why Both C-Suite Executives and Technical Experts Need to Take Memory Safe Coding Seriously_.  CISA: Cybersecurity and Infrastructure Security Agency.
  * Developers [2021] The Rust Project Developers. 2021\.  _The Rust FFI Omnibus_.  https://doc.rust-lang.org/nomicon/ffi.html Retrieved March 20, 2024.
  * Donovan and Kernighan [2015] Allen Donovan and Brian Kernighan. 2015.  _Go Programming Language_.  Addison-Wesley Professional.
  * Erlang Documentation [2024] Erlang Documentation. 2024\.  _Erlang NIFs (Native Implemented Functions)_.  https://www.erlang.org/doc/man/erl_nif.html Retrieved April 23, 2024.
  * Fedele and Roner [2022] Alessandro Fedele and Cristian Roner. 2022.  Dangerous games: A literature review on cybersecurity investments.  _Journal of Economic Surveys_ 36, 1 (2022), 157–187.
  * Foundation [2023] Python Software Foundation. 2023\.  _ctypes - A foreign function library for Python_.  https://docs.python.org/3/library/ctypes.html Retrieved March 20, 2024.
  * Gil et al. [2018] Ronald Gil, Hamed Okhravi, and Howard Shrobe. 2018\.  There’s a Hole in the Bottom of the C: On the Effectiveness of Allocation Protection. In _2018 IEEE Cybersecurity Development (SecDev)_. IEEE, 102–109.
  * Group [2024] Erlang/OTP Security Working Group. 2024\.  _Secure Coding and Deployment Hardening_.  https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/ Retrieved April 25, 2024.
  * Hejlsberg et al. [2010] Anders Hejlsberg et al. 2010\.  _The C# Programming Language_.  Addison-Wesley Professional.
  * Klabnik and Nichols [2023] Steve Klabnik and Carol Nichols. 2023.  _The Rust Programming Language, 2nd Edition_.  No Starch Press.
  * OpenJDK [nd] OpenJDK. n.d..  _Project Panama_.  https://openjdk.org/projects/panama/ Retrieved March 20, 2024.
  * Piromsopa and Enbody [2006] Krerk Piromsopa and Richard J Enbody. 2006.  Buffer-overflow protection: the theory. In _2006 IEEE International Conference on Electro/Information Technology_. IEEE, 454–458.
  * Summerfield [2009] Mark Summerfield. 2009\.  _Programming in Python 3: A Complete Introduction to the Python Language_.  Addison-Wesley Professional.
  * Sun et al. [2018] Xiaohui Sun, Sihan Xu, Chenkai Guo, Jing Xu, Naipeng Dong, Xiujuan Ji, and Sen Zhang. 2018.  A projection-based approach for memory leak detection. In _2018 IEEE 42nd Annual Computer Software and Applications Conference (COMPSAC)_ , Vol. 2. IEEE, 430–435.
  * Thomas [2018] Dave Thomas. 2018\.  _Programming Elixir $\geq$ 1.6: Functional |>Concurrent |>Pragmatic |>Fun_.  Pragmatic Bookshelf.
  * Ullenboom [2022] Christian Ullenboom. 2022\.  _Java: The Comprehensive Guide to Java Programming for Professionals_.  Rheinwerk Computing.
  * Unknown [2020] Unknown. 2020.  _The Heartbleed Bug_.  https://heartbleed.com Accessed: 2024-07-05.
  * Virding [2013] Robert Virding. 2013\.  _Hitchhiker’s tour of the BEAM_.  https://www.youtube.com/watch?v=_Pwlvy3zz9M Presentation at Erlang Factory SF Bay Area.
  * Yason [2013] Mark Yason. 2013\.  _Use-after-frees: That pointer may be pointing to something bad_.  https://securityintelligence.com/use-after-frees-that-pointer-may-be-pointing-to-something-bad/ Accessed: 2024-03-25.