Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / OpenSSL / ssl / context.c
1 /*
2  * context.c
3  *
4  * Copyright (C) AB Strakt
5  * Copyright (C) Jean-Paul Calderone
6  * See LICENSE for details.
7  *
8  * SSL Context objects and their methods.
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
15 #if PY_VERSION_HEX >= 0x02050000
16 # define PYARG_PARSETUPLE_FORMAT const char
17 # define PYOBJECT_GETATTRSTRING_TYPE const char*
18 #else
19 # define PYARG_PARSETUPLE_FORMAT char
20 # define PYOBJECT_GETATTRSTRING_TYPE char*
21 #endif
22
23 #ifndef MS_WINDOWS
24 #  include <sys/socket.h>
25 #  include <netinet/in.h>
26 #  if !(defined(__BEOS__) || defined(__CYGWIN__))
27 #    include <netinet/tcp.h>
28 #  endif
29 #else
30 #  include <winsock.h>
31 #  include <wincrypt.h>
32 #endif
33
34 #define SSL_MODULE
35 #include "ssl.h"
36
37 /*
38  * CALLBACKS
39  *
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.
44  *
45  * Three caveats:
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?
49  *
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()
54  * functions.
55  *
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.
60  */
61
62 /*
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.
66  *
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
71  *                     ask once.
72  *            arg    - User data, always a Context object
73  * Returns:   The length of the password if successful, 0 otherwise
74  */
75 static int
76 global_passphrase_callback(char *buf, int maxlen, int verify, void *arg)
77 {
78     /*
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.
81      */
82     int len = 0;
83     char *str;
84     PyObject *argv, *ret = NULL;
85     ssl_ContextObj *ctx = (ssl_ContextObj *)arg;
86
87     /*
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
90      * before returning.
91      */
92     MY_END_ALLOW_THREADS(ctx->tstate);
93
94     /* The Python callback is called with a (maxlen,verify,userdata) tuple */
95     argv = Py_BuildValue("(iiO)", maxlen, verify, ctx->passphrase_userdata);
96
97     /*
98      * XXX Didn't check argv to see if it was NULL. -exarkun
99      */
100     ret = PyEval_CallObject(ctx->passphrase_callback, argv);
101     Py_DECREF(argv);
102
103     if (ret == NULL) {
104         /*
105          * The callback raised an exception.  It will be raised by whatever
106          * Python API triggered this callback.
107          */
108         goto out;
109     }
110
111     if (!PyObject_IsTrue(ret)) {
112         /*
113          * Returned "", or None, or something.  Treat it as no passphrase.
114          */
115         Py_DECREF(ret);
116         goto out;
117     }
118
119     if (!PyBytes_Check(ret)) {
120         /*
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.
124          */
125         Py_DECREF(ret);
126         goto out;
127     }
128
129     len = PyBytes_Size(ret);
130     if (len > maxlen) {
131         /*
132          * Returned more than we said they were allowed to return.  Just
133          * truncate it.  Might be better to raise an exception,
134          * instead. -exarkun
135          */
136         len = maxlen;
137     }
138
139     str = PyBytes_AsString(ret);
140     strncpy(buf, str, len);
141     Py_XDECREF(ret);
142
143   out:
144     /*
145      * This function is returning into OpenSSL.  Release the GIL again.
146      */
147     MY_BEGIN_ALLOW_THREADS(ctx->tstate);
148     return len;
149 }
150
151 /*
152  * Globally defined verify callback
153  *
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
157  *                       dealing with
158  * Returns:   True if everything is okay, false otherwise
159  */
160 static int
161 global_verify_callback(int ok, X509_STORE_CTX *x509_ctx)
162 {
163     PyObject *argv, *ret;
164     SSL *ssl;
165     ssl_ConnectionObj *conn;
166     crypto_X509Obj *cert;
167     int errnum, errdepth, c_ret;
168
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);
172
173     MY_END_ALLOW_THREADS(conn->tstate);
174
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);
178
179     argv = Py_BuildValue("(OOiii)", (PyObject *)conn, (PyObject *)cert,
180                                     errnum, errdepth, ok);
181     Py_DECREF(cert);
182     ret = PyEval_CallObject(conn->context->verify_callback, argv);
183     Py_DECREF(argv);
184
185     if (ret != NULL && PyObject_IsTrue(ret)) {
186         X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
187         Py_DECREF(ret);
188         c_ret = 1;
189     } else {
190         c_ret = 0;
191     }
192
193     MY_BEGIN_ALLOW_THREADS(conn->tstate);
194     return c_ret;
195 }
196
197 /*
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.
201  *
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
205  * Returns:   None
206  */
207 static void
208 global_info_callback(const SSL *ssl, int where, int _ret)
209 {
210     ssl_ConnectionObj *conn = (ssl_ConnectionObj *)SSL_get_app_data(ssl);
211     PyObject *argv, *ret;
212
213     /*
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
216      * before returning.
217      */
218     MY_END_ALLOW_THREADS(conn->tstate);
219
220     argv = Py_BuildValue("(Oii)", (PyObject *)conn, where, _ret);
221     ret = PyEval_CallObject(conn->context->info_callback, argv);
222     Py_DECREF(argv);
223
224     if (ret == NULL) {
225         /*
226          * XXX - This should be reported somehow. -exarkun
227          */
228         PyErr_Clear();
229     } else {
230         Py_DECREF(ret);
231     }
232
233     /*
234      * This function is returning into OpenSSL.  Release the GIL again.
235      */
236     MY_BEGIN_ALLOW_THREADS(conn->tstate);
237     return;
238 }
239
240
241 static char ssl_Context_doc[] = "\n\
242 Context(method) -> Context instance\n\
243 \n\
244 OpenSSL.SSL.Context instances define the parameters for setting up new SSL\n\
245 connections.\n\
246 \n\
247 @param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or\n\
248                TLSv1_METHOD.\n\
249 ";
250
251 static char ssl_Context_load_verify_locations_doc[] = "\n\
252 Let SSL know where we can find trusted certificates for the certificate\n\
253 chain\n\
254 \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\
257 @return: None\n\
258 ";
259 static PyObject *
260 ssl_Context_load_verify_locations(ssl_ContextObj *self, PyObject *args) {
261     char *cafile = NULL;
262     char *capath = NULL;
263
264     if (!PyArg_ParseTuple(args, "z|z:load_verify_locations", &cafile, &capath)) {
265         return NULL;
266     }
267
268     if (!SSL_CTX_load_verify_locations(self->ctx, cafile, capath))
269     {
270         exception_from_error_queue(ssl_Error);
271         return NULL;
272     }
273     else
274     {
275         Py_INCREF(Py_None);
276         return Py_None;
277     }
278 }
279
280 static char ssl_Context_set_default_verify_paths_doc[] = "\n\
281 Use the platform-specific CA certificate locations\n\
282 \n\
283 @return: None\n\
284 ";
285 static PyObject *
286 ssl_Context_set_default_verify_paths(ssl_ContextObj *self, PyObject *args) {
287     if (!PyArg_ParseTuple(args, ":set_default_verify_paths")) {
288         return NULL;
289     }
290
291     /*
292      * XXX Error handling for SSL_CTX_set_default_verify_paths is untested.
293      * -exarkun
294      */
295     if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
296         exception_from_error_queue(ssl_Error);
297         return NULL;
298     }
299     Py_INCREF(Py_None);
300     return Py_None;
301 };
302
303
304 static char ssl_Context_set_passwd_cb_doc[] = "\n\
305 Set the passphrase callback\n\
306 \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\
310 @return: None\n\
311 ";
312 static PyObject *
313 ssl_Context_set_passwd_cb(ssl_ContextObj *self, PyObject *args)
314 {
315     PyObject *callback = NULL, *userdata = Py_None;
316
317     if (!PyArg_ParseTuple(args, "O|O:set_passwd_cb", &callback, &userdata))
318         return NULL;
319
320     if (!PyCallable_Check(callback))
321     {
322         PyErr_SetString(PyExc_TypeError, "expected PyCallable");
323         return NULL;
324     }
325
326     Py_DECREF(self->passphrase_callback);
327     Py_INCREF(callback);
328     self->passphrase_callback = callback;
329     SSL_CTX_set_default_passwd_cb(self->ctx, global_passphrase_callback);
330
331     Py_DECREF(self->passphrase_userdata);
332     Py_INCREF(userdata);
333     self->passphrase_userdata = userdata;
334     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, (void *)self);
335
336     Py_INCREF(Py_None);
337     return Py_None;
338 }
339
340 static PyTypeObject *
341 type_modified_error(const char *name) {
342     PyErr_Format(PyExc_RuntimeError,
343                  "OpenSSL.crypto's '%s' attribute has been modified",
344                  name);
345     return NULL;
346 }
347
348 static PyTypeObject *
349 import_crypto_type(const char *name, size_t objsize) {
350     PyObject *module, *type, *name_attr;
351     PyTypeObject *res;
352     int right_name;
353
354     module = PyImport_ImportModule("OpenSSL.crypto");
355     if (module == NULL) {
356         return NULL;
357     }
358     type = PyObject_GetAttrString(module, (PYOBJECT_GETATTRSTRING_TYPE)name);
359     Py_DECREF(module);
360     if (type == NULL) {
361         return NULL;
362     }
363     if (!(PyType_Check(type))) {
364         Py_DECREF(type);
365         return type_modified_error(name);
366     }
367     name_attr = PyObject_GetAttrString(type, "__name__");
368     if (name_attr == NULL) {
369         Py_DECREF(type);
370         return NULL;
371     }
372
373 #ifdef PY3
374     {
375         PyObject* asciiname = PyUnicode_AsASCIIString(name_attr);
376         Py_DECREF(name_attr);
377         name_attr = asciiname;
378     }
379 #endif
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) {
385         Py_DECREF(type);
386         return type_modified_error(name);
387     }
388     return res;
389 }
390
391 static crypto_X509Obj *
392 parse_certificate_argument(const char* format, PyObject* args) {
393     static PyTypeObject *crypto_X509_type = NULL;
394     crypto_X509Obj *cert;
395
396     if (!crypto_X509_type) {
397         crypto_X509_type = import_crypto_type("X509", sizeof(crypto_X509Obj));
398         if (!crypto_X509_type) {
399             return NULL;
400         }
401     }
402     if (!PyArg_ParseTuple(args, (PYARG_PARSETUPLE_FORMAT *)format,
403                           crypto_X509_type, &cert)) {
404         return NULL;
405     }
406     return cert;
407 }
408
409 static char ssl_Context_add_extra_chain_cert_doc[] = "\n\
410 Add certificate to chain\n\
411 \n\
412 @param certobj: The X509 certificate object to add to the chain\n\
413 @return: None\n\
414 ";
415
416 static PyObject *
417 ssl_Context_add_extra_chain_cert(ssl_ContextObj *self, PyObject *args)
418 {
419     X509* cert_original;
420     crypto_X509Obj *cert = parse_certificate_argument(
421         "O!:add_extra_chain_cert", args);
422     if (cert == NULL)
423     {
424         return NULL;
425     }
426     if (!(cert_original = X509_dup(cert->x509)))
427     {
428         /* exception_from_error_queue(ssl_Error); */
429         PyErr_SetString(PyExc_RuntimeError, "X509_dup failed");
430         return NULL;
431     }
432     if (!SSL_CTX_add_extra_chain_cert(self->ctx, cert_original))
433     {
434         X509_free(cert_original);
435         exception_from_error_queue(ssl_Error);
436         return NULL;
437     }
438     else
439     {
440         Py_INCREF(Py_None);
441         return Py_None;
442     }
443 }
444
445
446 static char ssl_Context_use_certificate_chain_file_doc[] = "\n\
447 Load a certificate chain from a file\n\
448 \n\
449 @param certfile: The name of the certificate chain file\n\
450 @return: None\n\
451 ";
452 static PyObject *
453 ssl_Context_use_certificate_chain_file(ssl_ContextObj *self, PyObject *args)
454 {
455     char *certfile;
456
457     if (!PyArg_ParseTuple(args, "s:use_certificate_chain_file", &certfile))
458         return NULL;
459
460     if (!SSL_CTX_use_certificate_chain_file(self->ctx, certfile))
461     {
462         exception_from_error_queue(ssl_Error);
463         return NULL;
464     }
465     else
466     {
467         Py_INCREF(Py_None);
468         return Py_None;
469     }
470 }
471
472
473 static char ssl_Context_use_certificate_file_doc[] = "\n\
474 Load a certificate from a file\n\
475 \n\
476 @param certfile: The name of the certificate file\n\
477 @param filetype: (optional) The encoding of the file, default is PEM\n\
478 @return: None\n\
479 ";
480 static PyObject *
481 ssl_Context_use_certificate_file(ssl_ContextObj *self, PyObject *args)
482 {
483     char *certfile;
484     int filetype = SSL_FILETYPE_PEM;
485
486     if (!PyArg_ParseTuple(args, "s|i:use_certificate_file", &certfile, &filetype))
487         return NULL;
488
489     if (!SSL_CTX_use_certificate_file(self->ctx, certfile, filetype))
490     {
491         exception_from_error_queue(ssl_Error);
492         return NULL;
493     }
494     else
495     {
496         Py_INCREF(Py_None);
497         return Py_None;
498     }
499 }
500
501 static char ssl_Context_use_certificate_doc[] = "\n\
502 Load a certificate from a X509 object\n\
503 \n\
504 @param cert: The X509 object\n\
505 @return: None\n\
506 ";
507 static PyObject *
508 ssl_Context_use_certificate(ssl_ContextObj *self, PyObject *args)
509 {
510     crypto_X509Obj *cert = parse_certificate_argument(
511         "O!:use_certificate", args);
512     if (cert == NULL) {
513         return NULL;
514     }
515     
516     if (!SSL_CTX_use_certificate(self->ctx, cert->x509))
517     {
518         exception_from_error_queue(ssl_Error);
519         return NULL;
520     }
521     else
522     {
523         Py_INCREF(Py_None);
524         return Py_None;
525     }
526 }
527
528 static char ssl_Context_use_privatekey_file_doc[] = "\n\
529 Load a private key from a file\n\
530 \n\
531 @param keyfile: The name of the key file\n\
532 @param filetype: (optional) The encoding of the file, default is PEM\n\
533 @return: None\n\
534 ";
535 static PyObject *
536 ssl_Context_use_privatekey_file(ssl_ContextObj *self, PyObject *args)
537 {
538     char *keyfile;
539     int filetype = SSL_FILETYPE_PEM, ret;
540
541     if (!PyArg_ParseTuple(args, "s|i:use_privatekey_file", &keyfile, &filetype))
542         return NULL;
543
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);
547
548     if (PyErr_Occurred())
549     {
550         flush_error_queue();
551         return NULL;
552     }
553
554     if (!ret)
555     {
556         exception_from_error_queue(ssl_Error);
557         return NULL;
558     }
559     else
560     {
561         Py_INCREF(Py_None);
562         return Py_None;
563     }
564 }
565
566 static char ssl_Context_use_privatekey_doc[] = "\n\
567 Load a private key from a PKey object\n\
568 \n\
569 @param pkey: The PKey object\n\
570 @return: None\n\
571 ";
572 static PyObject *
573 ssl_Context_use_privatekey(ssl_ContextObj *self, PyObject *args) {
574     static PyTypeObject *crypto_PKey_type = NULL;
575     crypto_PKeyObj *pkey;
576
577     if (!crypto_PKey_type) {
578         crypto_PKey_type = import_crypto_type("PKey", sizeof(crypto_PKeyObj));
579         if (!crypto_PKey_type) {
580             return NULL;
581         }
582     }
583     if (!PyArg_ParseTuple(args, "O!:use_privatekey", crypto_PKey_type, &pkey)) {
584         return NULL;
585     }
586
587     if (!SSL_CTX_use_PrivateKey(self->ctx, pkey->pkey)) {
588         exception_from_error_queue(ssl_Error);
589         return NULL;
590     } else {
591         Py_INCREF(Py_None);
592         return Py_None;
593     }
594 }
595
596 static char ssl_Context_check_privatekey_doc[] = "\n\
597 Check that the private key and certificate match up\n\
598 \n\
599 @return: None (raises an exception if something's wrong)\n\
600 ";
601 static PyObject *
602 ssl_Context_check_privatekey(ssl_ContextObj *self, PyObject *args)
603 {
604     if (!PyArg_ParseTuple(args, ":check_privatekey"))
605         return NULL;
606
607     if (!SSL_CTX_check_private_key(self->ctx))
608     {
609         exception_from_error_queue(ssl_Error);
610         return NULL;
611     }
612     else
613     {
614         Py_INCREF(Py_None);
615         return Py_None;
616     }
617 }
618
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\
623 separately.\n\
624 \n\
625 @param cafile: The name of the certificates file\n\
626 @return: None\n\
627 ";
628 static PyObject *
629 ssl_Context_load_client_ca(ssl_ContextObj *self, PyObject *args)
630 {
631     char *cafile;
632
633     if (!PyArg_ParseTuple(args, "s:load_client_ca", &cafile))
634         return NULL;
635
636     SSL_CTX_set_client_CA_list(self->ctx, SSL_load_client_CA_file(cafile));
637
638     Py_INCREF(Py_None);
639     return Py_None;
640 }
641
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\
645 \n\
646 @param buf: A Python object that can be safely converted to a string\n\
647 @returns: None\n\
648 ";
649 static PyObject *
650 ssl_Context_set_session_id(ssl_ContextObj *self, PyObject *args)
651 {
652     unsigned char *buf;
653     unsigned int len;
654
655     if (!PyArg_ParseTuple(args, "s#:set_session_id", &buf, &len))
656         return NULL;
657
658     if (!SSL_CTX_set_session_id_context(self->ctx, buf, len))
659     {
660         exception_from_error_queue(ssl_Error);
661         return NULL;
662     }
663     else
664     {
665         Py_INCREF(Py_None);
666         return Py_None;
667     }
668 }
669
670 static char ssl_Context_set_verify_doc[] = "\n\
671 Set the verify mode and verify callback\n\
672 \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\
676 @return: None\n\
677 \n\
678 See SSL_CTX_set_verify(3SSL) for further details.\n\
679 ";
680 static PyObject *
681 ssl_Context_set_verify(ssl_ContextObj *self, PyObject *args)
682 {
683     int mode;
684     PyObject *callback = NULL;
685
686     if (!PyArg_ParseTuple(args, "iO:set_verify", &mode, &callback))
687         return NULL;
688
689     if (!PyCallable_Check(callback))
690     {
691         PyErr_SetString(PyExc_TypeError, "expected PyCallable");
692         return NULL;
693     }
694
695     Py_DECREF(self->verify_callback);
696     Py_INCREF(callback);
697     self->verify_callback = callback;
698     SSL_CTX_set_verify(self->ctx, mode, global_verify_callback);
699
700     Py_INCREF(Py_None);
701     return Py_None;
702 }
703
704 static char ssl_Context_set_verify_depth_doc[] = "\n\
705 Set the verify depth\n\
706 \n\
707 @param depth: An integer specifying the verify depth\n\
708 @return: None\n\
709 ";
710 static PyObject *
711 ssl_Context_set_verify_depth(ssl_ContextObj *self, PyObject *args)
712 {
713     int depth;
714
715     if (!PyArg_ParseTuple(args, "i:set_verify_depth", &depth))
716         return NULL;
717
718     SSL_CTX_set_verify_depth(self->ctx, depth);
719     Py_INCREF(Py_None);
720     return Py_None;
721 }
722
723 static char ssl_Context_get_verify_mode_doc[] = "\n\
724 Get the verify mode\n\
725 \n\
726 @return: The verify mode\n\
727 ";
728 static PyObject *
729 ssl_Context_get_verify_mode(ssl_ContextObj *self, PyObject *args)
730 {
731     int mode;
732
733     if (!PyArg_ParseTuple(args, ":get_verify_mode"))
734         return NULL;
735
736     mode = SSL_CTX_get_verify_mode(self->ctx);
737     return PyLong_FromLong((long)mode);
738 }
739
740 static char ssl_Context_get_verify_depth_doc[] = "\n\
741 Get the verify depth\n\
742 \n\
743 @return: The verify depth\n\
744 ";
745 static PyObject *
746 ssl_Context_get_verify_depth(ssl_ContextObj *self, PyObject *args)
747 {
748     int depth;
749
750     if (!PyArg_ParseTuple(args, ":get_verify_depth"))
751         return NULL;
752
753     depth = SSL_CTX_get_verify_depth(self->ctx);
754     return PyLong_FromLong((long)depth);
755 }
756
757 static char ssl_Context_load_tmp_dh_doc[] = "\n\
758 Load parameters for Ephemeral Diffie-Hellman\n\
759 \n\
760 @param dhfile: The file to load EDH parameters from\n\
761 @return: None\n\
762 ";
763 static PyObject *
764 ssl_Context_load_tmp_dh(ssl_ContextObj *self, PyObject *args)
765 {
766     char *dhfile;
767     BIO *bio;
768     DH *dh;
769
770     if (!PyArg_ParseTuple(args, "s:load_tmp_dh", &dhfile))
771         return NULL;
772
773     bio = BIO_new_file(dhfile, "r");
774     if (bio == NULL) {
775         exception_from_error_queue(ssl_Error);
776         return NULL;
777     }
778
779     dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
780     SSL_CTX_set_tmp_dh(self->ctx, dh);
781     DH_free(dh);
782     BIO_free(bio);
783
784     Py_INCREF(Py_None);
785     return Py_None;
786 }
787
788 static char ssl_Context_set_cipher_list_doc[] = "\n\
789 Change the cipher list\n\
790 \n\
791 @param cipher_list: A cipher list, see ciphers(1)\n\
792 @return: None\n\
793 ";
794 static PyObject *
795 ssl_Context_set_cipher_list(ssl_ContextObj *self, PyObject *args)
796 {
797     char *cipher_list;
798
799     if (!PyArg_ParseTuple(args, "s:set_cipher_list", &cipher_list))
800         return NULL;
801
802     if (!SSL_CTX_set_cipher_list(self->ctx, cipher_list))
803     {
804         exception_from_error_queue(ssl_Error);
805         return NULL;
806     }
807     else
808     {
809         Py_INCREF(Py_None);
810         return Py_None;
811     }
812 }
813
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\
816 \n\
817 This list of certificate authorities will be sent to the client when the\n\
818 server requests a client certificate.\n\
819 \n\
820 @param certificate_authorities: a sequence of X509Names.\n\
821 @return: None\n\
822 ";
823
824 static PyObject *
825 ssl_Context_set_client_ca_list(ssl_ContextObj *self, PyObject *args)
826 {
827     static PyTypeObject *X509NameType;
828     PyObject *sequence, *tuple, *item;
829     crypto_X509NameObj *name;
830     X509_NAME *sslname;
831     STACK_OF(X509_NAME) *CANames;
832     Py_ssize_t length;
833     int i;
834
835     if (X509NameType == NULL) {
836         X509NameType = import_crypto_type("X509Name", sizeof(crypto_X509NameObj));
837         if (X509NameType == NULL) {
838             return NULL;
839         }
840     }
841     if (!PyArg_ParseTuple(args, "O:set_client_ca_list", &sequence)) {
842         return NULL;
843     }
844     tuple = PySequence_Tuple(sequence);
845     if (tuple == NULL) {
846         return NULL;
847     }
848     length = PyTuple_Size(tuple);
849     if (length >= INT_MAX) {
850         PyErr_SetString(PyExc_ValueError, "client CA list is too long");
851         Py_DECREF(tuple);
852         return NULL;
853     }
854     CANames = sk_X509_NAME_new_null();
855     if (CANames == NULL) {
856         Py_DECREF(tuple);
857         exception_from_error_queue(ssl_Error);
858         return NULL;
859     }
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);
867             Py_DECREF(tuple);
868             return NULL;
869         }
870         name = (crypto_X509NameObj *)item;
871         sslname = X509_NAME_dup(name->x509_name);
872         if (sslname == NULL) {
873             sk_X509_NAME_free(CANames);
874             Py_DECREF(tuple);
875             exception_from_error_queue(ssl_Error);
876             return NULL;
877         }
878         if (!sk_X509_NAME_push(CANames, sslname)) {
879             X509_NAME_free(sslname);
880             sk_X509_NAME_free(CANames);
881             Py_DECREF(tuple);
882             exception_from_error_queue(ssl_Error);
883             return NULL;
884         }
885     }
886     Py_DECREF(tuple);
887     SSL_CTX_set_client_CA_list(self->ctx, CANames);
888     Py_INCREF(Py_None);
889     return Py_None;
890 }
891
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\
894 \n\
895 The list of certificate authorities will be sent to the client when the\n\
896 server requests a client certificate.\n\
897 \n\
898 @param certificate_authority: certificate authority's X509 certificate.\n\
899 @return: None\n\
900 ";
901
902 static PyObject *
903 ssl_Context_add_client_ca(ssl_ContextObj *self, PyObject *args)
904 {
905     crypto_X509Obj *cert;
906
907     cert = parse_certificate_argument("O!:add_client_ca", args);
908     if (cert == NULL) {
909         return NULL;
910     }
911     if (!SSL_CTX_add_client_CA(self->ctx, cert->x509)) {
912         exception_from_error_queue(ssl_Error);
913         return NULL;
914     }
915     Py_INCREF(Py_None);
916     return Py_None;
917 }
918
919 static char ssl_Context_set_timeout_doc[] = "\n\
920 Set session timeout\n\
921 \n\
922 @param timeout: The timeout in seconds\n\
923 @return: The previous session timeout\n\
924 ";
925 static PyObject *
926 ssl_Context_set_timeout(ssl_ContextObj *self, PyObject *args)
927 {
928     long t, ret;
929
930     if (!PyArg_ParseTuple(args, "l:set_timeout", &t))
931         return NULL;
932
933     ret = SSL_CTX_set_timeout(self->ctx, t);
934     return PyLong_FromLong(ret);
935 }
936
937 static char ssl_Context_get_timeout_doc[] = "\n\
938 Get the session timeout\n\
939 \n\
940 @return: The session timeout\n\
941 ";
942 static PyObject *
943 ssl_Context_get_timeout(ssl_ContextObj *self, PyObject *args)
944 {
945     long ret;
946
947     if (!PyArg_ParseTuple(args, ":get_timeout"))
948         return NULL;
949
950     ret = SSL_CTX_get_timeout(self->ctx);
951     return PyLong_FromLong(ret);
952 }
953
954 static char ssl_Context_set_info_callback_doc[] = "\n\
955 Set the info callback\n\
956 \n\
957 @param callback: The Python callback to use\n\
958 @return: None\n\
959 ";
960 static PyObject *
961 ssl_Context_set_info_callback(ssl_ContextObj *self, PyObject *args)
962 {
963     PyObject *callback;
964
965     if (!PyArg_ParseTuple(args, "O:set_info_callback", &callback))
966         return NULL;
967
968     if (!PyCallable_Check(callback))
969     {
970         PyErr_SetString(PyExc_TypeError, "expected PyCallable");
971         return NULL;
972     }
973
974     Py_DECREF(self->info_callback);
975     Py_INCREF(callback);
976     self->info_callback = callback;
977     SSL_CTX_set_info_callback(self->ctx, global_info_callback);
978
979     Py_INCREF(Py_None);
980     return Py_None;
981 }
982
983 static char ssl_Context_get_app_data_doc[] = "\n\
984 Get the application data (supplied via set_app_data())\n\
985 \n\
986 @return: The application data\n\
987 ";
988 static PyObject *
989 ssl_Context_get_app_data(ssl_ContextObj *self, PyObject *args)
990 {
991     if (!PyArg_ParseTuple(args, ":get_app_data"))
992         return NULL;
993
994     Py_INCREF(self->app_data);
995     return self->app_data;
996 }
997
998 static char ssl_Context_set_app_data_doc[] = "\n\
999 Set the application data (will be returned from get_app_data())\n\
1000 \n\
1001 @param data: Any Python object\n\
1002 @return: None\n\
1003 ";
1004 static PyObject *
1005 ssl_Context_set_app_data(ssl_ContextObj *self, PyObject *args)
1006 {
1007     PyObject *data;
1008
1009     if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
1010         return NULL;
1011
1012     Py_DECREF(self->app_data);
1013     Py_INCREF(data);
1014     self->app_data = data;
1015
1016     Py_INCREF(Py_None);
1017     return Py_None;
1018 }
1019
1020 static char ssl_Context_get_cert_store_doc[] = "\n\
1021 Get the certificate store for the context\n\
1022 \n\
1023 @return: A X509Store object\n\
1024 ";
1025 static PyObject *
1026 ssl_Context_get_cert_store(ssl_ContextObj *self, PyObject *args)
1027 {
1028     X509_STORE *store;
1029
1030     if (!PyArg_ParseTuple(args, ":get_cert_store"))
1031         return NULL;
1032
1033     if ((store = SSL_CTX_get_cert_store(self->ctx)) == NULL)
1034     {
1035         Py_INCREF(Py_None);
1036         return Py_None;
1037     }
1038     else
1039     {
1040         return (PyObject *)new_x509store(store, 0);
1041     }
1042 }
1043
1044 static char ssl_Context_set_options_doc[] = "\n\
1045 Add options. Options set before are not cleared!\n\
1046 \n\
1047 @param options: The options to add.\n\
1048 @return: The new option bitmask.\n\
1049 ";
1050 static PyObject *
1051 ssl_Context_set_options(ssl_ContextObj *self, PyObject *args)
1052 {
1053     long options;
1054
1055     if (!PyArg_ParseTuple(args, "l:set_options", &options))
1056         return NULL;
1057
1058     return PyLong_FromLong(SSL_CTX_set_options(self->ctx, options));
1059 }
1060
1061
1062 /*
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 }
1066  * for convenience
1067  * ADD_ALIAS(name,real) creates an "alias" of the ssl_Context_real
1068  * function with the name 'name'
1069  */
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),
1099     { NULL, NULL }
1100 };
1101 #undef ADD_METHOD
1102
1103 /*
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.
1107  */
1108 static ssl_ContextObj*
1109 ssl_Context_init(ssl_ContextObj *self, int i_method) {
1110     SSL_METHOD *method;
1111
1112     switch (i_method) {
1113         case ssl_SSLv2_METHOD:
1114             method = SSLv2_method();
1115             break;
1116         case ssl_SSLv23_METHOD:
1117             method = SSLv23_method();
1118             break;
1119         case ssl_SSLv3_METHOD:
1120             method = SSLv3_method();
1121             break;
1122         case ssl_TLSv1_METHOD:
1123             method = TLSv1_method();
1124             break;
1125         default:
1126             PyErr_SetString(PyExc_ValueError, "No such protocol");
1127             return NULL;
1128     }
1129
1130     self->ctx = SSL_CTX_new(method);
1131     Py_INCREF(Py_None);
1132     self->passphrase_callback = Py_None;
1133     Py_INCREF(Py_None);
1134     self->verify_callback = Py_None;
1135     Py_INCREF(Py_None);
1136     self->info_callback = Py_None;
1137
1138     Py_INCREF(Py_None);
1139     self->passphrase_userdata = Py_None;
1140
1141     Py_INCREF(Py_None);
1142     self->app_data = Py_None;
1143
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);
1149
1150     self->tstate = NULL;
1151
1152     return self;
1153 }
1154
1155 /*
1156  * This one is exposed in the CObject API.  I want to deprecate it.
1157  */
1158 ssl_ContextObj*
1159 ssl_Context_New(int i_method) {
1160     ssl_ContextObj *self;
1161
1162     self = PyObject_GC_New(ssl_ContextObj, &ssl_Context_Type);
1163     if (self == NULL) {
1164        return (ssl_ContextObj *)PyErr_NoMemory();
1165     }
1166     self = ssl_Context_init(self, i_method);
1167     PyObject_GC_Track((PyObject *)self);
1168     return self;
1169 }
1170
1171
1172 /*
1173  * This one is the tp_new of the Context type.  It's great.
1174  */
1175 static PyObject*
1176 ssl_Context_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1177     int i_method;
1178     ssl_ContextObj *self;
1179     static char *kwlist[] = {"method", NULL};
1180
1181     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i:Context", kwlist, &i_method)) {
1182         return NULL;
1183     }
1184
1185     self = (ssl_ContextObj *)subtype->tp_alloc(subtype, 1);
1186     if (self == NULL) {
1187         return NULL;
1188     }
1189
1190     return (PyObject *)ssl_Context_init(self, i_method);
1191 }
1192
1193 /*
1194  * Call the visitproc on all contained objects.
1195  *
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.
1201  */
1202 static int
1203 ssl_Context_traverse(ssl_ContextObj *self, visitproc visit, void *arg)
1204 {
1205     int ret = 0;
1206
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);
1217     return ret;
1218 }
1219
1220 /*
1221  * Decref all contained objects and zero the pointers.
1222  *
1223  * Arguments: self - The Context object
1224  * Returns:   Always 0.
1225  */
1226 static int
1227 ssl_Context_clear(ssl_ContextObj *self)
1228 {
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;
1239     return 0;
1240 }
1241
1242 /*
1243  * Deallocate the memory used by the Context object
1244  *
1245  * Arguments: self - The Context object
1246  * Returns:   None
1247  */
1248 static void
1249 ssl_Context_dealloc(ssl_ContextObj *self)
1250 {
1251     PyObject_GC_UnTrack((PyObject *)self);
1252     SSL_CTX_free(self->ctx);
1253     ssl_Context_clear(self);
1254     PyObject_GC_Del(self);
1255 }
1256
1257
1258 PyTypeObject ssl_Context_Type = {
1259     PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
1260     "OpenSSL.SSL.Context",
1261     sizeof(ssl_ContextObj),
1262     0,
1263     (destructor)ssl_Context_dealloc, /* tp_dealloc */
1264     NULL, /* print */
1265     NULL, /* tp_getattr */
1266     NULL, /* setattr */
1267     NULL, /* compare */
1268     NULL, /* repr */
1269     NULL, /* as_number */
1270     NULL, /* as_sequence */
1271     NULL, /* as_mapping */
1272     NULL, /* hash */
1273     NULL, /* call */
1274     NULL, /* str */
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 */
1284     NULL, /* tp_iter */
1285     NULL, /* tp_iternext */
1286     ssl_Context_methods, /* tp_methods */
1287     NULL, /* tp_members */
1288     NULL, /* tp_getset */
1289     NULL, /* tp_base */
1290     NULL, /* tp_dict */
1291     NULL, /* tp_descr_get */
1292     NULL, /* tp_descr_set */
1293     0, /* tp_dictoffset */
1294     NULL, /* tp_init */
1295     NULL, /* tp_alloc */
1296     ssl_Context_new, /* tp_new */
1297 };
1298
1299
1300 /*
1301  * Initialize the Context part of the SSL sub module
1302  *
1303  * Arguments: dict - The OpenSSL.SSL module
1304  * Returns:   1 for success, 0 otherwise
1305  */
1306 int
1307 init_ssl_context(PyObject *module) {
1308
1309     if (PyType_Ready(&ssl_Context_Type) < 0) {
1310         return 0;
1311     }
1312
1313     if (PyModule_AddObject(module, "Context", (PyObject *)&ssl_Context_Type) < 0) {
1314         return 0;
1315     }
1316
1317     if (PyModule_AddObject(module, "ContextType", (PyObject *)&ssl_Context_Type) < 0) {
1318         return 0;
1319     }
1320
1321     return 1;
1322 }
1323