/* $OpenBSD: ecp_oct.c,v 1.8 2017/01/29 17:49:23 beck Exp $ */ /* Includes code written by Lenka Fibikova * for the OpenSSL project. * Includes code written by Bodo Moeller for the OpenSSL project. */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * Portions of this software developed by SUN MICROSYSTEMS, INC., * and contributed to the OpenSSL project. */ /* $OpenBSD: ec_key.c,v 1.13 2017/01/29 17:49:23 beck Exp $ */ /* * Written by Nils Larsch for the OpenSSL project. */ /* ==================================================================== * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * Portions originally developed by SUN MICROSYSTEMS, INC., and * contributed to the OpenSSL project. */ /* $OpenBSD: ecs_ossl.c,v 1.9 2017/01/29 17:49:23 beck Exp $ */ /* * Written by Nils Larsch for the OpenSSL project */ /* ==================================================================== * Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* $OpenBSD: ech_key.c,v 1.7 2017/01/29 17:49:23 beck Exp $ */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * The Elliptic Curve Public-Key Crypto Library (ECC Code) included * herein is developed by SUN MICROSYSTEMS, INC., and is contributed * to the OpenSSL project. * * The ECC Code is licensed pursuant to the OpenSSL open source * license provided below. * * The ECDH software is originally written by Douglas Stebila of * Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "prx/libSceLibreSsl/include/Api.hpp" #include #include #include #include #include #include #include #include #include #include #include #include "prx/libSceLibreSsl/include/Ec.hpp" #include "prx/libSceLibreSsl/include/Error.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/HostEntropy.hpp" #include "mbedtls/bignum.h" #include "mbedtls/ecdh.h" #include "mbedtls/ecdsa.h" #include "mbedtls/ecp.h" EcGroup::EcGroup(const NamedCurve& named) : curve(named) { mbedtls_ecp_group_init(&group); if (mbedtls_ecp_group_load(&group, named.id) != 0) { mbedtls_ecp_group_free(&group); throw std::runtime_error("EC_GROUP: mbedtls failed to load curve " + std::to_string(named.nid)); } } EcGroup::~EcGroup() { mbedtls_ecp_group_free(&group); } EcPoint::EcPoint(const NamedCurve& named) : curve(named) { mbedtls_ecp_point_init(&point); } EcPoint::~EcPoint() { mbedtls_ecp_point_free(&point); } EcPrivateKey::EcPrivateKey(const NamedCurve& named) : curve(named) { mbedtls_mpi_init(&value); } EcPrivateKey::~EcPrivateKey() { mbedtls_mpi_free(&value); } EcKey::~EcKey() { if (extraData) BN_free_nid_postfix(static_cast(extraData)); delete group; delete publicKey; delete privateKey; } namespace { constexpr NamedCurve NamedCurves[] = { {409, MBEDTLS_ECP_DP_SECP192R1}, {415, MBEDTLS_ECP_DP_SECP256R1}, {711, MBEDTLS_ECP_DP_SECP192K1}, {712, MBEDTLS_ECP_DP_SECP224K1}, {713, MBEDTLS_ECP_DP_SECP224R1}, {714, MBEDTLS_ECP_DP_SECP256K1}, {715, MBEDTLS_ECP_DP_SECP384R1}, {716, MBEDTLS_ECP_DP_SECP521R1}, {928, MBEDTLS_ECP_DP_BP256R1}, {932, MBEDTLS_ECP_DP_BP384R1}, {934, MBEDTLS_ECP_DP_BP512R1}, }; constexpr std::pair CurvesMissingFromMbedtls[] = { {410, 414}, {684, 690}, {693, 696}, {699, 710}, {717, 745}, {749, 750}, {839, 844}, {922, 927}, {929, 931}, {933, 933}, {935, 936}, {943, 944}, }; constexpr int PointConversionCompressed = 2; constexpr int PointConversionUncompressed = 4; constexpr int PointConversionHybrid = 6; constexpr int ErrorLibraryEc = 16; constexpr int ErrorLibraryEcdsa = 42; constexpr int ErrorLibraryEcdh = 43; constexpr int ReasonEcLibrary = 16; constexpr int ReasonMallocFailure = 65; constexpr int ReasonPassedNullParameter = 67; constexpr int EcBufferTooSmall = 100; constexpr int EcInvalidForm = 104; constexpr int EcPointAtInfinity = 106; constexpr int EcPointIsNotOnCurve = 107; constexpr int EcInvalidPrivateKey = 123; constexpr int EcUnknownGroup = 129; constexpr int EcdsaBadSignature = 100; constexpr int EcdsaMissingParameters = 103; constexpr int EcdhNoPrivateValue = 100; constexpr int EcdhPointArithmeticFailure = 101; constexpr int EcdhKdfFailed = 102; constexpr int EcdhKeyTruncation = 104; void Check(int result, const char* function) { if (result != 0) throw std::runtime_error(std::string(function) + ": mbedtls error " + std::to_string(result)); } int HostRandom(void*, unsigned char* buffer, std::size_t size) { HostEntropy_nid_no_patch(buffer, size); return 0; } struct Mpi { Mpi() { mbedtls_mpi_init(&value); } ~Mpi() { mbedtls_mpi_free(&value); } Mpi(const Mpi&) = delete; Mpi& operator=(const Mpi&) = delete; mbedtls_mpi value; }; struct Point { Point() { mbedtls_ecp_point_init(&value); } ~Point() { mbedtls_ecp_point_free(&value); } Point(const Point&) = delete; Point& operator=(const Point&) = delete; mbedtls_ecp_point value; }; std::unique_ptr NewGroup(int nid) { for (const NamedCurve& curve : NamedCurves) { if (curve.nid == nid) return std::make_unique(curve); } for (const auto& [first, last] : CurvesMissingFromMbedtls) { if (nid >= first && nid <= last) NotImplemented_nid_no_patch("EC_GROUP_new_by_curve_name: a LibreSSL curve that mbedtls does not provide"); } if (nid > 0) LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcUnknownGroup, __FILE__, __LINE__); return nullptr; } int DerLengthSize(int length) { int size = 1; if (length > 127) { for (; length > 0; length >>= 8) ++size; } return size; } void RequireSameCurve(const EcGroup& group, const NamedCurve& curve, const char* what) { if (group.curve.nid != curve.nid) NotImplemented_nid_no_patch(what); } bool AtInfinity(const mbedtls_ecp_point& point) { return mbedtls_ecp_is_zero(const_cast(&point)) == 1; } std::size_t FieldSize(const EcGroup& group) { return mbedtls_mpi_size(&group.group.P); } std::vector EncodeUncompressed(const EcGroup& group, const mbedtls_ecp_point& point) { std::vector out(1 + 2 * FieldSize(group)); std::size_t size = 0; Check(mbedtls_ecp_point_write_binary(&group.group, &point, MBEDTLS_ECP_PF_UNCOMPRESSED, &size, out.data(), out.size()), "EC point encoding"); out.resize(size); return out; } void AppendDerLength(std::vector& out, std::size_t length) { if (length < 128) { out.push_back(static_cast(length)); return; } unsigned char bytes[sizeof(length)]; std::size_t count = 0; for (; length > 0; length >>= 8) bytes[count++] = static_cast(length); out.push_back(static_cast(0x80 | count)); while (count > 0) out.push_back(bytes[--count]); } void AppendDerInteger(std::vector& out, const mbedtls_mpi& value) { const std::size_t size = mbedtls_mpi_bitlen(&value) / 8 + 1; out.push_back(0x02); AppendDerLength(out, size); out.resize(out.size() + size); Check(mbedtls_mpi_write_binary(&value, out.data() + out.size() - size, size), "ECDSA signature encoding"); } std::vector EncodeSignature(const mbedtls_mpi& r, const mbedtls_mpi& s) { std::vector integers; AppendDerInteger(integers, r); AppendDerInteger(integers, s); std::vector out{0x30}; AppendDerLength(out, integers.size()); out.insert(out.end(), integers.begin(), integers.end()); return out; } struct DerBytes { const unsigned char* data = nullptr; std::size_t size = 0; }; bool ReadDerElement(const unsigned char*& cursor, const unsigned char* end, unsigned char tag, DerBytes& content) { if (end - cursor < 2 || cursor[0] != tag) return false; std::size_t length = cursor[1]; cursor += 2; if (length & 0x80) { const std::size_t count = length & 0x7f; if (count == 0 || count > sizeof(int) || static_cast(end - cursor) < count || cursor[0] == 0) return false; length = 0; for (std::size_t i = 0; i < count; ++i) length = (length << 8) | *cursor++; if (length < 128) return false; } if (static_cast(end - cursor) < length) return false; content = {cursor, length}; cursor += length; return true; } bool ReadDerInteger(const unsigned char*& cursor, const unsigned char* end, DerBytes& magnitude) { if (!ReadDerElement(cursor, end, 0x02, magnitude) || magnitude.size == 0 || (magnitude.data[0] & 0x80)) return false; if (magnitude.data[0] == 0) { if (magnitude.size > 1 && !(magnitude.data[1] & 0x80)) return false; ++magnitude.data; --magnitude.size; } return true; } bool DecodeSignature(const unsigned char* signature, int length, DerBytes& r, DerBytes& s) { const unsigned char* cursor = signature; DerBytes sequence; if (!ReadDerElement(cursor, signature + length, 0x30, sequence) || cursor != signature + length) return false; const unsigned char* const sequenceEnd = sequence.data + sequence.size; return ReadDerInteger(sequence.data, sequenceEnd, r) && ReadDerInteger(sequence.data, sequenceEnd, s) && sequence.data == sequenceEnd; } bool ReadInRange(const DerBytes& magnitude, const mbedtls_mpi& order, mbedtls_mpi& out) { if (magnitude.size > mbedtls_mpi_size(&order)) return false; Check(mbedtls_mpi_read_binary(&out, magnitude.data, magnitude.size), "ECDSA_verify"); return mbedtls_mpi_cmp_int(&out, 0) > 0 && mbedtls_mpi_cmp_mpi(&out, &order) < 0; } void DigestToInteger(const EcGroup& group, const unsigned char* digest, int length, mbedtls_mpi& out) { const std::size_t bits = group.group.nbits; std::size_t used = static_cast(length); if (8 * used > bits) used = (bits + 7) / 8; Check(mbedtls_mpi_read_binary(&out, digest, used), "ECDSA_verify"); if (8 * used > bits) Check(mbedtls_mpi_shift_r(&out, 8 * used - bits), "ECDSA_verify"); } void RequireUsablePublicKey(const EcGroup& group, const EcPoint& point, const char* what) { if (AtInfinity(point.point) || mbedtls_ecp_check_pubkey(&group.group, &point.point) != 0) NotImplemented_nid_no_patch(what); } void ReadScalar(const Bignum& scalar, const mbedtls_mpi& order, mbedtls_mpi& out) { static_assert(std::endian::native == std::endian::little); const std::size_t size = scalar.top > 0 ? static_cast(scalar.top) * sizeof(*scalar.d) : 0; Check(mbedtls_mpi_read_binary_le(&out, reinterpret_cast(scalar.d), size), "EC_POINT_mul"); Check(mbedtls_mpi_mod_mpi(&out, &out, &order), "EC_POINT_mul"); if (scalar.neg && mbedtls_mpi_cmp_int(&out, 0) != 0) Check(mbedtls_mpi_sub_mpi(&out, &order, &out), "EC_POINT_mul"); } } extern "C" { EcGroup* APS5_VABI EC_GROUP_new_by_curve_name_nid_postfix(int nid) { return NewGroup(nid).release(); } void APS5_VABI EC_GROUP_free_nid_postfix(EcGroup* group) { delete group; } int APS5_VABI EC_GROUP_get_degree_nid_postfix(const EcGroup* group) { if (group == nullptr) APS5_INVALID_ARG_EX; return static_cast(group->group.pbits); } EcPoint* APS5_VABI EC_POINT_new_nid_postfix(const EcGroup* group) { if (group == nullptr) return nullptr; return new EcPoint(group->curve); } void APS5_VABI EC_POINT_free_nid_postfix(EcPoint* point) { delete point; } std::size_t APS5_VABI EC_POINT_point2oct_nid_postfix(const EcGroup* group, const EcPoint* point, int form, unsigned char* buffer, std::size_t length, void*) { if (group == nullptr || point == nullptr) APS5_INVALID_ARG_EX; RequireSameCurve(*group, point->curve, "EC_POINT_point2oct: a point of another curve"); if (form != PointConversionCompressed && form != PointConversionUncompressed && form != PointConversionHybrid) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcInvalidForm, __FILE__, __LINE__); return 0; } const mbedtls_ecp_point& value = point->point; if (AtInfinity(value)) { if (buffer != nullptr) { if (length < 1) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcBufferTooSmall, __FILE__, __LINE__); return 0; } buffer[0] = 0; } return 1; } const std::size_t fieldSize = FieldSize(*group); const std::size_t size = form == PointConversionCompressed ? 1 + fieldSize : 1 + 2 * fieldSize; if (buffer == nullptr) return size; if (length < size) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcBufferTooSmall, __FILE__, __LINE__); return 0; } const std::vector uncompressed = EncodeUncompressed(*group, value); buffer[0] = static_cast(form != PointConversionUncompressed && (uncompressed.back() & 1) ? form + 1 : form); std::memcpy(buffer + 1, uncompressed.data() + 1, size - 1); return size; } int APS5_VABI EC_POINT_oct2point_nid_postfix(const EcGroup* group, EcPoint* point, const unsigned char* buffer, std::size_t length, void*) { if (group == nullptr || point == nullptr) APS5_INVALID_ARG_EX; RequireSameCurve(*group, point->curve, "EC_POINT_oct2point: a point of another curve"); if (length == 0) return 0; if (buffer == nullptr) APS5_INVALID_ARG_EX; const int yBit = buffer[0] & 1; const int form = buffer[0] & ~1; if (form != 0 && form != PointConversionCompressed && form != PointConversionUncompressed && form != PointConversionHybrid) return 0; if ((form == 0 || form == PointConversionUncompressed) && yBit) return 0; if (form == 0) { if (length != 1) return 0; Check(mbedtls_ecp_set_zero(&point->point), __func__); return 1; } const std::size_t fieldSize = FieldSize(*group); if (length != (form == PointConversionCompressed ? 1 + fieldSize : 1 + 2 * fieldSize)) return 0; const mbedtls_ecp_group& curve = group->group; Mpi coordinate; Check(mbedtls_mpi_read_binary(&coordinate.value, buffer + 1, fieldSize), __func__); if (mbedtls_mpi_cmp_mpi(&coordinate.value, &curve.P) >= 0) return 0; if (form == PointConversionCompressed) { if (mbedtls_mpi_get_bit(&curve.P, 1) == 0) NotImplemented_nid_no_patch("EC_POINT_oct2point: a compressed point on a curve whose prime is not 3 mod 4"); Point decoded; Check(mbedtls_ecp_point_read_binary(&curve, &decoded.value, buffer, length), __func__); if (mbedtls_ecp_check_pubkey(&curve, &decoded.value) != 0) return 0; Check(mbedtls_ecp_copy(&point->point, &decoded.value), __func__); return 1; } Check(mbedtls_mpi_read_binary(&coordinate.value, buffer + 1 + fieldSize, fieldSize), __func__); if (mbedtls_mpi_cmp_mpi(&coordinate.value, &curve.P) >= 0) return 0; if (form == PointConversionHybrid && yBit != (buffer[length - 1] & 1)) return 0; std::vector uncompressed(buffer, buffer + length); uncompressed[0] = PointConversionUncompressed; Check(mbedtls_ecp_point_read_binary(&curve, &point->point, uncompressed.data(), uncompressed.size()), __func__); return mbedtls_ecp_check_pubkey(&curve, &point->point) == 0 ? 1 : 0; } int APS5_VABI EC_POINT_mul_nid_postfix(const EcGroup* group, EcPoint* result, const Bignum* generatorScalar, const EcPoint* point, const Bignum* pointScalar, BignumContext*) { if (group == nullptr || result == nullptr) APS5_INVALID_ARG_EX; RequireSameCurve(*group, result->curve, "EC_POINT_mul: a result point of another curve"); EcGroup local(group->curve); mbedtls_ecp_group& curve = local.group; Mpi generatorFactor; Mpi pointFactor; if (generatorScalar != nullptr) ReadScalar(*generatorScalar, curve.N, generatorFactor.value); if (point != nullptr && pointScalar != nullptr) { RequireSameCurve(*group, point->curve, "EC_POINT_mul: a point of another curve"); if (!AtInfinity(point->point)) { if (mbedtls_ecp_check_pubkey(&curve, &point->point) != 0) NotImplemented_nid_no_patch("EC_POINT_mul: a point off the curve"); ReadScalar(*pointScalar, curve.N, pointFactor.value); } } const bool withGenerator = mbedtls_mpi_cmp_int(&generatorFactor.value, 0) != 0; const bool withPoint = mbedtls_mpi_cmp_int(&pointFactor.value, 0) != 0; Point sum; if (withGenerator && withPoint) { Check(mbedtls_ecp_muladd(&curve, &sum.value, &generatorFactor.value, &curve.G, &pointFactor.value, &point->point), __func__); } else if (withGenerator) { Check(mbedtls_ecp_mul(&curve, &sum.value, &generatorFactor.value, &curve.G, HostRandom, nullptr), __func__); } else if (withPoint) { Check(mbedtls_ecp_mul(&curve, &sum.value, &pointFactor.value, &point->point, HostRandom, nullptr), __func__); } Check(mbedtls_ecp_copy(&result->point, &sum.value), __func__); return 1; } EcKey* APS5_VABI EC_KEY_new_nid_postfix(void) { return new EcKey; } EcKey* APS5_VABI EC_KEY_new_by_curve_name_nid_postfix(int nid) { std::unique_ptr group = NewGroup(nid); if (!group) return nullptr; EcKey* key = new EcKey; key->group = group.release(); return key; } void APS5_VABI EC_KEY_free_nid_postfix(EcKey* key) { static_assert(std::atomic_ref::required_alignment <= alignof(std::int32_t)); if (!key || std::atomic_ref(key->references).fetch_sub(1) > 1) return; delete key; } const EcGroup* APS5_VABI EC_KEY_get0_group_nid_postfix(const EcKey* key) { if (key == nullptr) APS5_INVALID_ARG_EX; return key->group; } Bignum* APS5_VABI EC_KEY_get0_private_key_nid_postfix(const EcKey* key) { if (key == nullptr) APS5_INVALID_ARG_EX; auto* mutableKey = const_cast(key); if (!mutableKey->privateKey) return nullptr; if (mutableKey->extraData) return static_cast(mutableKey->extraData); const std::size_t size = mbedtls_mpi_size(&mutableKey->privateKey->value); std::vector bytes(size); if (size != 0 && mbedtls_mpi_write_binary(&mutableKey->privateKey->value, bytes.data(), size) != 0) return nullptr; Bignum* number = BN_bin2bn_nid_postfix(bytes.data(), static_cast(bytes.size()), nullptr); mutableKey->extraData = number; return number; } int APS5_VABI EC_KEY_set_private_key_nid_postfix(EcKey* key, const Bignum* privateKey) { if (key == nullptr) APS5_INVALID_ARG_EX; if (key->extraData) { BN_free_nid_postfix(static_cast(key->extraData)); key->extraData = nullptr; } if (!privateKey) { delete key->privateKey; key->privateKey = nullptr; return 1; } if (!key->group) NotImplemented_nid_no_patch("EC_KEY_set_private_key: a key without a group"); const int bits = BN_num_bits_nid_postfix(privateKey); if (bits < 0) return 0; const int length = (bits + 7) / 8; std::vector bytes(static_cast(length)); if (length != 0 && BN_bn2bin_nid_postfix(privateKey, bytes.data()) != length) return 0; auto* replacement = new EcPrivateKey(key->group->curve); if (mbedtls_mpi_read_binary(&replacement->value, bytes.data(), bytes.size()) != 0) { delete replacement; return 0; } delete key->privateKey; key->privateKey = replacement; return 1; } int APS5_VABI EC_KEY_set_group_nid_postfix(EcKey* key, const EcGroup* group) { if (key == nullptr) APS5_INVALID_ARG_EX; if (group) { if (key->publicKey) RequireSameCurve(*group, key->publicKey->curve, "EC_KEY_set_group: a curve other than the one of the key's public key"); if (key->privateKey) RequireSameCurve(*group, key->privateKey->curve, "EC_KEY_set_group: a curve other than the one of the key's private key"); } EcGroup* copy = group ? new EcGroup(group->curve) : nullptr; if (copy) copy->asn1Flag = group->asn1Flag; delete key->group; key->group = copy; return copy ? 1 : 0; } const EcPoint* APS5_VABI EC_KEY_get0_public_key_nid_postfix(const EcKey* key) { if (key == nullptr) APS5_INVALID_ARG_EX; return key->publicKey; } int APS5_VABI EC_KEY_set_public_key_nid_postfix(EcKey* key, const EcPoint* point) { if (key == nullptr) APS5_INVALID_ARG_EX; if (point == nullptr || !key->group) { if (point != nullptr) LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, ReasonPassedNullParameter, __FILE__, __LINE__); delete key->publicKey; key->publicKey = nullptr; return 0; } RequireSameCurve(*key->group, point->curve, "EC_KEY_set_public_key: a point of another curve"); auto copy = std::make_unique(point->curve); Check(mbedtls_ecp_copy(©->point, &point->point), __func__); delete key->publicKey; key->publicKey = copy.release(); return 1; } int APS5_VABI EC_KEY_generate_key_nid_postfix(EcKey* key) { if (key == nullptr || !key->group) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, ReasonPassedNullParameter, __FILE__, __LINE__); return 0; } EcGroup& group = *key->group; if (!key->privateKey) key->privateKey = new EcPrivateKey(group.curve); if (!key->publicKey) key->publicKey = new EcPoint(group.curve); Check(mbedtls_ecp_gen_keypair(&group.group, &key->privateKey->value, &key->publicKey->point, HostRandom, nullptr), __func__); return 1; } int APS5_VABI EC_KEY_check_key_nid_postfix(const EcKey* key) { if (key == nullptr || !key->group || !key->publicKey) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, ReasonPassedNullParameter, __FILE__, __LINE__); return 0; } EcGroup& group = *key->group; const mbedtls_ecp_point& publicKey = key->publicKey->point; if (AtInfinity(publicKey)) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcPointAtInfinity, __FILE__, __LINE__); return 0; } if (mbedtls_ecp_check_pubkey(&group.group, &publicKey) != 0) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcPointIsNotOnCurve, __FILE__, __LINE__); return 0; } if (key->privateKey) { Point product; Check(mbedtls_ecp_mul(&group.group, &product.value, &key->privateKey->value, &group.group.G, HostRandom, nullptr), __func__); if (mbedtls_ecp_point_cmp(&product.value, &publicKey) != 0) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcInvalidPrivateKey, __FILE__, __LINE__); return 0; } } return 1; } int APS5_VABI ECDSA_size_nid_postfix(const EcKey* key) { if (key == nullptr || !key->group) return 0; const int orderBytes = static_cast((mbedtls_mpi_bitlen(&key->group->group.N) + 7) / 8); const int integerSize = 1 + DerLengthSize(orderBytes + 1) + orderBytes + 1; return 1 + DerLengthSize(2 * integerSize) + 2 * integerSize; } int APS5_VABI ECDSA_sign_nid_postfix(int, const unsigned char* digest, int digestLength, unsigned char* signature, unsigned int* signatureLength, EcKey* key) { if (key == nullptr || signatureLength == nullptr) APS5_INVALID_ARG_EX; if (!key->group || !key->privateKey) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdsa, 0xfff, ReasonPassedNullParameter, __FILE__, __LINE__); *signatureLength = 0; return 0; } if (digestLength < 0 || (digest == nullptr && digestLength > 0)) APS5_INVALID_ARG_EX; Mpi r; Mpi s; Check(mbedtls_ecdsa_sign(&key->group->group, &r.value, &s.value, &key->privateKey->value, digest, static_cast(digestLength), HostRandom, nullptr), __func__); const std::vector encoded = EncodeSignature(r.value, s.value); if (signature != nullptr) std::memcpy(signature, encoded.data(), encoded.size()); *signatureLength = static_cast(encoded.size()); return 1; } int APS5_VABI ECDSA_verify_nid_postfix(int, const unsigned char* digest, int digestLength, const unsigned char* signature, int signatureLength, EcKey* key) { if (signatureLength <= 0) return -1; if (signature == nullptr) APS5_INVALID_ARG_EX; DerBytes encodedR; DerBytes encodedS; if (!DecodeSignature(signature, signatureLength, encodedR, encodedS)) return -1; if (key == nullptr) APS5_INVALID_ARG_EX; if (!key->group || !key->publicKey) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdsa, 0xfff, EcdsaMissingParameters, __FILE__, __LINE__); return -1; } EcGroup& group = *key->group; const mbedtls_mpi& order = group.group.N; Mpi r; Mpi s; if (!ReadInRange(encodedR, order, r.value) || !ReadInRange(encodedS, order, s.value)) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdsa, 0xfff, EcdsaBadSignature, __FILE__, __LINE__); return 0; } if (digestLength < 0 || (digest == nullptr && digestLength > 0)) APS5_INVALID_ARG_EX; RequireUsablePublicKey(group, *key->publicKey, "ECDSA_verify: a public key at infinity or off the curve"); Mpi inverse; Mpi message; Mpi u1; Mpi u2; Check(mbedtls_mpi_inv_mod(&inverse.value, &s.value, &order), __func__); DigestToInteger(group, digest, digestLength, message.value); Check(mbedtls_mpi_mul_mpi(&u1.value, &message.value, &inverse.value), __func__); Check(mbedtls_mpi_mod_mpi(&u1.value, &u1.value, &order), __func__); Check(mbedtls_mpi_mul_mpi(&u2.value, &r.value, &inverse.value), __func__); Check(mbedtls_mpi_mod_mpi(&u2.value, &u2.value, &order), __func__); Point sum; Check(mbedtls_ecp_muladd(&group.group, &sum.value, &u1.value, &group.group.G, &u2.value, &key->publicKey->point), __func__); if (AtInfinity(sum.value)) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcPointAtInfinity, __FILE__, __LINE__); LibreSslPutError_nid_no_patch(ErrorLibraryEcdsa, 0xfff, ReasonEcLibrary, __FILE__, __LINE__); return -1; } const std::vector encoded = EncodeUncompressed(group, sum.value); Check(mbedtls_mpi_read_binary(&u1.value, encoded.data() + 1, FieldSize(group)), __func__); Check(mbedtls_mpi_mod_mpi(&u1.value, &u1.value, &order), __func__); return mbedtls_mpi_cmp_mpi(&u1.value, &r.value) == 0 ? 1 : 0; } int APS5_VABI ECDH_compute_key_nid_postfix(void* out, std::size_t outLength, const EcPoint* publicKey, EcKey* key, void* (APS5_VABI* kdf)(const void*, std::size_t, void*, std::size_t*)) { if (key == nullptr) APS5_INVALID_ARG_EX; if (outLength > INT_MAX) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, ReasonMallocFailure, __FILE__, __LINE__); return -1; } if (!key->privateKey) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, EcdhNoPrivateValue, __FILE__, __LINE__); return -1; } if (!key->group) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, ReasonPassedNullParameter, __FILE__, __LINE__); LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, ReasonMallocFailure, __FILE__, __LINE__); return -1; } EcGroup& group = *key->group; if (publicKey == nullptr || AtInfinity(publicKey->point)) { if (publicKey == nullptr || publicKey->curve.nid == group.curve.nid) { LibreSslPutError_nid_no_patch(ErrorLibraryEc, 0xfff, EcPointAtInfinity, __FILE__, __LINE__); LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, EcdhPointArithmeticFailure, __FILE__, __LINE__); } return -1; } RequireSameCurve(group, publicKey->curve, "ECDH_compute_key: a public key of another curve"); RequireUsablePublicKey(group, *publicKey, "ECDH_compute_key: a public key off the curve"); Mpi shared; Check(mbedtls_ecdh_compute_shared(&group.group, &shared.value, &publicKey->point, &key->privateKey->value, HostRandom, nullptr), __func__); const std::size_t size = FieldSize(group); if (kdf == nullptr && outLength < size) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, EcdhKeyTruncation, __FILE__, __LINE__); return -1; } std::vector secret(size); Check(mbedtls_mpi_write_binary(&shared.value, secret.data(), size), __func__); if (kdf != nullptr) { if (kdf(secret.data(), size, out, &outLength) == nullptr) { LibreSslPutError_nid_no_patch(ErrorLibraryEcdh, 0xfff, EcdhKdfFailed, __FILE__, __LINE__); return -1; } return static_cast(outLength); } if (out == nullptr) APS5_INVALID_ARG_EX; std::memset(static_cast(out) + size, 0, outLength - size); std::memcpy(out, secret.data(), size); return static_cast(size); } }