4 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
8 * Certificate (X.509) handling code, mostly thin wrappers around OpenSSL.
9 * See the file RATIONALE for a short explanation of why this module was written.
19 * X.509 is a standard for digital certificates. See e.g. the OpenSSL homepage
20 * http://www.openssl.org/ for more information
23 static char crypto_X509_get_version_doc[] = "\n\
24 Return version number of the certificate\n\
26 @return: Version number as a Python integer\n\
30 crypto_X509_get_version(crypto_X509Obj *self, PyObject *args)
32 if (!PyArg_ParseTuple(args, ":get_version"))
35 return PyLong_FromLong((long)X509_get_version(self->x509));
38 static char crypto_X509_set_version_doc[] = "\n\
39 Set version number of the certificate\n\
41 @param version: The version number\n\
46 crypto_X509_set_version(crypto_X509Obj *self, PyObject *args)
50 if (!PyArg_ParseTuple(args, "i:set_version", &version))
53 X509_set_version(self->x509, version);
59 static char crypto_X509_get_serial_number_doc[] = "\n\
60 Return serial number of the certificate\n\
62 @return: Serial number as a Python integer\n\
66 crypto_X509_get_serial_number(crypto_X509Obj *self, PyObject *args)
73 if (!PyArg_ParseTuple(args, ":get_serial_number"))
76 asn1_i = X509_get_serialNumber(self->x509);
77 bignum = ASN1_INTEGER_to_BN(asn1_i, NULL);
78 hex = BN_bn2hex(bignum);
79 res = PyLong_FromString(hex, NULL, 16);
85 static char crypto_X509_set_serial_number_doc[] = "\n\
86 Set serial number of the certificate\n\
88 @param serial: The serial number\n\
93 crypto_X509_set_serial_number(crypto_X509Obj *self, PyObject *args)
96 PyObject *serial = NULL;
98 ASN1_INTEGER *asn1_i = NULL;
99 BIGNUM *bignum = NULL;
102 if (!PyArg_ParseTuple(args, "O:set_serial_number", &serial)) {
106 if (!PyOpenSSL_Integer_Check(serial)) {
108 PyExc_TypeError, "serial number must be integer");
112 if ((hex = PyOpenSSL_LongToHex(serial)) == NULL) {
118 PyObject *hexbytes = PyUnicode_AsASCIIString(hex);
125 * BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
126 * it. If bignum is still NULL after this call, then the return value
127 * is actually the result. I hope. -exarkun
129 hexstr = PyBytes_AsString(hex);
130 if (hexstr[1] == 'x') {
131 /* +2 to skip the "0x" */
134 small_serial = BN_hex2bn(&bignum, hexstr);
139 if (bignum == NULL) {
140 if (ASN1_INTEGER_set(X509_get_serialNumber(self->x509), small_serial)) {
141 exception_from_error_queue(crypto_Error);
145 asn1_i = BN_to_ASN1_INTEGER(bignum, NULL);
148 if (asn1_i == NULL) {
149 exception_from_error_queue(crypto_Error);
152 if (!X509_set_serialNumber(self->x509, asn1_i)) {
153 exception_from_error_queue(crypto_Error);
156 ASN1_INTEGER_free(asn1_i);
171 ASN1_INTEGER_free(asn1_i);
176 static char crypto_X509_get_issuer_doc[] = "\n\
177 Create an X509Name object for the issuer of the certificate\n\
179 @return: An X509Name object\n\
183 crypto_X509_get_issuer(crypto_X509Obj *self, PyObject *args)
185 crypto_X509NameObj *pyname;
188 if (!PyArg_ParseTuple(args, ":get_issuer"))
191 name = X509_get_issuer_name(self->x509);
192 pyname = crypto_X509Name_New(name, 0);
195 pyname->parent_cert = (PyObject *)self;
198 return (PyObject *)pyname;
201 static char crypto_X509_set_issuer_doc[] = "\n\
202 Set the issuer of the certificate\n\
204 @param issuer: The issuer name\n\
205 @type issuer: L{X509Name}\n\
210 crypto_X509_set_issuer(crypto_X509Obj *self, PyObject *args)
212 crypto_X509NameObj *issuer;
214 if (!PyArg_ParseTuple(args, "O!:set_issuer", &crypto_X509Name_Type,
218 if (!X509_set_issuer_name(self->x509, issuer->x509_name))
220 exception_from_error_queue(crypto_Error);
228 static char crypto_X509_get_subject_doc[] = "\n\
229 Create an X509Name object for the subject of the certificate\n\
231 @return: An X509Name object\n\
235 crypto_X509_get_subject(crypto_X509Obj *self, PyObject *args)
237 crypto_X509NameObj *pyname;
240 if (!PyArg_ParseTuple(args, ":get_subject"))
243 name = X509_get_subject_name(self->x509);
244 pyname = crypto_X509Name_New(name, 0);
247 pyname->parent_cert = (PyObject *)self;
250 return (PyObject *)pyname;
253 static char crypto_X509_set_subject_doc[] = "\n\
254 Set the subject of the certificate\n\
256 @param subject: The subject name\n\
257 @type subject: L{X509Name}\n\
262 crypto_X509_set_subject(crypto_X509Obj *self, PyObject *args)
264 crypto_X509NameObj *subject;
266 if (!PyArg_ParseTuple(args, "O!:set_subject", &crypto_X509Name_Type,
270 if (!X509_set_subject_name(self->x509, subject->x509_name))
272 exception_from_error_queue(crypto_Error);
280 static char crypto_X509_get_pubkey_doc[] = "\n\
281 Get the public key of the certificate\n\
283 @return: The public key\n\
287 crypto_X509_get_pubkey(crypto_X509Obj *self, PyObject *args)
289 crypto_PKeyObj *crypto_PKey_New(EVP_PKEY *, int);
291 crypto_PKeyObj *py_pkey;
293 if (!PyArg_ParseTuple(args, ":get_pubkey"))
296 if ((pkey = X509_get_pubkey(self->x509)) == NULL)
298 exception_from_error_queue(crypto_Error);
302 py_pkey = crypto_PKey_New(pkey, 1);
303 if (py_pkey != NULL) {
304 py_pkey->only_public = 1;
306 return (PyObject *)py_pkey;
309 static char crypto_X509_set_pubkey_doc[] = "\n\
310 Set the public key of the certificate\n\
312 @param pkey: The public key\n\
317 crypto_X509_set_pubkey(crypto_X509Obj *self, PyObject *args)
319 crypto_PKeyObj *pkey;
321 if (!PyArg_ParseTuple(args, "O!:set_pubkey", &crypto_PKey_Type, &pkey))
324 if (!X509_set_pubkey(self->x509, pkey->pkey))
326 exception_from_error_queue(crypto_Error);
335 _set_asn1_time(char *format, ASN1_TIME* timestamp, PyObject *args)
339 if (!PyArg_ParseTuple(args, format, &when))
342 if (ASN1_GENERALIZEDTIME_set_string(timestamp, when) == 0) {
343 ASN1_GENERALIZEDTIME dummy;
344 dummy.type = V_ASN1_GENERALIZEDTIME;
345 dummy.length = strlen(when);
346 dummy.data = (unsigned char *)when;
347 if (!ASN1_GENERALIZEDTIME_check(&dummy)) {
348 PyErr_SetString(PyExc_ValueError, "Invalid string");
350 PyErr_SetString(PyExc_RuntimeError, "Unknown ASN1_GENERALIZEDTIME_set_string failure");
358 static char crypto_X509_set_notBefore_doc[] = "\n\
359 Set the time stamp for when the certificate starts being valid\n\
361 @param when: A string giving the timestamp, in the format:\n\
364 YYYYMMDDhhmmss+hhmm\n\
365 YYYYMMDDhhmmss-hhmm\n\
371 crypto_X509_set_notBefore(crypto_X509Obj *self, PyObject *args)
373 return _set_asn1_time(
374 BYTESTRING_FMT ":set_notBefore",
375 X509_get_notBefore(self->x509), args);
378 static char crypto_X509_set_notAfter_doc[] = "\n\
379 Set the time stamp for when the certificate stops being valid\n\
381 @param when: A string giving the timestamp, in the format:\n\
384 YYYYMMDDhhmmss+hhmm\n\
385 YYYYMMDDhhmmss-hhmm\n\
391 crypto_X509_set_notAfter(crypto_X509Obj *self, PyObject *args)
393 return _set_asn1_time(
394 BYTESTRING_FMT ":set_notAfter",
395 X509_get_notAfter(self->x509), args);
399 _get_asn1_time(char *format, ASN1_TIME* timestamp, PyObject *args)
401 ASN1_GENERALIZEDTIME *gt_timestamp = NULL;
402 PyObject *py_timestamp = NULL;
404 if (!PyArg_ParseTuple(args, format)) {
409 * http://www.columbia.edu/~ariel/ssleay/asn1-time.html
412 * There must be a way to do this without touching timestamp->data
415 if (timestamp->length == 0) {
418 } else if (timestamp->type == V_ASN1_GENERALIZEDTIME) {
419 return PyBytes_FromString((char *)timestamp->data);
421 ASN1_TIME_to_generalizedtime(timestamp, >_timestamp);
422 if (gt_timestamp == NULL) {
423 exception_from_error_queue(crypto_Error);
426 py_timestamp = PyBytes_FromString((char *)gt_timestamp->data);
427 ASN1_GENERALIZEDTIME_free(gt_timestamp);
433 static char crypto_X509_get_notBefore_doc[] = "\n\
434 Retrieve the time stamp for when the certificate starts being valid\n\
436 @return: A string giving the timestamp, in the format:\n\
439 YYYYMMDDhhmmss+hhmm\n\
440 YYYYMMDDhhmmss-hhmm\n\
441 or None if there is no value set.\n\
445 crypto_X509_get_notBefore(crypto_X509Obj *self, PyObject *args)
448 * X509_get_notBefore returns a borrowed reference.
450 return _get_asn1_time(
451 ":get_notBefore", X509_get_notBefore(self->x509), args);
455 static char crypto_X509_get_notAfter_doc[] = "\n\
456 Retrieve the time stamp for when the certificate stops being valid\n\
458 @return: A string giving the timestamp, in the format:\n\
461 YYYYMMDDhhmmss+hhmm\n\
462 YYYYMMDDhhmmss-hhmm\n\
463 or None if there is no value set.\n\
467 crypto_X509_get_notAfter(crypto_X509Obj *self, PyObject *args)
470 * X509_get_notAfter returns a borrowed reference.
472 return _get_asn1_time(
473 ":get_notAfter", X509_get_notAfter(self->x509), args);
477 static char crypto_X509_gmtime_adj_notBefore_doc[] = "\n\
478 Change the timestamp for when the certificate starts being valid to the current\n\
479 time plus an offset.\n \
481 @param amount: The number of seconds by which to adjust the starting validity\n\
487 crypto_X509_gmtime_adj_notBefore(crypto_X509Obj *self, PyObject *args)
491 if (!PyArg_ParseTuple(args, "l:gmtime_adj_notBefore", &amount))
494 X509_gmtime_adj(X509_get_notBefore(self->x509), amount);
500 static char crypto_X509_gmtime_adj_notAfter_doc[] = "\n\
501 Adjust the time stamp for when the certificate stops being valid\n\
503 @param amount: The number of seconds by which to adjust the ending validity\n\
509 crypto_X509_gmtime_adj_notAfter(crypto_X509Obj *self, PyObject *args)
513 if (!PyArg_ParseTuple(args, "l:gmtime_adj_notAfter", &amount))
516 X509_gmtime_adj(X509_get_notAfter(self->x509), amount);
522 static char crypto_X509_sign_doc[] = "\n\
523 Sign the certificate using the supplied key and digest\n\
525 @param pkey: The key to sign with\n\
526 @param digest: The message digest to use\n\
531 crypto_X509_sign(crypto_X509Obj *self, PyObject *args)
533 crypto_PKeyObj *pkey;
535 const EVP_MD *digest;
537 if (!PyArg_ParseTuple(args, "O!s:sign", &crypto_PKey_Type, &pkey,
541 if (pkey->only_public) {
542 PyErr_SetString(PyExc_ValueError, "Key has only public part");
546 if (!pkey->initialized) {
547 PyErr_SetString(PyExc_ValueError, "Key is uninitialized");
551 if ((digest = EVP_get_digestbyname(digest_name)) == NULL)
553 PyErr_SetString(PyExc_ValueError, "No such digest method");
557 if (!X509_sign(self->x509, pkey->pkey, digest))
559 exception_from_error_queue(crypto_Error);
567 static char crypto_X509_has_expired_doc[] = "\n\
568 Check whether the certificate has expired.\n\
570 @return: True if the certificate has expired, false otherwise\n\
574 crypto_X509_has_expired(crypto_X509Obj *self, PyObject *args)
578 if (!PyArg_ParseTuple(args, ":has_expired"))
582 if (ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(self->x509), tnow) < 0)
583 return PyLong_FromLong(1L);
585 return PyLong_FromLong(0L);
588 static char crypto_X509_subject_name_hash_doc[] = "\n\
589 Return the hash of the X509 subject.\n\
591 @return: The hash of the subject\n\
595 crypto_X509_subject_name_hash(crypto_X509Obj *self, PyObject *args)
597 if (!PyArg_ParseTuple(args, ":subject_name_hash"))
600 return PyLong_FromLongLong(X509_subject_name_hash(self->x509));
603 static char crypto_X509_digest_doc[] = "\n\
604 Return the digest of the X509 object.\n\
606 @return: The digest of the object\n\
610 crypto_X509_digest(crypto_X509Obj *self, PyObject *args)
612 unsigned char fp[EVP_MAX_MD_SIZE];
617 const EVP_MD *digest;
619 if (!PyArg_ParseTuple(args, "s:digest", &digest_name))
622 if ((digest = EVP_get_digestbyname(digest_name)) == NULL)
624 PyErr_SetString(PyExc_ValueError, "No such digest method");
628 if (!X509_digest(self->x509,digest,fp,&len))
630 exception_from_error_queue(crypto_Error);
632 tmp = malloc(3*len+1);
633 memset(tmp, 0, 3*len+1);
634 for (i = 0; i < len; i++) {
635 sprintf(tmp+i*3,"%02X:",fp[i]);
638 ret = PyBytes_FromStringAndSize(tmp,3*len-1);
644 static char crypto_X509_add_extensions_doc[] = "\n\
645 Add extensions to the certificate.\n\
647 @param extensions: a sequence of X509Extension objects\n\
652 crypto_X509_add_extensions(crypto_X509Obj *self, PyObject *args)
654 PyObject *extensions, *seq;
655 crypto_X509ExtensionObj *ext;
656 int nr_of_extensions, i;
658 if (!PyArg_ParseTuple(args, "O:add_extensions", &extensions))
661 seq = PySequence_Fast(extensions, "Expected a sequence");
665 nr_of_extensions = PySequence_Fast_GET_SIZE(seq);
667 for (i = 0; i < nr_of_extensions; i++)
669 ext = (crypto_X509ExtensionObj *)PySequence_Fast_GET_ITEM(seq, i);
670 if (!crypto_X509Extension_Check(ext))
673 PyErr_SetString(PyExc_ValueError,
674 "One of the elements is not an X509Extension");
677 if (!X509_add_ext(self->x509, ext->x509_extension, -1))
680 exception_from_error_queue(crypto_Error);
689 static char crypto_X509_get_extension_count_doc[] = "\n\
690 Get the number of extensions on the certificate.\n\
692 @return: Number of extensions as a Python integer\n\
696 crypto_X509_get_extension_count(crypto_X509Obj *self, PyObject *args) {
697 if (!PyArg_ParseTuple(args, ":get_extension_count")) {
701 return PyLong_FromLong((long)X509_get_ext_count(self->x509));
704 static char crypto_X509_get_extension_doc[] = "\n\
705 Get a specific extension of the certificate by index.\n\
707 @param index: The index of the extension to retrieve.\n\
708 @return: The X509Extension object at the specified index.\n\
712 crypto_X509_get_extension(crypto_X509Obj *self, PyObject *args) {
713 crypto_X509ExtensionObj *extobj;
717 if (!PyArg_ParseTuple(args, "i:get_extension", &loc)) {
721 /* will return NULL if loc is outside the range of extensions,
722 not registered as an error*/
723 ext = X509_get_ext(self->x509, loc);
725 PyErr_SetString(PyExc_IndexError, "extension index out of bounds");
726 return NULL; /* Should be reported as an IndexError ? */
729 extobj = PyObject_New(crypto_X509ExtensionObj, &crypto_X509Extension_Type);
730 extobj->x509_extension = X509_EXTENSION_dup(ext);
732 return (PyObject*)extobj;
736 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
737 * { 'name', (PyCFunction)crypto_X509_name, METH_VARARGS }
740 #define ADD_METHOD(name) \
741 { #name, (PyCFunction)crypto_X509_##name, METH_VARARGS, crypto_X509_##name##_doc }
742 static PyMethodDef crypto_X509_methods[] =
744 ADD_METHOD(get_version),
745 ADD_METHOD(set_version),
746 ADD_METHOD(get_serial_number),
747 ADD_METHOD(set_serial_number),
748 ADD_METHOD(get_issuer),
749 ADD_METHOD(set_issuer),
750 ADD_METHOD(get_subject),
751 ADD_METHOD(set_subject),
752 ADD_METHOD(get_pubkey),
753 ADD_METHOD(set_pubkey),
754 ADD_METHOD(get_notBefore),
755 ADD_METHOD(set_notBefore),
756 ADD_METHOD(get_notAfter),
757 ADD_METHOD(set_notAfter),
758 ADD_METHOD(gmtime_adj_notBefore),
759 ADD_METHOD(gmtime_adj_notAfter),
761 ADD_METHOD(has_expired),
762 ADD_METHOD(subject_name_hash),
764 ADD_METHOD(add_extensions),
765 ADD_METHOD(get_extension),
766 ADD_METHOD(get_extension_count),
773 * Constructor for X509 objects, never called by Python code directly
775 * Arguments: cert - A "real" X509 certificate object
776 * dealloc - Boolean value to specify whether the destructor should
777 * free the "real" X509 object
778 * Returns: The newly created X509 object
781 crypto_X509_New(X509 *cert, int dealloc)
783 crypto_X509Obj *self;
785 self = PyObject_New(crypto_X509Obj, &crypto_X509_Type);
791 self->dealloc = dealloc;
797 static char crypto_X509_doc[] = "\n\
798 X509() -> X509 instance\n\
800 Create a new X509 object.\n\
802 @returns: The X509 object\n\
806 crypto_X509_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
808 if (!PyArg_ParseTuple(args, ":X509")) {
812 return (PyObject *)crypto_X509_New(X509_new(), 1);
817 * Deallocate the memory used by the X509 object
819 * Arguments: self - The X509 object
823 crypto_X509_dealloc(crypto_X509Obj *self)
825 /* Sometimes we don't have to dealloc the "real" X509 pointer ourselves */
827 X509_free(self->x509);
832 PyTypeObject crypto_X509_Type = {
833 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
835 sizeof(crypto_X509Obj),
837 (destructor)crypto_X509_dealloc,
843 NULL, /* as_number */
844 NULL, /* as_sequence */
845 NULL, /* as_mapping */
851 NULL, /* as_buffer */
853 crypto_X509_doc, /* doc */
856 NULL, /* tp_richcompare */
857 0, /* tp_weaklistoffset */
859 NULL, /* tp_iternext */
860 crypto_X509_methods, /* tp_methods */
861 NULL, /* tp_members */
862 NULL, /* tp_getset */
865 NULL, /* tp_descr_get */
866 NULL, /* tp_descr_set */
867 0, /* tp_dictoffset */
870 crypto_X509_new, /* tp_new */
874 * Initialize the X509 part of the crypto sub module
876 * Arguments: module - The crypto module
880 init_crypto_x509(PyObject *module)
882 if (PyType_Ready(&crypto_X509_Type) < 0) {
886 if (PyModule_AddObject(module, "X509", (PyObject *)&crypto_X509_Type) != 0) {
890 if (PyModule_AddObject(module, "X509Type", (PyObject *)&crypto_X509_Type) != 0) {