~exarkun/pyopenssl/trunk

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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/*
 * x509name.c
 *
 * Copyright (C) AB Strakt
 * Copyright (C) Jean-Paul Calderone
 * See LICENSE for details.
 *
 * X.509 Name handling, mostly thin wrapping.
 * See the file RATIONALE for a short explanation of why this module was written.
 *
 * Reviewed 2001-07-23
 */
#include <Python.h>
#define crypto_MODULE
#include "crypto.h"

static PyMethodDef crypto_X509Name_methods[4];

/*
 * Constructor for X509Name, never called by Python code directly
 *
 * Arguments: name    - A "real" X509_NAME object
 *            dealloc - Boolean value to specify whether the destructor should
 *                      free the "real" X509_NAME object
 * Returns:   The newly created X509Name object
 */
crypto_X509NameObj *
crypto_X509Name_New(X509_NAME *name, int dealloc)
{
    crypto_X509NameObj *self;

    self = PyObject_GC_New(crypto_X509NameObj, &crypto_X509Name_Type);

    if (self == NULL)
        return NULL;

    self->x509_name = name;
    self->dealloc = dealloc;
    self->parent_cert = NULL;

    PyObject_GC_Track(self);
    return self;
}


static char crypto_X509Name_doc[] = "\n\
X509Name(name) -> New X509Name object\n\
\n\
Create a new X509Name, copying the given X509Name instance.\n\
\n\
:param name: An X509Name object to copy\n\
:return: The X509Name object\n\
";

static PyObject *
crypto_X509Name_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
{
    crypto_X509NameObj *name;

    if (!PyArg_ParseTuple(args, "O!:X509Name", &crypto_X509Name_Type, &name)) {
        return NULL;
    }

    return (PyObject *)crypto_X509Name_New(X509_NAME_dup(name->x509_name), 1);
}


/*
 * Return a name string given a X509_NAME object and a name identifier. Used
 * by the getattr function.
 *
 * Arguments: name - The X509_NAME object
 *            nid  - The name identifier
 * Returns:   The name as a Python string object
 */
static int
get_name_by_nid(X509_NAME *name, int nid, char **utf8string)
{
    int entry_idx;
    X509_NAME_ENTRY *entry;
    ASN1_STRING *data;
    int len;

    if ((entry_idx = X509_NAME_get_index_by_NID(name, nid, -1)) == -1)
    {
        return 0;
    }
    entry = X509_NAME_get_entry(name, entry_idx);
    data = X509_NAME_ENTRY_get_data(entry);
    if ((len = ASN1_STRING_to_UTF8((unsigned char **)utf8string, data)) < 0)
    {
        exception_from_error_queue(crypto_Error);
        return -1;
    }

    return len;
}

/*
 * Given a X509_NAME object and a name identifier, set the corresponding
 * attribute to the given string. Used by the setattr function.
 *
 * Arguments: name  - The X509_NAME object
 *            nid   - The name identifier
 *            value - The string to set
 * Returns:   0 for success, -1 on failure
 */
static int
set_name_by_nid(X509_NAME *name, int nid, char *utf8string)
{
    X509_NAME_ENTRY *ne;
    int i, entry_count, temp_nid;

    /* If there's an old entry for this NID, remove it */
    entry_count = X509_NAME_entry_count(name);
    for (i = 0; i < entry_count; i++)
    {
        ne = X509_NAME_get_entry(name, i);
        temp_nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(ne));
        if (temp_nid == nid)
        {
            ne = X509_NAME_delete_entry(name, i);
            X509_NAME_ENTRY_free(ne);
            break;
        }
    }

    /* Add the new entry */
    if (!X509_NAME_add_entry_by_NID(name, nid, MBSTRING_UTF8, 
				    (unsigned char *)utf8string,
				    -1, -1, 0))
    {
        exception_from_error_queue(crypto_Error);
        return -1;
    }
    return 0;
}


/*
 * Find attribute. An X509Name object has the following attributes:
 * countryName (alias C), stateOrProvince (alias ST), locality (alias L),
 * organization (alias O), organizationalUnit (alias OU), commonName (alias
 * CN) and more...
 *
 * Arguments: self - The X509Name object
 *            name - The attribute name
 * Returns:   A Python object for the attribute, or NULL if something went
 *            wrong
 */
static PyObject *
crypto_X509Name_getattro(crypto_X509NameObj *self, PyObject *nameobj)
{
    int nid, len;
    char *utf8string;
    char *name;
#ifdef PY3
    name = PyBytes_AsString(PyUnicode_AsASCIIString(nameobj));
#else
    name = PyBytes_AsString(nameobj);
#endif

    if ((nid = OBJ_txt2nid(name)) == NID_undef) {
        /*
         * This is a bit weird.  OBJ_txt2nid indicated failure, but it seems
         * a lower level function, a2d_ASN1_OBJECT, also feels the need to
         * push something onto the error queue.  If we don't clean that up
         * now, someone else will bump into it later and be quite confused. 
         * See lp#314814.
         */
        flush_error_queue();
        return PyObject_GenericGetAttr((PyObject*)self, nameobj);
    }

    len = get_name_by_nid(self->x509_name, nid, &utf8string);
    if (len < 0)
        return NULL;
    else if (len == 0)
    {
        Py_INCREF(Py_None);
        return Py_None;
    }
    else {
	    PyObject* result = PyUnicode_Decode(utf8string, len, "utf-8", NULL);
	    OPENSSL_free(utf8string);
	    return result;
    }
}

/*
 * Set attribute
 *
 * Arguments: self  - The X509Name object
 *            name  - The attribute name
 *            value - The value to set
 */
static int
crypto_X509Name_setattro(crypto_X509NameObj *self, PyObject *nameobj, PyObject *value)
{
    int nid;
    int result;
    char *buffer;
    char *name;

    if (!PyBytes_CheckExact(nameobj) && !PyUnicode_CheckExact(nameobj)) {
        PyErr_Format(PyExc_TypeError,
                     "attribute name must be string, not '%.200s'",
                     Py_TYPE(nameobj)->tp_name);
        return -1;
    }

#ifdef PY3
    name = PyBytes_AsString(PyUnicode_AsASCIIString(nameobj));
#else
    name = PyBytes_AsString(nameobj);
#endif

    if ((nid = OBJ_txt2nid(name)) == NID_undef)
    {
        /* Just like the case in the getattr function */
        flush_error_queue();
        PyErr_SetString(PyExc_AttributeError, "No such attribute");
        return -1;
    }

    /* Something of a hack to get nice unicode behaviour */
    if (!PyArg_Parse(value, "es:setattr", "utf-8", &buffer))
        return -1;

    result = set_name_by_nid(self->x509_name, nid, buffer);
    PyMem_Free(buffer);
    return result;
}

/*
 * Compare two X509Name structures.
 *
 * Arguments: n - The first X509Name
 *            m - The second X509Name
 * Returns:   <0 if n < m, 0 if n == m and >0 if n > m
 */
static PyObject *
crypto_X509Name_richcompare(PyObject *n, PyObject *m, int op) {
    int result;

    if (!crypto_X509Name_Check(n) || !crypto_X509Name_Check(m)) {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    result = X509_NAME_cmp(
        ((crypto_X509NameObj*)n)->x509_name,
        ((crypto_X509NameObj*)m)->x509_name);

    switch (op) {
    case Py_EQ:
        result = (result == 0);
        break;

    case Py_NE:
        result = (result != 0);
        break;

    case Py_LT:
        result = (result < 0);
        break;

    case Py_LE:
        result = (result <= 0);
        break;

    case Py_GT:
        result = (result > 0);
        break;

    case Py_GE:
        result = (result >= 0);
        break;

    default:
        /* Should be impossible */
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    if (result) {
        Py_INCREF(Py_True);
        return Py_True;
    } else {
        Py_INCREF(Py_False);
        return Py_False;
    }
}

/*
 * String representation of an X509Name
 *
 * Arguments: self - The X509Name object
 * Returns:   A string representation of the object
 */
static PyObject *
crypto_X509Name_repr(crypto_X509NameObj *self)
{
    char tmpbuf[512] = "";
    char realbuf[512+64];

    if (X509_NAME_oneline(self->x509_name, tmpbuf, 512) == NULL)
    {
        exception_from_error_queue(crypto_Error);
        return NULL;
    }
    else
    {
        /* This is safe because tmpbuf is max 512 characters */
        sprintf(realbuf, "<X509Name object '%s'>", tmpbuf);
        return PyText_FromString(realbuf);
    }
}

static char crypto_X509Name_hash_doc[] = "\n\
Return the hash value of this name\n\
\n\
:return: None\n\
";

/*
 * First four bytes of the MD5 digest of the DER form of an X509Name.
 *
 * Arguments: self - The X509Name object
 * Returns:   An integer giving the hash.
 */
static PyObject *
crypto_X509Name_hash(crypto_X509NameObj *self, PyObject* args)
{
    unsigned long hash;

    if (!PyArg_ParseTuple(args, ":hash")) {
        return NULL;
    }
    hash = X509_NAME_hash(self->x509_name);
    return PyLong_FromLong(hash);
}

static char crypto_X509Name_der_doc[] = "\n\
Return the DER encoding of this name\n\
\n\
:return: None\n\
";

/*
 * Arguments: self - The X509Name object
 * Returns:   The DER form of an X509Name.
 */
static PyObject *
crypto_X509Name_der(crypto_X509NameObj *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, ":der")) {
	return NULL;
    }

    i2d_X509_NAME(self->x509_name, 0);
    return PyBytes_FromStringAndSize(self->x509_name->bytes->data,
                                     self->x509_name->bytes->length);
}


static char crypto_X509Name_get_components_doc[] = "\n\
Returns the split-up components of this name.\n\
\n\
:return: List of tuples (name, value).\n\
";

static PyObject *
crypto_X509Name_get_components(crypto_X509NameObj *self, PyObject *args)
{
    int n, i;
    X509_NAME *name = self->x509_name;
    PyObject *list;

    if (!PyArg_ParseTuple(args, ":get_components"))
	return NULL;

    n = X509_NAME_entry_count(name);
    list = PyList_New(n);
    for (i = 0; i < n; i++)
    {
	X509_NAME_ENTRY *ent;
	ASN1_OBJECT *fname;
	ASN1_STRING *fval;
	int nid;
	int l;
	unsigned char *str;
	PyObject *tuple;

	ent = X509_NAME_get_entry(name, i);

	fname = X509_NAME_ENTRY_get_object(ent);
	fval = X509_NAME_ENTRY_get_data(ent);

	l = ASN1_STRING_length(fval);
	str = ASN1_STRING_data(fval);

	nid = OBJ_obj2nid(fname);

	/* printf("fname is %s len=%d str=%s\n", OBJ_nid2sn(nid), l, str); */

	tuple = PyTuple_New(2);
	PyTuple_SetItem(tuple, 0, PyBytes_FromString(OBJ_nid2sn(nid)));
	PyTuple_SetItem(tuple, 1, PyBytes_FromStringAndSize((char *)str, l));

	PyList_SetItem(list, i, tuple);
    }

    return list;
}


/*
 * Call the visitproc on all contained objects.
 *
 * Arguments: self - The Connection object
 *            visit - Function to call
 *            arg - Extra argument to visit
 * Returns:   0 if all goes well, otherwise the return code from the first
 *            call that gave non-zero result.
 */
static int
crypto_X509Name_traverse(crypto_X509NameObj *self, visitproc visit, void *arg)
{
    int ret = 0;

    if (ret == 0 && self->parent_cert != NULL)
        ret = visit(self->parent_cert, arg);
    return ret;
}

/*
 * Decref all contained objects and zero the pointers.
 *
 * Arguments: self - The Connection object
 * Returns:   Always 0.
 */
static int
crypto_X509Name_clear(crypto_X509NameObj *self)
{
    Py_XDECREF(self->parent_cert);
    self->parent_cert = NULL;
    return 0;
}

/*
 * Deallocate the memory used by the X509Name object
 *
 * Arguments: self - The X509Name object
 * Returns:   None
 */
static void
crypto_X509Name_dealloc(crypto_X509NameObj *self)
{
    PyObject_GC_UnTrack(self);
    /* Sometimes we don't have to dealloc this */
    if (self->dealloc)
        X509_NAME_free(self->x509_name);

    crypto_X509Name_clear(self);

    PyObject_GC_Del(self);
}

/*
 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
 *   {  'name', (PyCFunction)crypto_X509_name, METH_VARARGS }
 * for convenience
 */
#define ADD_METHOD(name)        \
    { #name, (PyCFunction)crypto_X509Name_##name, METH_VARARGS, crypto_X509Name_##name##_doc }
static PyMethodDef crypto_X509Name_methods[] =
{
    ADD_METHOD(hash),
    ADD_METHOD(der),
    ADD_METHOD(get_components),
    { NULL, NULL }
};
#undef ADD_METHOD

PyTypeObject crypto_X509Name_Type = {
    PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
    "X509Name",
    sizeof(crypto_X509NameObj),
    0,
    (destructor)crypto_X509Name_dealloc,
    NULL, /* print */
    NULL, /* getattr */
    NULL, /* setattr */
    NULL, /* reserved */
    (reprfunc)crypto_X509Name_repr,
    NULL, /* as_number */
    NULL, /* as_sequence */
    NULL, /* as_mapping */
    NULL, /* hash */
    NULL, /* call */
    NULL, /* str */
    (getattrofunc)crypto_X509Name_getattro, /* getattro */
    (setattrofunc)crypto_X509Name_setattro, /* setattro */
    NULL, /* as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
    crypto_X509Name_doc, /* tp_doc */
    (traverseproc)crypto_X509Name_traverse, /* tp_traverse */
    (inquiry)crypto_X509Name_clear, /* tp_clear */
    crypto_X509Name_richcompare, /* tp_richcompare */
    0, /* tp_weaklistoffset */
    NULL, /* tp_iter */
    NULL, /* tp_iternext */
    crypto_X509Name_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_X509Name_new, /* tp_new */
};

/*
 * Initialize the X509Name part of the crypto module
 *
 * Arguments: module - The crypto module
 * Returns:   None
 */
int
init_crypto_x509name(PyObject *module)
{
    if (PyType_Ready(&crypto_X509Name_Type) < 0) {
        return 0;
    }

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

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

    return 1;
}