4 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
8 * SSL Context objects and their methods.
9 * See the file RATIONALE for a short explanation of why this module was written.
15 #if PY_VERSION_HEX >= 0x02050000
16 # define PYARG_PARSETUPLE_FORMAT const char
17 # define PYOBJECT_GETATTRSTRING_TYPE const char*
19 # define PYARG_PARSETUPLE_FORMAT char
20 # define PYOBJECT_GETATTRSTRING_TYPE char*
24 # include <sys/socket.h>
25 # include <netinet/in.h>
26 # if !(defined(__BEOS__) || defined(__CYGWIN__))
27 # include <netinet/tcp.h>
31 # include <wincrypt.h>
40 * Callbacks work like this: We provide a "global" callback in C which
41 * transforms the arguments into a Python argument tuple and calls the
42 * corresponding Python callback, and then parsing the return value back into
43 * things the C function can return.
46 * + How do we find the Context object where the Python callbacks are stored?
47 * + What about multithreading and execution frames?
48 * + What about Python callbacks that raise exceptions?
50 * The solution to the first issue is trivial if the callback provides
51 * "userdata" functionality. Since the only callbacks that don't provide
52 * userdata do provide a pointer to an SSL structure, we can associate an SSL
53 * object and a Connection one-to-one via the SSL_set/get_app_data()
56 * The solution to the other issue is to rewrite the Py_BEGIN_ALLOW_THREADS
57 * macro allowing it (or rather a new macro) to specify where to save the
58 * thread state (in our case, as a member of the Connection/Context object) so
59 * we can retrieve it again before calling the Python callback.
63 * Globally defined passphrase callback. This is called from OpenSSL
64 * internally. The GIL will not be held when this function is invoked. It
65 * must not be held when the function returns.
67 * Arguments: buf - Buffer to store the returned passphrase in
68 * maxlen - Maximum length of the passphrase
69 * verify - If true, the passphrase callback should ask for a
70 * password twice and verify they're equal. If false, only
72 * arg - User data, always a Context object
73 * Returns: The length of the password if successful, 0 otherwise
76 global_passphrase_callback(char *buf, int maxlen, int verify, void *arg)
79 * Initialize len here because we're always going to return it, and we
80 * might jump to the return before it gets initialized in any other way.
84 PyObject *argv, *ret = NULL;
85 ssl_ContextObj *ctx = (ssl_ContextObj *)arg;
88 * GIL isn't held yet. First things first - acquire it, or any Python API
89 * we invoke might segfault or blow up the sun. The reverse will be done
92 MY_END_ALLOW_THREADS(ctx->tstate);
94 /* The Python callback is called with a (maxlen,verify,userdata) tuple */
95 argv = Py_BuildValue("(iiO)", maxlen, verify, ctx->passphrase_userdata);
98 * XXX Didn't check argv to see if it was NULL. -exarkun
100 ret = PyEval_CallObject(ctx->passphrase_callback, argv);
105 * The callback raised an exception. It will be raised by whatever
106 * Python API triggered this callback.
111 if (!PyObject_IsTrue(ret)) {
113 * Returned "", or None, or something. Treat it as no passphrase.
119 if (!PyBytes_Check(ret)) {
121 * XXX Returned something that wasn't a string. This is bogus. We'll
122 * return 0 and OpenSSL will treat it as an error, resulting in an
123 * exception from whatever Python API triggered this callback.
129 len = PyBytes_Size(ret);
132 * Returned more than we said they were allowed to return. Just
133 * truncate it. Might be better to raise an exception,
139 str = PyBytes_AsString(ret);
140 strncpy(buf, str, len);
145 * This function is returning into OpenSSL. Release the GIL again.
147 MY_BEGIN_ALLOW_THREADS(ctx->tstate);
152 * Globally defined verify callback
154 * Arguments: ok - True everything is OK "so far", false otherwise
155 * x509_ctx - Contains the certificate being checked, the current
156 * error number and depth, and the Connection we're
158 * Returns: True if everything is okay, false otherwise
161 global_verify_callback(int ok, X509_STORE_CTX *x509_ctx)
163 PyObject *argv, *ret;
165 ssl_ConnectionObj *conn;
166 crypto_X509Obj *cert;
167 int errnum, errdepth, c_ret;
169 // Get Connection object to check thread state
170 ssl = (SSL *)X509_STORE_CTX_get_app_data(x509_ctx);
171 conn = (ssl_ConnectionObj *)SSL_get_app_data(ssl);
173 MY_END_ALLOW_THREADS(conn->tstate);
175 cert = new_x509(X509_STORE_CTX_get_current_cert(x509_ctx), 0);
176 errnum = X509_STORE_CTX_get_error(x509_ctx);
177 errdepth = X509_STORE_CTX_get_error_depth(x509_ctx);
179 argv = Py_BuildValue("(OOiii)", (PyObject *)conn, (PyObject *)cert,
180 errnum, errdepth, ok);
182 ret = PyEval_CallObject(conn->context->verify_callback, argv);
185 if (ret != NULL && PyObject_IsTrue(ret)) {
186 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
193 MY_BEGIN_ALLOW_THREADS(conn->tstate);
198 * Globally defined info callback. This is called from OpenSSL internally.
199 * The GIL will not be held when this function is invoked. It must not be held
200 * when the function returns.
202 * Arguments: ssl - The Connection
203 * where - The part of the SSL code that called us
204 * _ret - The return code of the SSL function that called us
208 global_info_callback(const SSL *ssl, int where, int _ret)
210 ssl_ConnectionObj *conn = (ssl_ConnectionObj *)SSL_get_app_data(ssl);
211 PyObject *argv, *ret;
214 * GIL isn't held yet. First things first - acquire it, or any Python API
215 * we invoke might segfault or blow up the sun. The reverse will be done
218 MY_END_ALLOW_THREADS(conn->tstate);
220 argv = Py_BuildValue("(Oii)", (PyObject *)conn, where, _ret);
221 ret = PyEval_CallObject(conn->context->info_callback, argv);
226 * XXX - This should be reported somehow. -exarkun
234 * This function is returning into OpenSSL. Release the GIL again.
236 MY_BEGIN_ALLOW_THREADS(conn->tstate);
241 static char ssl_Context_doc[] = "\n\
242 Context(method) -> Context instance\n\
244 OpenSSL.SSL.Context instances define the parameters for setting up new SSL\n\
247 @param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or\n\
251 static char ssl_Context_load_verify_locations_doc[] = "\n\
252 Let SSL know where we can find trusted certificates for the certificate\n\
255 @param cafile: In which file we can find the certificates\n\
256 @param capath: In which directory we can find the certificates\n\
260 ssl_Context_load_verify_locations(ssl_ContextObj *self, PyObject *args) {
264 if (!PyArg_ParseTuple(args, "z|z:load_verify_locations", &cafile, &capath)) {
268 if (!SSL_CTX_load_verify_locations(self->ctx, cafile, capath))
270 exception_from_error_queue(ssl_Error);
280 static char ssl_Context_set_default_verify_paths_doc[] = "\n\
281 Use the platform-specific CA certificate locations\n\
286 ssl_Context_set_default_verify_paths(ssl_ContextObj *self, PyObject *args) {
287 if (!PyArg_ParseTuple(args, ":set_default_verify_paths")) {
292 * XXX Error handling for SSL_CTX_set_default_verify_paths is untested.
295 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
296 exception_from_error_queue(ssl_Error);
304 static char ssl_Context_set_passwd_cb_doc[] = "\n\
305 Set the passphrase callback\n\
307 @param callback: The Python callback to use\n\
308 @param userdata: (optional) A Python object which will be given as\n\
309 argument to the callback\n\
313 ssl_Context_set_passwd_cb(ssl_ContextObj *self, PyObject *args)
315 PyObject *callback = NULL, *userdata = Py_None;
317 if (!PyArg_ParseTuple(args, "O|O:set_passwd_cb", &callback, &userdata))
320 if (!PyCallable_Check(callback))
322 PyErr_SetString(PyExc_TypeError, "expected PyCallable");
326 Py_DECREF(self->passphrase_callback);
328 self->passphrase_callback = callback;
329 SSL_CTX_set_default_passwd_cb(self->ctx, global_passphrase_callback);
331 Py_DECREF(self->passphrase_userdata);
333 self->passphrase_userdata = userdata;
334 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, (void *)self);
340 static PyTypeObject *
341 type_modified_error(const char *name) {
342 PyErr_Format(PyExc_RuntimeError,
343 "OpenSSL.crypto's '%s' attribute has been modified",
348 static PyTypeObject *
349 import_crypto_type(const char *name, size_t objsize) {
350 PyObject *module, *type, *name_attr;
354 module = PyImport_ImportModule("OpenSSL.crypto");
355 if (module == NULL) {
358 type = PyObject_GetAttrString(module, (PYOBJECT_GETATTRSTRING_TYPE)name);
363 if (!(PyType_Check(type))) {
365 return type_modified_error(name);
367 name_attr = PyObject_GetAttrString(type, "__name__");
368 if (name_attr == NULL) {
375 PyObject* asciiname = PyUnicode_AsASCIIString(name_attr);
376 Py_DECREF(name_attr);
377 name_attr = asciiname;
380 right_name = (PyBytes_CheckExact(name_attr) &&
381 strcmp(name, PyBytes_AsString(name_attr)) == 0);
382 Py_DECREF(name_attr);
383 res = (PyTypeObject *)type;
384 if (!right_name || res->tp_basicsize != objsize) {
386 return type_modified_error(name);
391 static crypto_X509Obj *
392 parse_certificate_argument(const char* format, PyObject* args) {
393 static PyTypeObject *crypto_X509_type = NULL;
394 crypto_X509Obj *cert;
396 if (!crypto_X509_type) {
397 crypto_X509_type = import_crypto_type("X509", sizeof(crypto_X509Obj));
398 if (!crypto_X509_type) {
402 if (!PyArg_ParseTuple(args, (PYARG_PARSETUPLE_FORMAT *)format,
403 crypto_X509_type, &cert)) {
409 static char ssl_Context_add_extra_chain_cert_doc[] = "\n\
410 Add certificate to chain\n\
412 @param certobj: The X509 certificate object to add to the chain\n\
417 ssl_Context_add_extra_chain_cert(ssl_ContextObj *self, PyObject *args)
420 crypto_X509Obj *cert = parse_certificate_argument(
421 "O!:add_extra_chain_cert", args);
426 if (!(cert_original = X509_dup(cert->x509)))
428 /* exception_from_error_queue(ssl_Error); */
429 PyErr_SetString(PyExc_RuntimeError, "X509_dup failed");
432 if (!SSL_CTX_add_extra_chain_cert(self->ctx, cert_original))
434 X509_free(cert_original);
435 exception_from_error_queue(ssl_Error);
446 static char ssl_Context_use_certificate_chain_file_doc[] = "\n\
447 Load a certificate chain from a file\n\
449 @param certfile: The name of the certificate chain file\n\
453 ssl_Context_use_certificate_chain_file(ssl_ContextObj *self, PyObject *args)
457 if (!PyArg_ParseTuple(args, "s:use_certificate_chain_file", &certfile))
460 if (!SSL_CTX_use_certificate_chain_file(self->ctx, certfile))
462 exception_from_error_queue(ssl_Error);
473 static char ssl_Context_use_certificate_file_doc[] = "\n\
474 Load a certificate from a file\n\
476 @param certfile: The name of the certificate file\n\
477 @param filetype: (optional) The encoding of the file, default is PEM\n\
481 ssl_Context_use_certificate_file(ssl_ContextObj *self, PyObject *args)
484 int filetype = SSL_FILETYPE_PEM;
486 if (!PyArg_ParseTuple(args, "s|i:use_certificate_file", &certfile, &filetype))
489 if (!SSL_CTX_use_certificate_file(self->ctx, certfile, filetype))
491 exception_from_error_queue(ssl_Error);
501 static char ssl_Context_use_certificate_doc[] = "\n\
502 Load a certificate from a X509 object\n\
504 @param cert: The X509 object\n\
508 ssl_Context_use_certificate(ssl_ContextObj *self, PyObject *args)
510 crypto_X509Obj *cert = parse_certificate_argument(
511 "O!:use_certificate", args);
516 if (!SSL_CTX_use_certificate(self->ctx, cert->x509))
518 exception_from_error_queue(ssl_Error);
528 static char ssl_Context_use_privatekey_file_doc[] = "\n\
529 Load a private key from a file\n\
531 @param keyfile: The name of the key file\n\
532 @param filetype: (optional) The encoding of the file, default is PEM\n\
536 ssl_Context_use_privatekey_file(ssl_ContextObj *self, PyObject *args)
539 int filetype = SSL_FILETYPE_PEM, ret;
541 if (!PyArg_ParseTuple(args, "s|i:use_privatekey_file", &keyfile, &filetype))
544 MY_BEGIN_ALLOW_THREADS(self->tstate);
545 ret = SSL_CTX_use_PrivateKey_file(self->ctx, keyfile, filetype);
546 MY_END_ALLOW_THREADS(self->tstate);
548 if (PyErr_Occurred())
556 exception_from_error_queue(ssl_Error);
566 static char ssl_Context_use_privatekey_doc[] = "\n\
567 Load a private key from a PKey object\n\
569 @param pkey: The PKey object\n\
573 ssl_Context_use_privatekey(ssl_ContextObj *self, PyObject *args) {
574 static PyTypeObject *crypto_PKey_type = NULL;
575 crypto_PKeyObj *pkey;
577 if (!crypto_PKey_type) {
578 crypto_PKey_type = import_crypto_type("PKey", sizeof(crypto_PKeyObj));
579 if (!crypto_PKey_type) {
583 if (!PyArg_ParseTuple(args, "O!:use_privatekey", crypto_PKey_type, &pkey)) {
587 if (!SSL_CTX_use_PrivateKey(self->ctx, pkey->pkey)) {
588 exception_from_error_queue(ssl_Error);
596 static char ssl_Context_check_privatekey_doc[] = "\n\
597 Check that the private key and certificate match up\n\
599 @return: None (raises an exception if something's wrong)\n\
602 ssl_Context_check_privatekey(ssl_ContextObj *self, PyObject *args)
604 if (!PyArg_ParseTuple(args, ":check_privatekey"))
607 if (!SSL_CTX_check_private_key(self->ctx))
609 exception_from_error_queue(ssl_Error);
619 static char ssl_Context_load_client_ca_doc[] = "\n\
620 Load the trusted certificates that will be sent to the client (basically\n \
621 telling the client \"These are the guys I trust\"). Does not actually\n\
622 imply any of the certificates are trusted; that must be configured\n\
625 @param cafile: The name of the certificates file\n\
629 ssl_Context_load_client_ca(ssl_ContextObj *self, PyObject *args)
633 if (!PyArg_ParseTuple(args, "s:load_client_ca", &cafile))
636 SSL_CTX_set_client_CA_list(self->ctx, SSL_load_client_CA_file(cafile));
642 static char ssl_Context_set_session_id_doc[] = "\n\
643 Set the session identifier, this is needed if you want to do session\n\
644 resumption (which, ironically, isn't implemented yet)\n\
646 @param buf: A Python object that can be safely converted to a string\n\
650 ssl_Context_set_session_id(ssl_ContextObj *self, PyObject *args)
655 if (!PyArg_ParseTuple(args, "s#:set_session_id", &buf, &len))
658 if (!SSL_CTX_set_session_id_context(self->ctx, buf, len))
660 exception_from_error_queue(ssl_Error);
670 static char ssl_Context_set_verify_doc[] = "\n\
671 Set the verify mode and verify callback\n\
673 @param mode: The verify mode, this is either VERIFY_NONE or\n\
674 VERIFY_PEER combined with possible other flags\n\
675 @param callback: The Python callback to use\n\
678 See SSL_CTX_set_verify(3SSL) for further details.\n\
681 ssl_Context_set_verify(ssl_ContextObj *self, PyObject *args)
684 PyObject *callback = NULL;
686 if (!PyArg_ParseTuple(args, "iO:set_verify", &mode, &callback))
689 if (!PyCallable_Check(callback))
691 PyErr_SetString(PyExc_TypeError, "expected PyCallable");
695 Py_DECREF(self->verify_callback);
697 self->verify_callback = callback;
698 SSL_CTX_set_verify(self->ctx, mode, global_verify_callback);
704 static char ssl_Context_set_verify_depth_doc[] = "\n\
705 Set the verify depth\n\
707 @param depth: An integer specifying the verify depth\n\
711 ssl_Context_set_verify_depth(ssl_ContextObj *self, PyObject *args)
715 if (!PyArg_ParseTuple(args, "i:set_verify_depth", &depth))
718 SSL_CTX_set_verify_depth(self->ctx, depth);
723 static char ssl_Context_get_verify_mode_doc[] = "\n\
724 Get the verify mode\n\
726 @return: The verify mode\n\
729 ssl_Context_get_verify_mode(ssl_ContextObj *self, PyObject *args)
733 if (!PyArg_ParseTuple(args, ":get_verify_mode"))
736 mode = SSL_CTX_get_verify_mode(self->ctx);
737 return PyLong_FromLong((long)mode);
740 static char ssl_Context_get_verify_depth_doc[] = "\n\
741 Get the verify depth\n\
743 @return: The verify depth\n\
746 ssl_Context_get_verify_depth(ssl_ContextObj *self, PyObject *args)
750 if (!PyArg_ParseTuple(args, ":get_verify_depth"))
753 depth = SSL_CTX_get_verify_depth(self->ctx);
754 return PyLong_FromLong((long)depth);
757 static char ssl_Context_load_tmp_dh_doc[] = "\n\
758 Load parameters for Ephemeral Diffie-Hellman\n\
760 @param dhfile: The file to load EDH parameters from\n\
764 ssl_Context_load_tmp_dh(ssl_ContextObj *self, PyObject *args)
770 if (!PyArg_ParseTuple(args, "s:load_tmp_dh", &dhfile))
773 bio = BIO_new_file(dhfile, "r");
775 exception_from_error_queue(ssl_Error);
779 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
780 SSL_CTX_set_tmp_dh(self->ctx, dh);
788 static char ssl_Context_set_cipher_list_doc[] = "\n\
789 Change the cipher list\n\
791 @param cipher_list: A cipher list, see ciphers(1)\n\
795 ssl_Context_set_cipher_list(ssl_ContextObj *self, PyObject *args)
799 if (!PyArg_ParseTuple(args, "s:set_cipher_list", &cipher_list))
802 if (!SSL_CTX_set_cipher_list(self->ctx, cipher_list))
804 exception_from_error_queue(ssl_Error);
814 static char ssl_Context_set_client_ca_list_doc[] = "\n\
815 Set the list of preferred client certificate signers for this server context.\n\
817 This list of certificate authorities will be sent to the client when the\n\
818 server requests a client certificate.\n\
820 @param certificate_authorities: a sequence of X509Names.\n\
825 ssl_Context_set_client_ca_list(ssl_ContextObj *self, PyObject *args)
827 static PyTypeObject *X509NameType;
828 PyObject *sequence, *tuple, *item;
829 crypto_X509NameObj *name;
831 STACK_OF(X509_NAME) *CANames;
835 if (X509NameType == NULL) {
836 X509NameType = import_crypto_type("X509Name", sizeof(crypto_X509NameObj));
837 if (X509NameType == NULL) {
841 if (!PyArg_ParseTuple(args, "O:set_client_ca_list", &sequence)) {
844 tuple = PySequence_Tuple(sequence);
848 length = PyTuple_Size(tuple);
849 if (length >= INT_MAX) {
850 PyErr_SetString(PyExc_ValueError, "client CA list is too long");
854 CANames = sk_X509_NAME_new_null();
855 if (CANames == NULL) {
857 exception_from_error_queue(ssl_Error);
860 for (i = 0; i < length; i++) {
861 item = PyTuple_GetItem(tuple, i);
862 if (item->ob_type != X509NameType) {
863 PyErr_Format(PyExc_TypeError,
864 "client CAs must be X509Name objects, not %s objects",
865 item->ob_type->tp_name);
866 sk_X509_NAME_free(CANames);
870 name = (crypto_X509NameObj *)item;
871 sslname = X509_NAME_dup(name->x509_name);
872 if (sslname == NULL) {
873 sk_X509_NAME_free(CANames);
875 exception_from_error_queue(ssl_Error);
878 if (!sk_X509_NAME_push(CANames, sslname)) {
879 X509_NAME_free(sslname);
880 sk_X509_NAME_free(CANames);
882 exception_from_error_queue(ssl_Error);
887 SSL_CTX_set_client_CA_list(self->ctx, CANames);
892 static char ssl_Context_add_client_ca_doc[] = "\n\
893 Add the CA certificate to the list of preferred signers for this context.\n\
895 The list of certificate authorities will be sent to the client when the\n\
896 server requests a client certificate.\n\
898 @param certificate_authority: certificate authority's X509 certificate.\n\
903 ssl_Context_add_client_ca(ssl_ContextObj *self, PyObject *args)
905 crypto_X509Obj *cert;
907 cert = parse_certificate_argument("O!:add_client_ca", args);
911 if (!SSL_CTX_add_client_CA(self->ctx, cert->x509)) {
912 exception_from_error_queue(ssl_Error);
919 static char ssl_Context_set_timeout_doc[] = "\n\
920 Set session timeout\n\
922 @param timeout: The timeout in seconds\n\
923 @return: The previous session timeout\n\
926 ssl_Context_set_timeout(ssl_ContextObj *self, PyObject *args)
930 if (!PyArg_ParseTuple(args, "l:set_timeout", &t))
933 ret = SSL_CTX_set_timeout(self->ctx, t);
934 return PyLong_FromLong(ret);
937 static char ssl_Context_get_timeout_doc[] = "\n\
938 Get the session timeout\n\
940 @return: The session timeout\n\
943 ssl_Context_get_timeout(ssl_ContextObj *self, PyObject *args)
947 if (!PyArg_ParseTuple(args, ":get_timeout"))
950 ret = SSL_CTX_get_timeout(self->ctx);
951 return PyLong_FromLong(ret);
954 static char ssl_Context_set_info_callback_doc[] = "\n\
955 Set the info callback\n\
957 @param callback: The Python callback to use\n\
961 ssl_Context_set_info_callback(ssl_ContextObj *self, PyObject *args)
965 if (!PyArg_ParseTuple(args, "O:set_info_callback", &callback))
968 if (!PyCallable_Check(callback))
970 PyErr_SetString(PyExc_TypeError, "expected PyCallable");
974 Py_DECREF(self->info_callback);
976 self->info_callback = callback;
977 SSL_CTX_set_info_callback(self->ctx, global_info_callback);
983 static char ssl_Context_get_app_data_doc[] = "\n\
984 Get the application data (supplied via set_app_data())\n\
986 @return: The application data\n\
989 ssl_Context_get_app_data(ssl_ContextObj *self, PyObject *args)
991 if (!PyArg_ParseTuple(args, ":get_app_data"))
994 Py_INCREF(self->app_data);
995 return self->app_data;
998 static char ssl_Context_set_app_data_doc[] = "\n\
999 Set the application data (will be returned from get_app_data())\n\
1001 @param data: Any Python object\n\
1005 ssl_Context_set_app_data(ssl_ContextObj *self, PyObject *args)
1009 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
1012 Py_DECREF(self->app_data);
1014 self->app_data = data;
1020 static char ssl_Context_get_cert_store_doc[] = "\n\
1021 Get the certificate store for the context\n\
1023 @return: A X509Store object\n\
1026 ssl_Context_get_cert_store(ssl_ContextObj *self, PyObject *args)
1030 if (!PyArg_ParseTuple(args, ":get_cert_store"))
1033 if ((store = SSL_CTX_get_cert_store(self->ctx)) == NULL)
1040 return (PyObject *)new_x509store(store, 0);
1044 static char ssl_Context_set_options_doc[] = "\n\
1045 Add options. Options set before are not cleared!\n\
1047 @param options: The options to add.\n\
1048 @return: The new option bitmask.\n\
1051 ssl_Context_set_options(ssl_ContextObj *self, PyObject *args)
1055 if (!PyArg_ParseTuple(args, "l:set_options", &options))
1058 return PyLong_FromLong(SSL_CTX_set_options(self->ctx, options));
1063 * Member methods in the Context object
1064 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1065 * { 'name', (PyCFunction)ssl_Context_name, METH_VARARGS }
1067 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Context_real
1068 * function with the name 'name'
1070 #define ADD_METHOD(name) { #name, (PyCFunction)ssl_Context_##name, METH_VARARGS, ssl_Context_##name##_doc }
1071 static PyMethodDef ssl_Context_methods[] = {
1072 ADD_METHOD(load_verify_locations),
1073 ADD_METHOD(set_passwd_cb),
1074 ADD_METHOD(set_default_verify_paths),
1075 ADD_METHOD(use_certificate_chain_file),
1076 ADD_METHOD(use_certificate_file),
1077 ADD_METHOD(use_certificate),
1078 ADD_METHOD(add_extra_chain_cert),
1079 ADD_METHOD(use_privatekey_file),
1080 ADD_METHOD(use_privatekey),
1081 ADD_METHOD(check_privatekey),
1082 ADD_METHOD(load_client_ca),
1083 ADD_METHOD(set_session_id),
1084 ADD_METHOD(set_verify),
1085 ADD_METHOD(set_verify_depth),
1086 ADD_METHOD(get_verify_mode),
1087 ADD_METHOD(get_verify_depth),
1088 ADD_METHOD(load_tmp_dh),
1089 ADD_METHOD(set_cipher_list),
1090 ADD_METHOD(set_client_ca_list),
1091 ADD_METHOD(add_client_ca),
1092 ADD_METHOD(set_timeout),
1093 ADD_METHOD(get_timeout),
1094 ADD_METHOD(set_info_callback),
1095 ADD_METHOD(get_app_data),
1096 ADD_METHOD(set_app_data),
1097 ADD_METHOD(get_cert_store),
1098 ADD_METHOD(set_options),
1104 * Despite the name which might suggest otherwise, this is not the tp_init for
1105 * the Context type. It's just the common initialization code shared by the
1106 * two _{Nn}ew functions below.
1108 static ssl_ContextObj*
1109 ssl_Context_init(ssl_ContextObj *self, int i_method) {
1113 case ssl_SSLv2_METHOD:
1114 method = SSLv2_method();
1116 case ssl_SSLv23_METHOD:
1117 method = SSLv23_method();
1119 case ssl_SSLv3_METHOD:
1120 method = SSLv3_method();
1122 case ssl_TLSv1_METHOD:
1123 method = TLSv1_method();
1126 PyErr_SetString(PyExc_ValueError, "No such protocol");
1130 self->ctx = SSL_CTX_new(method);
1132 self->passphrase_callback = Py_None;
1134 self->verify_callback = Py_None;
1136 self->info_callback = Py_None;
1139 self->passphrase_userdata = Py_None;
1142 self->app_data = Py_None;
1144 /* Some initialization that's required to operate smoothly in Python */
1145 SSL_CTX_set_app_data(self->ctx, self);
1146 SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
1147 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
1148 SSL_MODE_AUTO_RETRY);
1150 self->tstate = NULL;
1156 * This one is exposed in the CObject API. I want to deprecate it.
1159 ssl_Context_New(int i_method) {
1160 ssl_ContextObj *self;
1162 self = PyObject_GC_New(ssl_ContextObj, &ssl_Context_Type);
1164 return (ssl_ContextObj *)PyErr_NoMemory();
1166 self = ssl_Context_init(self, i_method);
1167 PyObject_GC_Track((PyObject *)self);
1173 * This one is the tp_new of the Context type. It's great.
1176 ssl_Context_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1178 ssl_ContextObj *self;
1179 static char *kwlist[] = {"method", NULL};
1181 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i:Context", kwlist, &i_method)) {
1185 self = (ssl_ContextObj *)subtype->tp_alloc(subtype, 1);
1190 return (PyObject *)ssl_Context_init(self, i_method);
1194 * Call the visitproc on all contained objects.
1196 * Arguments: self - The Context object
1197 * visit - Function to call
1198 * arg - Extra argument to visit
1199 * Returns: 0 if all goes well, otherwise the return code from the first
1200 * call that gave non-zero result.
1203 ssl_Context_traverse(ssl_ContextObj *self, visitproc visit, void *arg)
1207 if (ret == 0 && self->passphrase_callback != NULL)
1208 ret = visit((PyObject *)self->passphrase_callback, arg);
1209 if (ret == 0 && self->passphrase_userdata != NULL)
1210 ret = visit((PyObject *)self->passphrase_userdata, arg);
1211 if (ret == 0 && self->verify_callback != NULL)
1212 ret = visit((PyObject *)self->verify_callback, arg);
1213 if (ret == 0 && self->info_callback != NULL)
1214 ret = visit((PyObject *)self->info_callback, arg);
1215 if (ret == 0 && self->app_data != NULL)
1216 ret = visit(self->app_data, arg);
1221 * Decref all contained objects and zero the pointers.
1223 * Arguments: self - The Context object
1224 * Returns: Always 0.
1227 ssl_Context_clear(ssl_ContextObj *self)
1229 Py_XDECREF(self->passphrase_callback);
1230 self->passphrase_callback = NULL;
1231 Py_XDECREF(self->passphrase_userdata);
1232 self->passphrase_userdata = NULL;
1233 Py_XDECREF(self->verify_callback);
1234 self->verify_callback = NULL;
1235 Py_XDECREF(self->info_callback);
1236 self->info_callback = NULL;
1237 Py_XDECREF(self->app_data);
1238 self->app_data = NULL;
1243 * Deallocate the memory used by the Context object
1245 * Arguments: self - The Context object
1249 ssl_Context_dealloc(ssl_ContextObj *self)
1251 PyObject_GC_UnTrack((PyObject *)self);
1252 SSL_CTX_free(self->ctx);
1253 ssl_Context_clear(self);
1254 PyObject_GC_Del(self);
1258 PyTypeObject ssl_Context_Type = {
1259 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
1260 "OpenSSL.SSL.Context",
1261 sizeof(ssl_ContextObj),
1263 (destructor)ssl_Context_dealloc, /* tp_dealloc */
1265 NULL, /* tp_getattr */
1269 NULL, /* as_number */
1270 NULL, /* as_sequence */
1271 NULL, /* as_mapping */
1275 NULL, /* getattro */
1276 NULL, /* setattro */
1277 NULL, /* as_buffer */
1278 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */
1279 ssl_Context_doc, /* tp_doc */
1280 (traverseproc)ssl_Context_traverse, /* tp_traverse */
1281 (inquiry)ssl_Context_clear, /* tp_clear */
1282 NULL, /* tp_richcompare */
1283 0, /* tp_weaklistoffset */
1285 NULL, /* tp_iternext */
1286 ssl_Context_methods, /* tp_methods */
1287 NULL, /* tp_members */
1288 NULL, /* tp_getset */
1291 NULL, /* tp_descr_get */
1292 NULL, /* tp_descr_set */
1293 0, /* tp_dictoffset */
1295 NULL, /* tp_alloc */
1296 ssl_Context_new, /* tp_new */
1301 * Initialize the Context part of the SSL sub module
1303 * Arguments: dict - The OpenSSL.SSL module
1304 * Returns: 1 for success, 0 otherwise
1307 init_ssl_context(PyObject *module) {
1309 if (PyType_Ready(&ssl_Context_Type) < 0) {
1313 if (PyModule_AddObject(module, "Context", (PyObject *)&ssl_Context_Type) < 0) {
1317 if (PyModule_AddObject(module, "ContextType", (PyObject *)&ssl_Context_Type) < 0) {