Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / OpenSSL / crypto / x509name.c
1 /*
2  * x509name.c
3  *
4  * Copyright (C) AB Strakt
5  * Copyright (C) Jean-Paul Calderone
6  * See LICENSE for details.
7  *
8  * X.509 Name handling, mostly thin wrapping.
9  * See the file RATIONALE for a short explanation of why this module was written.
10  *
11  * Reviewed 2001-07-23
12  */
13 #include <Python.h>
14 #define crypto_MODULE
15 #include "crypto.h"
16
17 static PyMethodDef crypto_X509Name_methods[4];
18
19 /*
20  * Constructor for X509Name, never called by Python code directly
21  *
22  * Arguments: name    - A "real" X509_NAME object
23  *            dealloc - Boolean value to specify whether the destructor should
24  *                      free the "real" X509_NAME object
25  * Returns:   The newly created X509Name object
26  */
27 crypto_X509NameObj *
28 crypto_X509Name_New(X509_NAME *name, int dealloc)
29 {
30     crypto_X509NameObj *self;
31
32     self = PyObject_GC_New(crypto_X509NameObj, &crypto_X509Name_Type);
33
34     if (self == NULL)
35         return NULL;
36
37     self->x509_name = name;
38     self->dealloc = dealloc;
39     self->parent_cert = NULL;
40
41     PyObject_GC_Track(self);
42     return self;
43 }
44
45
46 static char crypto_X509Name_doc[] = "\n\
47 X509Name(name) -> New X509Name object\n\
48 \n\
49 Create a new X509Name, copying the given X509Name instance.\n\
50 \n\
51 @param name: An X509Name object to copy\n\
52 @return: The X509Name object\n\
53 ";
54
55 static PyObject *
56 crypto_X509Name_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
57 {
58     crypto_X509NameObj *name;
59
60     if (!PyArg_ParseTuple(args, "O!:X509Name", &crypto_X509Name_Type, &name)) {
61         return NULL;
62     }
63
64     return (PyObject *)crypto_X509Name_New(X509_NAME_dup(name->x509_name), 1);
65 }
66
67
68 /*
69  * Return a name string given a X509_NAME object and a name identifier. Used
70  * by the getattr function.
71  *
72  * Arguments: name - The X509_NAME object
73  *            nid  - The name identifier
74  * Returns:   The name as a Python string object
75  */
76 static int
77 get_name_by_nid(X509_NAME *name, int nid, char **utf8string)
78 {
79     int entry_idx;
80     X509_NAME_ENTRY *entry;
81     ASN1_STRING *data;
82     int len;
83
84     if ((entry_idx = X509_NAME_get_index_by_NID(name, nid, -1)) == -1)
85     {
86         return 0;
87     }
88     entry = X509_NAME_get_entry(name, entry_idx);
89     data = X509_NAME_ENTRY_get_data(entry);
90     if ((len = ASN1_STRING_to_UTF8((unsigned char **)utf8string, data)) < 0)
91     {
92         exception_from_error_queue(crypto_Error);
93         return -1;
94     }
95
96     return len;
97 }
98
99 /*
100  * Given a X509_NAME object and a name identifier, set the corresponding
101  * attribute to the given string. Used by the setattr function.
102  *
103  * Arguments: name  - The X509_NAME object
104  *            nid   - The name identifier
105  *            value - The string to set
106  * Returns:   0 for success, -1 on failure
107  */
108 static int
109 set_name_by_nid(X509_NAME *name, int nid, char *utf8string)
110 {
111     X509_NAME_ENTRY *ne;
112     int i, entry_count, temp_nid;
113
114     /* If there's an old entry for this NID, remove it */
115     entry_count = X509_NAME_entry_count(name);
116     for (i = 0; i < entry_count; i++)
117     {
118         ne = X509_NAME_get_entry(name, i);
119         temp_nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(ne));
120         if (temp_nid == nid)
121         {
122             ne = X509_NAME_delete_entry(name, i);
123             X509_NAME_ENTRY_free(ne);
124             break;
125         }
126     }
127
128     /* Add the new entry */
129     if (!X509_NAME_add_entry_by_NID(name, nid, MBSTRING_UTF8, 
130                                     (unsigned char *)utf8string,
131                                     -1, -1, 0))
132     {
133         exception_from_error_queue(crypto_Error);
134         return -1;
135     }
136     return 0;
137 }
138
139
140 /*
141  * Find attribute. An X509Name object has the following attributes:
142  * countryName (alias C), stateOrProvince (alias ST), locality (alias L),
143  * organization (alias O), organizationalUnit (alias OU), commonName (alias
144  * CN) and more...
145  *
146  * Arguments: self - The X509Name object
147  *            name - The attribute name
148  * Returns:   A Python object for the attribute, or NULL if something went
149  *            wrong
150  */
151 static PyObject *
152 crypto_X509Name_getattro(crypto_X509NameObj *self, PyObject *nameobj)
153 {
154     int nid, len;
155     char *utf8string;
156     char *name;
157 #ifdef PY3
158     name = PyBytes_AsString(PyUnicode_AsASCIIString(nameobj));
159 #else
160     name = PyBytes_AsString(nameobj);
161 #endif
162
163     if ((nid = OBJ_txt2nid(name)) == NID_undef) {
164         /*
165          * This is a bit weird.  OBJ_txt2nid indicated failure, but it seems
166          * a lower level function, a2d_ASN1_OBJECT, also feels the need to
167          * push something onto the error queue.  If we don't clean that up
168          * now, someone else will bump into it later and be quite confused. 
169          * See lp#314814.
170          */
171         flush_error_queue();
172         return PyObject_GenericGetAttr((PyObject*)self, nameobj);
173     }
174
175     len = get_name_by_nid(self->x509_name, nid, &utf8string);
176     if (len < 0)
177         return NULL;
178     else if (len == 0)
179     {
180         Py_INCREF(Py_None);
181         return Py_None;
182     }
183     else {
184             PyObject* result = PyUnicode_Decode(utf8string, len, "utf-8", NULL);
185             OPENSSL_free(utf8string);
186             return result;
187     }
188 }
189
190 /*
191  * Set attribute
192  *
193  * Arguments: self  - The X509Name object
194  *            name  - The attribute name
195  *            value - The value to set
196  */
197 static int
198 crypto_X509Name_setattr(crypto_X509NameObj *self, char *name, PyObject *value)
199 {
200     int nid;
201     int result;
202     char *buffer;
203
204     if ((nid = OBJ_txt2nid(name)) == NID_undef)
205     {
206         PyErr_SetString(PyExc_AttributeError, "No such attribute");
207         return -1;
208     }
209
210     /* Something of a hack to get nice unicode behaviour */
211     if (!PyArg_Parse(value, "es:setattr", "utf-8", &buffer))
212         return -1;
213
214     result = set_name_by_nid(self->x509_name, nid, buffer);
215     PyMem_Free(buffer);
216     return result;
217 }
218
219 /*
220  * Compare two X509Name structures.
221  *
222  * Arguments: n - The first X509Name
223  *            m - The second X509Name
224  * Returns:   <0 if n < m, 0 if n == m and >0 if n > m
225  */
226 static PyObject *
227 crypto_X509Name_richcompare(PyObject *n, PyObject *m, int op) {
228     int result;
229
230     if (!crypto_X509Name_Check(n) || !crypto_X509Name_Check(m)) {
231         Py_INCREF(Py_NotImplemented);
232         return Py_NotImplemented;
233     }
234
235     result = X509_NAME_cmp(
236         ((crypto_X509NameObj*)n)->x509_name,
237         ((crypto_X509NameObj*)m)->x509_name);
238
239     switch (op) {
240     case Py_EQ:
241         result = (result == 0);
242         break;
243
244     case Py_NE:
245         result = (result != 0);
246         break;
247
248     case Py_LT:
249         result = (result < 0);
250         break;
251
252     case Py_LE:
253         result = (result <= 0);
254         break;
255
256     case Py_GT:
257         result = (result > 0);
258         break;
259
260     case Py_GE:
261         result = (result >= 0);
262         break;
263
264     default:
265         /* Should be impossible */
266         Py_INCREF(Py_NotImplemented);
267         return Py_NotImplemented;
268     }
269
270     if (result) {
271         Py_INCREF(Py_True);
272         return Py_True;
273     } else {
274         Py_INCREF(Py_False);
275         return Py_False;
276     }
277 }
278
279 /*
280  * String representation of an X509Name
281  *
282  * Arguments: self - The X509Name object
283  * Returns:   A string representation of the object
284  */
285 static PyObject *
286 crypto_X509Name_repr(crypto_X509NameObj *self)
287 {
288     char tmpbuf[512] = "";
289     char realbuf[512+64];
290
291     if (X509_NAME_oneline(self->x509_name, tmpbuf, 512) == NULL)
292     {
293         exception_from_error_queue(crypto_Error);
294         return NULL;
295     }
296     else
297     {
298         /* This is safe because tmpbuf is max 512 characters */
299         sprintf(realbuf, "<X509Name object '%s'>", tmpbuf);
300         return PyText_FromString(realbuf);
301     }
302 }
303
304 static char crypto_X509Name_hash_doc[] = "\n\
305 Return the hash value of this name\n\
306 \n\
307 @return: None\n\
308 ";
309
310 /*
311  * First four bytes of the MD5 digest of the DER form of an X509Name.
312  *
313  * Arguments: self - The X509Name object
314  * Returns:   An integer giving the hash.
315  */
316 static PyObject *
317 crypto_X509Name_hash(crypto_X509NameObj *self, PyObject* args)
318 {
319     unsigned long hash;
320
321     if (!PyArg_ParseTuple(args, ":hash")) {
322         return NULL;
323     }
324     hash = X509_NAME_hash(self->x509_name);
325     return PyLong_FromLong(hash);
326 }
327
328 static char crypto_X509Name_der_doc[] = "\n\
329 Return the DER encoding of this name\n\
330 \n\
331 @return: None\n\
332 ";
333
334 /*
335  * Arguments: self - The X509Name object
336  * Returns:   The DER form of an X509Name.
337  */
338 static PyObject *
339 crypto_X509Name_der(crypto_X509NameObj *self, PyObject *args)
340 {
341     if (!PyArg_ParseTuple(args, ":der")) {
342         return NULL;
343     }
344
345     i2d_X509_NAME(self->x509_name, 0);
346     return PyBytes_FromStringAndSize(self->x509_name->bytes->data,
347                                      self->x509_name->bytes->length);
348 }
349
350
351 static char crypto_X509Name_get_components_doc[] = "\n\
352 Returns the split-up components of this name.\n\
353 \n\
354 @return: List of tuples (name, value).\n\
355 ";
356
357 static PyObject *
358 crypto_X509Name_get_components(crypto_X509NameObj *self, PyObject *args)
359 {
360     int n, i;
361     X509_NAME *name = self->x509_name;
362     PyObject *list;
363
364     if (!PyArg_ParseTuple(args, ":get_components"))
365         return NULL;
366
367     n = X509_NAME_entry_count(name);
368     list = PyList_New(n);
369     for (i = 0; i < n; i++)
370     {
371         X509_NAME_ENTRY *ent;
372         ASN1_OBJECT *fname;
373         ASN1_STRING *fval;
374         int nid;
375         int l;
376         unsigned char *str;
377         PyObject *tuple;
378
379         ent = X509_NAME_get_entry(name, i);
380
381         fname = X509_NAME_ENTRY_get_object(ent);
382         fval = X509_NAME_ENTRY_get_data(ent);
383
384         l = ASN1_STRING_length(fval);
385         str = ASN1_STRING_data(fval);
386
387         nid = OBJ_obj2nid(fname);
388
389         /* printf("fname is %s len=%d str=%s\n", OBJ_nid2sn(nid), l, str); */
390
391         tuple = PyTuple_New(2);
392         PyTuple_SetItem(tuple, 0, PyBytes_FromString(OBJ_nid2sn(nid)));
393         PyTuple_SetItem(tuple, 1, PyBytes_FromStringAndSize((char *)str, l));
394
395         PyList_SetItem(list, i, tuple);
396     }
397
398     return list;
399 }
400
401
402 /*
403  * Call the visitproc on all contained objects.
404  *
405  * Arguments: self - The Connection object
406  *            visit - Function to call
407  *            arg - Extra argument to visit
408  * Returns:   0 if all goes well, otherwise the return code from the first
409  *            call that gave non-zero result.
410  */
411 static int
412 crypto_X509Name_traverse(crypto_X509NameObj *self, visitproc visit, void *arg)
413 {
414     int ret = 0;
415
416     if (ret == 0 && self->parent_cert != NULL)
417         ret = visit(self->parent_cert, arg);
418     return ret;
419 }
420
421 /*
422  * Decref all contained objects and zero the pointers.
423  *
424  * Arguments: self - The Connection object
425  * Returns:   Always 0.
426  */
427 static int
428 crypto_X509Name_clear(crypto_X509NameObj *self)
429 {
430     Py_XDECREF(self->parent_cert);
431     self->parent_cert = NULL;
432     return 0;
433 }
434
435 /*
436  * Deallocate the memory used by the X509Name object
437  *
438  * Arguments: self - The X509Name object
439  * Returns:   None
440  */
441 static void
442 crypto_X509Name_dealloc(crypto_X509NameObj *self)
443 {
444     PyObject_GC_UnTrack(self);
445     /* Sometimes we don't have to dealloc this */
446     if (self->dealloc)
447         X509_NAME_free(self->x509_name);
448
449     crypto_X509Name_clear(self);
450
451     PyObject_GC_Del(self);
452 }
453
454 /*
455  * ADD_METHOD(name) expands to a correct PyMethodDef declaration
456  *   {  'name', (PyCFunction)crypto_X509_name, METH_VARARGS }
457  * for convenience
458  */
459 #define ADD_METHOD(name)        \
460     { #name, (PyCFunction)crypto_X509Name_##name, METH_VARARGS, crypto_X509Name_##name##_doc }
461 static PyMethodDef crypto_X509Name_methods[] =
462 {
463     ADD_METHOD(hash),
464     ADD_METHOD(der),
465     ADD_METHOD(get_components),
466     { NULL, NULL }
467 };
468 #undef ADD_METHOD
469
470 PyTypeObject crypto_X509Name_Type = {
471     PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
472     "X509Name",
473     sizeof(crypto_X509NameObj),
474     0,
475     (destructor)crypto_X509Name_dealloc,
476     NULL, /* print */
477     NULL, /* getattr */
478     (setattrfunc)crypto_X509Name_setattr,
479     NULL, /* reserved */
480     (reprfunc)crypto_X509Name_repr,
481     NULL, /* as_number */
482     NULL, /* as_sequence */
483     NULL, /* as_mapping */
484     NULL, /* hash */
485     NULL, /* call */
486     NULL, /* str */
487     (getattrofunc)crypto_X509Name_getattro, /* getattro */
488     NULL, /* setattro */
489     NULL, /* as_buffer */
490     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
491     crypto_X509Name_doc, /* tp_doc */
492     (traverseproc)crypto_X509Name_traverse, /* tp_traverse */
493     (inquiry)crypto_X509Name_clear, /* tp_clear */
494     crypto_X509Name_richcompare, /* tp_richcompare */
495     0, /* tp_weaklistoffset */
496     NULL, /* tp_iter */
497     NULL, /* tp_iternext */
498     crypto_X509Name_methods, /* tp_methods */
499     NULL, /* tp_members */
500     NULL, /* tp_getset */
501     NULL, /* tp_base */
502     NULL, /* tp_dict */
503     NULL, /* tp_descr_get */
504     NULL, /* tp_descr_set */
505     0, /* tp_dictoffset */
506     NULL, /* tp_init */
507     NULL, /* tp_alloc */
508     crypto_X509Name_new, /* tp_new */
509 };
510
511 /*
512  * Initialize the X509Name part of the crypto module
513  *
514  * Arguments: module - The crypto module
515  * Returns:   None
516  */
517 int
518 init_crypto_x509name(PyObject *module)
519 {
520     if (PyType_Ready(&crypto_X509Name_Type) < 0) {
521         return 0;
522     }
523
524     if (PyModule_AddObject(module, "X509Name", (PyObject *)&crypto_X509Name_Type) != 0) {
525         return 0;
526     }
527
528     if (PyModule_AddObject(module, "X509NameType", (PyObject *)&crypto_X509Name_Type) != 0) {
529         return 0;
530     }
531
532     return 1;
533 }