summaryrefslogtreecommitdiff
path: root/OpenSSL/crypto/pkey.c
blob: b9472ec85af656992ae57c58cc0907d3cab5a5f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
 * pkey.c
 *
 * Copyright (C) AB Strakt
 * Copyright (C) Jean-Paul Calderone
 * See LICENSE for details.
 *
 * Public/rivate key handling code, mostly thin wrappers around OpenSSL.
 * See the file RATIONALE for a short explanation of why this module was written.
 *
 */
#include <Python.h>
#define crypto_MODULE
#include "crypto.h"

/*
 * This is done every time something fails, so turning it into a macro is
 * really nice.
 *
 * Arguments:   None
 * Returns:     Doesn't return
 */
#define FAIL() \
do {                                    \
    exception_from_error_queue(crypto_Error); \
    return NULL;                        \
} while (0)
    

static char crypto_PKey_generate_key_doc[] = "\n\
Generate a key of a given type, with a given number of a bits\n\
\n\
:param type: The key type (TYPE_RSA or TYPE_DSA)\n\
:param bits: The number of bits\n\
:return: None\n\
";

static PyObject *
crypto_PKey_generate_key(crypto_PKeyObj *self, PyObject *args)
{
    int type, bits;
    RSA *rsa;
    DSA *dsa;

    if (!PyArg_ParseTuple(args, "ii:generate_key", &type, &bits))
        return NULL;

    switch (type)
    {
        case crypto_TYPE_RSA:
            if (bits <= 0) {
                PyErr_SetString(PyExc_ValueError, "Invalid number of bits");
                return NULL;
            }
            if ((rsa = RSA_generate_key(bits, 0x10001, NULL, NULL)) == NULL)
                FAIL();
            if (!EVP_PKEY_assign_RSA(self->pkey, rsa))
                FAIL();
	    break;

        case crypto_TYPE_DSA:
            if ((dsa = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL)) == NULL)
                FAIL();
            if (!DSA_generate_key(dsa))
                FAIL();
            if (!EVP_PKEY_assign_DSA(self->pkey, dsa))
                FAIL();
	    break;

        default:
	    PyErr_SetString(crypto_Error, "No such key type");
	    return NULL;

    }
    self->initialized = 1;
    Py_INCREF(Py_None);
    return Py_None;
}

static char crypto_PKey_bits_doc[] = "\n\
Returns the number of bits of the key\n\
\n\
:return: The number of bits of the key.\n\
";

static PyObject *
crypto_PKey_bits(crypto_PKeyObj *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, ":bits"))
        return NULL;

    return PyLong_FromLong(EVP_PKEY_bits(self->pkey));
}

static char crypto_PKey_type_doc[] = "\n\
Returns the type of the key\n\
\n\
:return: The type of the key.\n\
";

static PyObject *
crypto_PKey_type(crypto_PKeyObj *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, ":type"))
        return NULL;

    return PyLong_FromLong(self->pkey->type);
}

static char crypto_PKey_check_doc[] = "\n\
Check the consistency of an RSA private key.\n\
\n\
:return: True if key is consistent.\n\
:raise Error: if the key is inconsistent.\n\
:raise TypeError: if the key is of a type which cannot be checked.\n\
    Only RSA keys can currently be checked.\n\
";

static PyObject *
crypto_PKey_check(crypto_PKeyObj *self, PyObject *args) {
    int r;

    if (!PyArg_ParseTuple(args, ":check")) {
        return NULL;
    }

    if (self->only_public) {
        PyErr_SetString(PyExc_TypeError, "public key only");
        return NULL;
    }

    if (self->pkey->type == EVP_PKEY_RSA) {
        RSA *rsa;
        rsa = EVP_PKEY_get1_RSA(self->pkey);
        r = RSA_check_key(rsa);
        if (r == 1) {
            return PyBool_FromLong(1L);
        } else {
            FAIL();
        }
    } else {
        PyErr_SetString(PyExc_TypeError, "key type unsupported");
        return NULL;
    }
}

/*
 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
 *   {  'name', (PyCFunction)crypto_PKey_name, METH_VARARGS }
 * for convenience
 */
#define ADD_METHOD(name)        \
    { #name, (PyCFunction)crypto_PKey_##name, METH_VARARGS, crypto_PKey_##name##_doc }
static PyMethodDef crypto_PKey_methods[] =
{
    ADD_METHOD(generate_key),
    ADD_METHOD(bits),
    ADD_METHOD(type),
    ADD_METHOD(check),
    { NULL, NULL }
};
#undef ADD_METHOD


/*
 * Constructor for PKey objects, never called by Python code directly
 *
 * Arguments: pkey    - A "real" EVP_PKEY object
 *            dealloc - Boolean value to specify whether the destructor should
 *                      free the "real" EVP_PKEY object
 * Returns:   The newly created PKey object
 */
crypto_PKeyObj *
crypto_PKey_New(EVP_PKEY *pkey, int dealloc)
{
    crypto_PKeyObj *self;

    self = PyObject_New(crypto_PKeyObj, &crypto_PKey_Type);

    if (self == NULL)
        return NULL;

    self->pkey = pkey;
    self->dealloc = dealloc;
    self->only_public = 0;

    /*
     * Heuristic.  Most call-sites pass an initialized EVP_PKEY.  Not
     * necessarily the case that they will, though.  That's part of why this is
     * a hack. -exarkun
     */
    self->initialized = 1;

    return self;
}

static char crypto_PKey_doc[] = "\n\
PKey() -> PKey instance\n\
\n\
Create a new PKey object.\n\
\n\
:return: The PKey object\n\
";
static PyObject*
crypto_PKey_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
    crypto_PKeyObj *self;

    if (!PyArg_ParseTuple(args, ":PKey")) {
        return NULL;
    }

    self = crypto_PKey_New(EVP_PKEY_new(), 1);
    if (self) {
	self->initialized = 0;
    }

    return (PyObject *)self;
}


/*
 * Deallocate the memory used by the PKey object
 *
 * Arguments: self - The PKey object
 * Returns:   None
 */
static void
crypto_PKey_dealloc(crypto_PKeyObj *self)
{
    /* Sometimes we don't have to dealloc the "real" EVP_PKEY pointer ourselves */
    if (self->dealloc)
        EVP_PKEY_free(self->pkey);

    PyObject_Del(self);
}

PyTypeObject crypto_PKey_Type = {
    PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
    "OpenSSL.crypto.PKey",
    sizeof(crypto_PKeyObj),
    0,
    (destructor)crypto_PKey_dealloc,
    NULL, /* print */
    NULL, /* getattr */
    NULL, /* setattr */
    NULL, /* compare */
    NULL, /* repr */
    NULL, /* as_number */
    NULL, /* as_sequence */
    NULL, /* as_mapping */
    NULL, /* hash */
    NULL, /* call */
    NULL, /* str */
    NULL, /* getattro */
    NULL, /* setattro */
    NULL, /* as_buffer */
    Py_TPFLAGS_DEFAULT,
    crypto_PKey_doc, /* doc */
    NULL, /* traverse */
    NULL, /* clear */
    NULL, /* tp_richcompare */
    0, /* tp_weaklistoffset */
    NULL, /* tp_iter */
    NULL, /* tp_iternext */
    crypto_PKey_methods, /* tp_methods */
    NULL, /* tp_members */
    NULL, /* tp_getset */
    NULL, /* tp_base */
    NULL, /* tp_dict */
    NULL, /* tp_descr_get */
    NULL, /* tp_descr_set */
    0, /* tp_dictoffset */
    NULL, /* tp_init */
    NULL, /* tp_alloc */
    crypto_PKey_new, /* tp_new */
};


/*
 * Initialize the PKey part of the crypto sub module
 *
 * Arguments: module - The crypto module
 * Returns:   None
 */
int
init_crypto_pkey(PyObject *module)
{
    if (PyType_Ready(&crypto_PKey_Type) < 0) {
        return 0;
    }

    /* PyModule_AddObject steals a reference.
     */
    Py_INCREF((PyObject *)&crypto_PKey_Type);
    if (PyModule_AddObject(module, "PKey", (PyObject *)&crypto_PKey_Type) != 0) {
        return 0;
    }

    /* PyModule_AddObject steals a reference.
     */
    Py_INCREF((PyObject *)&crypto_PKey_Type);
    if (PyModule_AddObject(module, "PKeyType", (PyObject *)&crypto_PKey_Type) != 0) {
        return 0;
    }

    return 1;
}