1112158Sdas/*
2112158Sdas * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
3112158Sdas *
4112158Sdas * Licensed under the Apache License 2.0 (the "License").  You may not use
5112158Sdas * this file except in compliance with the License.  You can obtain a copy
6112158Sdas * in the file LICENSE in the source distribution or at
7112158Sdas * https://www.openssl.org/source/license.html
8112158Sdas */
9112158Sdas
10112158Sdas/*
11112158Sdas * A simple ASN.1 DER encoder/decoder for DSA-Sig-Value and ECDSA-Sig-Value.
12112158Sdas *
13112158Sdas * DSA-Sig-Value ::= SEQUENCE {
14112158Sdas *  r  INTEGER,
15112158Sdas *  s  INTEGER
16112158Sdas * }
17112158Sdas *
18112158Sdas * ECDSA-Sig-Value ::= SEQUENCE {
19112158Sdas *  r  INTEGER,
20112158Sdas *  s  INTEGER
21112158Sdas * }
22112158Sdas */
23112158Sdas
24112158Sdas#include <openssl/crypto.h>
25112158Sdas#include <openssl/bn.h>
26112158Sdas#include "crypto/asn1_dsa.h"
27112158Sdas#include "internal/packet.h"
28112158Sdas
29165743Sdas#define ID_SEQUENCE 0x30
30165743Sdas#define ID_INTEGER 0x02
31112158Sdas
32112158Sdas/*
33112158Sdas * Outputs the encoding of the length octets for a DER value with a content
34112158Sdas * length of cont_len bytes to pkt. The maximum supported content length is
35112158Sdas * 65535 (0xffff) bytes.
36112158Sdas *
37112158Sdas * Returns 1 on success or 0 on error.
38112158Sdas */
39112158Sdasint ossl_encode_der_length(WPACKET *pkt, size_t cont_len)
40112158Sdas{
41112158Sdas    if (cont_len > 0xffff)
42112158Sdas        return 0; /* Too large for supported length encodings */
43112158Sdas
44112158Sdas    if (cont_len > 0xff) {
45112158Sdas        if (!WPACKET_put_bytes_u8(pkt, 0x82)
46112158Sdas                || !WPACKET_put_bytes_u16(pkt, cont_len))
47112158Sdas            return 0;
48112158Sdas    } else {
49112158Sdas        if (cont_len > 0x7f
50112158Sdas                && !WPACKET_put_bytes_u8(pkt, 0x81))
51112158Sdas            return 0;
52112158Sdas        if (!WPACKET_put_bytes_u8(pkt, cont_len))
53112158Sdas            return 0;
54112158Sdas    }
55112158Sdas
56187808Sdas    return 1;
57112158Sdas}
58187808Sdas
59112158Sdas/*
60112158Sdas * Outputs the DER encoding of a positive ASN.1 INTEGER to pkt.
61187808Sdas *
62112158Sdas * Results in an error if n is negative or too large.
63112158Sdas *
64112158Sdas * Returns 1 on success or 0 on error.
65112158Sdas */
66187808Sdasint ossl_encode_der_integer(WPACKET *pkt, const BIGNUM *n)
67187808Sdas{
68187808Sdas    unsigned char *bnbytes;
69187808Sdas    size_t cont_len;
70187808Sdas
71112158Sdas    if (BN_is_negative(n))
72112158Sdas        return 0;
73112158Sdas
74112158Sdas    /*
75112158Sdas     * Calculate the ASN.1 INTEGER DER content length for n.
76112158Sdas     * This is the number of whole bytes required to represent n (i.e. rounded
77112158Sdas     * down), plus one.
78112158Sdas     * If n is zero then the content is a single zero byte (length = 1).
79112158Sdas     * If the number of bits of n is a multiple of 8 then an extra zero padding
80112158Sdas     * byte is included to ensure that the value is still treated as positive
81112158Sdas     * in the INTEGER two's complement representation.
82112158Sdas     */
83112158Sdas    cont_len = BN_num_bits(n) / 8 + 1;
84112158Sdas
85112158Sdas    if (!WPACKET_start_sub_packet(pkt)
86112158Sdas            || !WPACKET_put_bytes_u8(pkt, ID_INTEGER)
87112158Sdas            || !ossl_encode_der_length(pkt, cont_len)
88112158Sdas            || !WPACKET_allocate_bytes(pkt, cont_len, &bnbytes)
89112158Sdas            || !WPACKET_close(pkt))
90112158Sdas        return 0;
91112158Sdas
92112158Sdas    if (bnbytes != NULL
93112158Sdas            && BN_bn2binpad(n, bnbytes, (int)cont_len) != (int)cont_len)
94112158Sdas        return 0;
95112158Sdas
96112158Sdas    return 1;
97112158Sdas}
98165743Sdas
99112158Sdas/*
100112158Sdas * Outputs the DER encoding of a DSA-Sig-Value or ECDSA-Sig-Value to pkt. pkt
101112158Sdas * may be initialised with a NULL buffer which enables pkt to be used to
102112158Sdas * calculate how many bytes would be needed.
103112158Sdas *
104112158Sdas * Returns 1 on success or 0 on error.
105112158Sdas */
106112158Sdasint ossl_encode_der_dsa_sig(WPACKET *pkt, const BIGNUM *r, const BIGNUM *s)
107112158Sdas{
108112158Sdas    WPACKET tmppkt, *dummypkt;
109112158Sdas    size_t cont_len;
110112158Sdas    int isnull = WPACKET_is_null_buf(pkt);
111112158Sdas
112112158Sdas    if (!WPACKET_start_sub_packet(pkt))
113112158Sdas        return 0;
114112158Sdas
115112158Sdas    if (!isnull) {
116112158Sdas        if (!WPACKET_init_null(&tmppkt, 0))
117187808Sdas            return 0;
118187808Sdas        dummypkt = &tmppkt;
119112158Sdas    } else {
120        /* If the input packet has a NULL buffer, we don't need a dummy packet */
121        dummypkt = pkt;
122    }
123
124    /* Calculate the content length */
125    if (!ossl_encode_der_integer(dummypkt, r)
126            || !ossl_encode_der_integer(dummypkt, s)
127            || !WPACKET_get_length(dummypkt, &cont_len)
128            || (!isnull && !WPACKET_finish(dummypkt))) {
129        if (!isnull)
130            WPACKET_cleanup(dummypkt);
131        return 0;
132    }
133
134    /* Add the tag and length bytes */
135    if (!WPACKET_put_bytes_u8(pkt, ID_SEQUENCE)
136            || !ossl_encode_der_length(pkt, cont_len)
137               /*
138                * Really encode the integers. We already wrote to the main pkt
139                * if it had a NULL buffer, so don't do it again
140                */
141            || (!isnull && !ossl_encode_der_integer(pkt, r))
142            || (!isnull && !ossl_encode_der_integer(pkt, s))
143            || !WPACKET_close(pkt))
144        return 0;
145
146    return 1;
147}
148
149/*
150 * Decodes the DER length octets in pkt and initialises subpkt with the
151 * following bytes of that length.
152 *
153 * Returns 1 on success or 0 on failure.
154 */
155int ossl_decode_der_length(PACKET *pkt, PACKET *subpkt)
156{
157    unsigned int byte;
158
159    if (!PACKET_get_1(pkt, &byte))
160        return 0;
161
162    if (byte < 0x80)
163        return PACKET_get_sub_packet(pkt, subpkt, (size_t)byte);
164    if (byte == 0x81)
165        return PACKET_get_length_prefixed_1(pkt, subpkt);
166    if (byte == 0x82)
167        return PACKET_get_length_prefixed_2(pkt, subpkt);
168
169    /* Too large, invalid, or not DER. */
170    return 0;
171}
172
173/*
174 * Decodes a single ASN.1 INTEGER value from pkt, which must be DER encoded,
175 * and updates n with the decoded value.
176 *
177 * The BIGNUM, n, must have already been allocated by calling BN_new().
178 * pkt must not be NULL.
179 *
180 * An attempt to consume more than len bytes results in an error.
181 * Returns 1 on success or 0 on error.
182 *
183 * If the PACKET is supposed to only contain a single INTEGER value with no
184 * trailing garbage then it is up to the caller to verify that all bytes
185 * were consumed.
186 */
187int ossl_decode_der_integer(PACKET *pkt, BIGNUM *n)
188{
189    PACKET contpkt, tmppkt;
190    unsigned int tag, tmp;
191
192    /* Check we have an integer and get the content bytes */
193    if (!PACKET_get_1(pkt, &tag)
194            || tag != ID_INTEGER
195            || !ossl_decode_der_length(pkt, &contpkt))
196        return 0;
197
198    /* Peek ahead at the first bytes to check for proper encoding */
199    tmppkt = contpkt;
200    /* The INTEGER must be positive */
201    if (!PACKET_get_1(&tmppkt, &tmp)
202            || (tmp & 0x80) != 0)
203        return 0;
204    /* If there a zero padding byte the next byte must have the msb set */
205    if (PACKET_remaining(&tmppkt) > 0 && tmp == 0) {
206        if (!PACKET_get_1(&tmppkt, &tmp)
207                || (tmp & 0x80) == 0)
208            return 0;
209    }
210
211    if (BN_bin2bn(PACKET_data(&contpkt),
212                  (int)PACKET_remaining(&contpkt), n) == NULL)
213        return 0;
214
215    return 1;
216}
217
218/*
219 * Decodes a single DSA-Sig-Value or ECDSA-Sig-Value from *ppin, which must be
220 * DER encoded, updates r and s with the decoded values, and increments *ppin
221 * past the data that was consumed.
222 *
223 * The BIGNUMs, r and s, must have already been allocated by calls to BN_new().
224 * ppin and *ppin must not be NULL.
225 *
226 * An attempt to consume more than len bytes results in an error.
227 * Returns the number of bytes of input consumed or 0 if an error occurs.
228 *
229 * If the buffer is supposed to only contain a single [EC]DSA-Sig-Value with no
230 * trailing garbage then it is up to the caller to verify that all bytes
231 * were consumed.
232 */
233size_t ossl_decode_der_dsa_sig(BIGNUM *r, BIGNUM *s,
234                               const unsigned char **ppin, size_t len)
235{
236    size_t consumed;
237    PACKET pkt, contpkt;
238    unsigned int tag;
239
240    if (!PACKET_buf_init(&pkt, *ppin, len)
241            || !PACKET_get_1(&pkt, &tag)
242            || tag != ID_SEQUENCE
243            || !ossl_decode_der_length(&pkt, &contpkt)
244            || !ossl_decode_der_integer(&contpkt, r)
245            || !ossl_decode_der_integer(&contpkt, s)
246            || PACKET_remaining(&contpkt) != 0)
247        return 0;
248
249    consumed = PACKET_data(&pkt) - *ppin;
250    *ppin += consumed;
251    return consumed;
252}
253