<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[15210] PySecureTransport/trunk</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/15210">15210</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2015-10-21 13:10:47 -0700 (Wed, 21 Oct 2015)</dd>
</dl>

<h3>Log Message</h3>
<pre>Initial commit.</pre>

<h3>Added Paths</h3>
<ul>
<li><a href="#PySecureTransporttrunkLICENSE">PySecureTransport/trunk/LICENSE</a></li>
<li>PySecureTransport/trunk/OpenSSL/</li>
<li><a href="#PySecureTransporttrunkOpenSSLSSLpy">PySecureTransport/trunk/OpenSSL/SSL.py</a></li>
<li><a href="#PySecureTransporttrunkOpenSSL__init__py">PySecureTransport/trunk/OpenSSL/__init__.py</a></li>
<li><a href="#PySecureTransporttrunkOpenSSLcryptopy">PySecureTransport/trunk/OpenSSL/crypto.py</a></li>
<li><a href="#PySecureTransporttrunkOpenSSLversionpy">PySecureTransport/trunk/OpenSSL/version.py</a></li>
<li><a href="#PySecureTransporttrunkREADME">PySecureTransport/trunk/README</a></li>
<li><a href="#PySecureTransporttrunksetuppy">PySecureTransport/trunk/setup.py</a></li>
</ul>

<h3>Property Changed</h3>
<ul>
<li><a href="#PySecureTransporttrunk">PySecureTransport/trunk/</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="PySecureTransporttrunk"></a>
<div class="propset"><h4>Property changes: PySecureTransport/trunk</h4>
<pre class="diff"><span>
</span></pre></div>
<a id="svnignore"></a>
<div class="addfile"><h4>Added: svn:ignore</h4></div>
<span class="cx">.pydevproject
</span><a id="PySecureTransporttrunkLICENSE"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/LICENSE (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/LICENSE                                (rev 0)
+++ PySecureTransport/trunk/LICENSE        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,202 @@
</span><ins>+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      &quot;License&quot; shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      &quot;Legal Entity&quot; shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      &quot;control&quot; means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      &quot;Source&quot; form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      &quot;Object&quot; form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      &quot;Work&quot; shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      &quot;Contribution&quot; shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, &quot;submitted&quot;
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
+
+      &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same &quot;printed page&quot; as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
</ins></span></pre></div>
<a id="PySecureTransporttrunkOpenSSLSSLpy"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/OpenSSL/SSL.py (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/OpenSSL/SSL.py                                (rev 0)
+++ PySecureTransport/trunk/OpenSSL/SSL.py        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,489 @@
</span><ins>+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+&quot;&quot;&quot;
+An API compatible replace for pyOpenSSL's OpenSSL.SSL module that uses SecureTransport as the
+underlying SSL library. This is designed to work with Twisted's twisted.protocols.tls.TLSMemoryBIOProtocol
+object, and provide a way to use SecureTransport with Twisted with the minimum amount of changes.
+&quot;&quot;&quot;
+
+from osx._corefoundation import ffi, lib as security
+from osx.corefoundation import CFArrayRef
+
+from OpenSSL.crypto import _getIdentityCertificate
+
+
+class Error(Exception):
+    &quot;&quot;&quot;
+    An error occurred in an `OpenSSL.SSL` API.
+    &quot;&quot;&quot;
+    pass
+
+
+
+class WantReadError(Error):
+    pass
+
+
+
+class WantWriteError(Error):
+    pass
+
+
+
+class WantX509LookupError(Error):
+    pass
+
+
+
+class ZeroReturnError(Error):
+    pass
+
+
+# Constants grabbed from pyOpenSSL and openssl/include/ssl.h
+
+SSLv2_METHOD = 1
+SSLv3_METHOD = 2
+SSLv23_METHOD = 3
+TLSv1_METHOD = 4
+TLSv1_1_METHOD = 5
+TLSv1_2_METHOD = 6
+
+OP_NO_SSLv2 = 0x01000000
+OP_NO_SSLv3 = 0x02000000
+OP_NO_TLSv1 = 0x04000000
+OP_NO_TLSv1_1 = 0x08000000
+OP_NO_TLSv1_2 = 0x10000000
+
+OP_NO_COMPRESSION = 0x00020000
+OP_CIPHER_SERVER_PREFERENCE = 0x00400000
+
+VERIFY_NONE = 0x00
+VERIFY_PEER = 0x01
+VERIFY_FAIL_IF_NO_PEER_CERT = 0x02
+VERIFY_CLIENT_ONCE = 0x04
+
+
+
+class Context(object):
+    &quot;&quot;&quot;
+    Equivalent of an pyOpenSSL OpenSSL.SSL.Context object, with many of the methods stubbed out.
+    &quot;&quot;&quot;
+
+    def __init__(self, method):
+        &quot;&quot;&quot;
+        The L{method} value is actually ignored for SecureTransport.
+
+        @param method: one of the *_METHOD values
+        @type method: L{int}
+        &quot;&quot;&quot;
+        self.method = method
+        self.identity = None
+        self.options = set()
+
+
+    def set_options(self, option):
+        &quot;&quot;&quot;
+        Add an option to this context.
+
+        @param option: the OP_* value to add
+        @type option: L{int}
+        &quot;&quot;&quot;
+        self.options.add(option)
+
+
+    def use_certificate_file(self, certificateFileName):
+        &quot;&quot;&quot;
+        Certificate file to use - for SecureTransport we actually treat the file name as the certificate name
+        to lookup in the KeyChain. Set it only if an identity has not already been set.
+
+        @param certificateFileName: subject name of the certificate to use
+        @type certificateFileName: L{str}
+        &quot;&quot;&quot;
+        if self.identity is None and certificateFileName:
+            self.identity = _getIdentityCertificate(certificateFileName)
+
+
+    def use_privatekey_file(self, privateKeyFileName):
+        &quot;&quot;&quot;
+        Private key file to use - for SecureTransport we actually treat the file name as the certificate name
+        to lookup in the KeyChain. Set it only if an identity has not already been set.
+
+        @param certificateFileName: subject name of the certificate to use
+        @type certificateFileName: L{str}
+        &quot;&quot;&quot;
+        if self.identity is None and privateKeyFileName:
+            self.identity = _getIdentityCertificate(privateKeyFileName)
+
+
+    def use_certificate_chain_file(self, certfile):
+        pass
+
+
+    def set_passwd_cb(self, callback, userdata=None):
+        pass
+
+
+    def set_cipher_list(self, cipher_list):
+        pass
+
+
+    def set_session_id(self, buf):
+        pass
+
+
+    def set_verify(self, mode, callback):
+        &quot;&quot;&quot;
+        We are going to rely on SecureTransport's own KeyChain based verification rather than overriding with
+        our own.
+        &quot;&quot;&quot;
+        pass
+
+
+    def set_verify_depth(self, depth):
+        &quot;&quot;&quot;
+        We are going to rely on SecureTransport's own KeyChain based verification rather than overriding with
+        our own.
+        &quot;&quot;&quot;
+        pass
+
+
+    def add_client_ca(self, certificate_authority):
+        pass
+
+
+
+class Connection(object):
+    &quot;&quot;&quot;
+    Equivalent of an pyOpenSSL OpenSSL.SSL.Connection object.
+
+    Due to the way SecureTransport's read/write callbacks work, we need a way to track all instances of this class
+    via a simple reference value (an L{int}) so that we can gain access to the L{Connection} object during the
+    callbacks. This is done using the C{engines} class variable and a counter.
+    &quot;&quot;&quot;
+
+    engines = {}
+    next_engine_id = 1
+
+    def __init__(self, context, socket=None):
+        &quot;&quot;&quot;
+        @param context: the context to use for the connection settings
+        @type context: L{Context}
+        @param socket: ignored
+        @type socket: L{None}
+        &quot;&quot;&quot;
+        self.context = context
+        self.protocol = None
+        self.is_client = None
+
+        self.ctx = None
+        self.connref = None
+        self.bytes = []
+        self._in_handshake = None
+
+        # Register for callbacks
+        self.engine_id = self.next_engine_id
+        self.__class__.next_engine_id += 1
+        self.engines[self.engine_id] = self
+
+
+    def set_app_data(self, protocol):
+        &quot;&quot;&quot;
+        We need access to the Twisted L{Protocol} object so we can get to the associated L{Transport} object
+        which allows us to read/write to the underlying socket.
+
+        @param protocol: Twisted protocol to use
+        @type protocol: L{TLSMemoryBIOProtocol}
+        &quot;&quot;&quot;
+        self.protocol = protocol
+
+
+    def set_connect_state(self):
+        &quot;&quot;&quot;
+        Called when a client connection needs to be initiated.
+        &quot;&quot;&quot;
+        self.is_client = True
+        self.connect()
+
+
+    def set_accept_state(self):
+        &quot;&quot;&quot;
+        Called when a server connection needs to be initiated.
+        &quot;&quot;&quot;
+        self.is_client = False
+        self.connect()
+
+
+    @staticmethod
+    @ffi.callback(&quot;OSStatus (*) ( SSLConnectionRef connection, void *data, size_t *dataLength )&quot;)
+    def _read(fdptr, data, dataLength):
+        &quot;&quot;&quot;
+        The SecureTransport SSL read callback.
+
+        @param fdptr: reference value added via SSLSetConnection
+        @type fdptr: ffi(int *)
+        @param data: buffer to read data into
+        @type data: ffi(void *)
+        @param dataLength: length of the buffer to read into, and on return
+            the actual length of data read
+        @type dataLength: ffi(size_t *)
+        &quot;&quot;&quot;
+
+        # Get the associated L{Connection} object
+        engine_id = ffi.cast(&quot;int *&quot;, fdptr)[0]
+        engine = Connection.engines[engine_id]
+
+        # If there are bytes pending in the L{Connection}s buffer, read as much
+        # of those as possible, or return errSSLWouldBlock
+        dlen = dataLength[0]
+        rdata = ffi.buffer(data, dlen)
+        if engine.getBytes(rdata, dlen) is None:
+            dataLength[0] = 0
+            return security.errSSLWouldBlock
+
+        return 0
+
+
+    @staticmethod
+    @ffi.callback(&quot;OSStatus (*) ( SSLConnectionRef connection, const void *data, size_t *dataLength )&quot;)
+    def _write(fdptr, data, dataLength):
+        &quot;&quot;&quot;
+        The SecureTransport SSL write callback.
+
+        @param fdptr: reference value added via SSLSetConnection
+        @type fdptr: ffi(int *)
+        @param data: buffer to write
+        @type data: ffi(const void *)
+        @param dataLength: length of the data to write, and on return
+            the actual length of data written
+        @type dataLength: ffi(size_t *)
+        &quot;&quot;&quot;
+
+        # Get the associated L{Connection} object
+        engine_id = ffi.cast(&quot;int *&quot;, fdptr)[0]
+        engine = Connection.engines[engine_id]
+
+        # We always write everything in one go
+        dlen = dataLength[0]
+        wdata = ffi.buffer(data, dlen)
+        engine.protocol.transport.write(wdata[:])
+
+        return 0
+
+
+    def _sslread(self, bytes):
+        &quot;&quot;&quot;
+        Wrapper for SecureTransport SSLRead method.
+
+        @param bytes: maximum length of data to read
+        @type bytes: L{int}
+
+        @return: the data read
+        @rtype: L{ffi.buffer}
+        &quot;&quot;&quot;
+
+        read = ffi.new(&quot;char[]&quot;, bytes)
+        processed = ffi.new(&quot;size_t *&quot;)
+        err = security.SSLRead(self.ctx, read, bytes, processed)
+        if err == 0:
+            response = ffi.buffer(read, processed[0])
+            return response
+        elif err == security.errSSLWouldBlock:
+            raise WantReadError
+        elif err == security.errSSLClosedGraceful:
+            raise ZeroReturnError
+        else:
+            self.shutdown()
+            raise Error(err)
+
+
+    def _sslwrite(self, data):
+        &quot;&quot;&quot;
+        Wrapper for SecureTransport SSLWrite method.
+
+        @param data: data to write
+        @type data: L{str}
+        &quot;&quot;&quot;
+
+        processed = ffi.new(&quot;size_t *&quot;)
+        err = security.SSLWrite(self.ctx, data, len(data), processed)
+        if err == 0:
+            return processed[0]
+        elif err == security.errSSLWouldBlock:
+            return processed[0]
+        else:
+            self.shutdown()
+            raise Error(err)
+
+
+    def connect(self):
+        &quot;&quot;&quot;
+        Create the SecureTransport SSLContextRef object and initialize it.
+        &quot;&quot;&quot;
+
+        self.ctx = security.SSLCreateContext(ffi.NULL, security.kSSLClientSide if self.is_client else security.kSSLServerSide, security.kSSLStreamType)
+
+        if OP_NO_SSLv2 in self.context.options:
+            security.SSLSetProtocolVersionEnabled(self.ctx, security.kSSLProtocol2, False)
+        if OP_NO_SSLv3 in self.context.options:
+            security.SSLSetProtocolVersionEnabled(self.ctx, security.kSSLProtocol3, False)
+        if OP_NO_TLSv1 in self.context.options:
+            security.SSLSetProtocolVersionEnabled(self.ctx, security.kTLSProtocol1, False)
+        if OP_NO_TLSv1_1 in self.context.options:
+            security.SSLSetProtocolVersionEnabled(self.ctx, security.kTLSProtocol11, False)
+        if OP_NO_TLSv1_2 in self.context.options:
+            security.SSLSetProtocolVersionEnabled(self.ctx, security.kTLSProtocol12, False)
+
+        # Make sure we have a reference back to this L{Connection} in the SecureTransport callbacks
+        self.connref = ffi.new(&quot;int *&quot;, self.engine_id)
+        err = security.SSLSetConnection(self.ctx, ffi.cast(&quot;SSLConnectionRef&quot;, self.connref))
+        if err:
+            self.shutdown()
+            raise Error(err)
+
+        # Setup the actual SecureTransport callbacks
+        err = security.SSLSetIOFuncs(self.ctx, self._read, self._write)
+        if err:
+            self.shutdown()
+            raise Error(err)
+
+        # Must have a certificate identity if we are a server
+        if not self.is_client and self.context.identity is None:
+            self.shutdown()
+            raise Error(&quot;No certificate&quot;)
+
+        # Add the crtificate
+        if self.context.identity is not None:
+            certs = CFArrayRef.fromList([self.context.identity])
+            err = security.SSLSetCertificate(self.ctx, certs.ref())
+            if err:
+                self.shutdown()
+                raise Error(err)
+
+
+    def do_handshake(self):
+        &quot;&quot;&quot;
+        Carry out the SecureTransport SSLHandshake. Note that this can be called multiple times during the SSL connection
+        setup as data needs to be read/written via the underlying Twisted L{Transport} object in order for the actual
+        handshake data exchange to take place. So this will likely get errSSLWouldBlock several times.
+        &quot;&quot;&quot;
+        if self.ctx is None:
+            raise Error(&quot;No context&quot;)
+        self._in_handshake = True
+        err = security.SSLHandshake(self.ctx)
+        if err == 0:
+            self._in_handshake = False
+        elif err == security.errSSLWouldBlock:
+            raise WantReadError
+        else:
+            self.shutdown()
+            raise Error(err)
+
+
+    def get_peer_certificate(self):
+        return None
+
+
+    def get_cipher_list(self):
+        return (&quot;null&quot;,)
+
+
+    def shutdown(self):
+        &quot;&quot;&quot;
+        Wrapper for SecureTransport SSLCLose method
+        &quot;&quot;&quot;
+        if self.ctx is not None:
+            err = security.SSLClose(self.ctx)
+
+            # Always clear out the callbacks reference
+            self.ctx = None
+            self.connref = None
+            del self.engines[self.engine_id]
+            if err:
+                raise Error(err)
+        return True
+
+
+    def bio_read(self, bytes):
+        &quot;&quot;&quot;
+        We always send immediately so there is nothing to do here.
+        &quot;&quot;&quot;
+        raise WantReadError
+
+
+    def bio_write(self, bytes):
+        &quot;&quot;&quot;
+        Just append to our internal buffer so that the next SSLRead will can retrieve the &quot;raw&quot; SSL bytes
+        from the buffer and decode them into actual &quot;application&quot; data.
+
+        @param bytes: data to write
+        @type bytes: L{str}
+        &quot;&quot;&quot;
+        self.bytes.append(bytes)
+
+
+    def bio_shutdown(self):
+        self.shutdown()
+
+
+    def recv(self, bytes):
+        &quot;&quot;&quot;
+        Retrieve application level data from SSL.
+        &quot;&quot;&quot;
+        if self.ctx is None:
+            raise ZeroReturnError
+        elif self._in_handshake is None:
+            raise WantReadError
+        elif self._in_handshake:
+            self.do_handshake()
+
+        data = self._sslread(bytes)
+        return data[:]
+
+
+    def send(self, bytes):
+        &quot;&quot;&quot;
+        Send application level data to SSL.
+        &quot;&quot;&quot;
+        if self.ctx is None:
+            raise ZeroReturnError
+        elif self._in_handshake is None:
+            raise WantReadError
+        elif self._in_handshake:
+            self.do_handshake()
+
+        return self._sslwrite(bytes)
+
+
+    def getBytes(self, buf, blen):
+        &quot;&quot;&quot;
+        Get the next set of pending data for SSLRead from the internal buffer.
+
+        @param buf: buffer to read into
+        @type buf: L{ffi.buffer}
+        @param blen: maximum length to read
+        @type blen: L{int}
+
+        @return: the length actually read
+        @rtype: L{int}
+        &quot;&quot;&quot;
+        self.bytes = [&quot;&quot;.join(self.bytes)]
+        if len(self.bytes[0]) &gt;= blen:
+            buf[:] = self.bytes[0][:blen]
+            self.bytes[0] = self.bytes[0][blen:]
+            return blen
+        else:
+            return None
</ins></span></pre></div>
<a id="PySecureTransporttrunkOpenSSL__init__py"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/OpenSSL/__init__.py (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/OpenSSL/__init__.py                                (rev 0)
+++ PySecureTransport/trunk/OpenSSL/__init__.py        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,22 @@
</span><ins>+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from OpenSSL import crypto, SSL
+from OpenSSL.version import __version__
+
+__all__ = [
+    'crypto', 'SSL', '__version__'
+]
</ins></span></pre></div>
<a id="PySecureTransporttrunkOpenSSLcryptopy"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/OpenSSL/crypto.py (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/OpenSSL/crypto.py                                (rev 0)
+++ PySecureTransport/trunk/OpenSSL/crypto.py        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,272 @@
</span><ins>+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+&quot;&quot;&quot;
+An API compatible replace for pyOpenSSL's OpenSSL.crypto module that uses Security.frameowork.
+&quot;&quot;&quot;
+
+from osx._corefoundation import ffi, lib as security
+from osx.corefoundation import CFDictionaryRef, CFStringRef, CFArrayRef, \
+    CFBooleanRef, CFObjectRef, CFErrorRef
+
+userIDOID = &quot;0.9.2342.19200300.100.1.1&quot;
+
+OID2STR = {
+    str(CFStringRef.fromRef(security.kSecOIDCommonName)): &quot;CN&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDCountryName)): &quot;C&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDEmailAddress)): &quot;emailAddress&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDLocalityName)): &quot;L&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDOrganizationName)): &quot;O&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDOrganizationalUnitName)): &quot;OU&quot;,
+    str(CFStringRef.fromRef(security.kSecOIDStateProvinceName)): &quot;ST&quot;,
+    userIDOID: &quot;UID&quot;,
+}
+
+FILETYPE_PEM = 1
+FILETYPE_ASN1 = 2
+FILETYPE_DEFAULT = 3
+
+TYPE_RSA = 6
+TYPE_DSA = 116
+
+class Error(Exception):
+    &quot;&quot;&quot;
+    An error occurred in an `OpenSSL.crypto` API.
+    &quot;&quot;&quot;
+    pass
+
+
+
+class X509Name(object):
+    &quot;&quot;&quot;
+    Equivalent of an pyOpenSSL OpenSSL.crypto.X509Name object.
+    &quot;&quot;&quot;
+    def __init__(self, name, components=None):
+        self.name = name
+        self.components = components
+
+
+    def get_components(self):
+        return self.components.items()
+
+
+
+class X509(object):
+    &quot;&quot;&quot;
+    Equivalent of an pyOpenSSL OpenSSL.crypto.X509Name object, with many methods unimplemented.
+    &quot;&quot;&quot;
+
+    def __init__(self, certificate=None):
+        self.certificate = certificate
+
+
+    def set_version(self, version):
+        raise NotImplementedError
+
+
+    def get_version(self):
+        raise NotImplementedError
+
+
+    def get_pubkey(self):
+        raise NotImplementedError
+
+
+    def set_pubkey(self, pkey):
+        raise NotImplementedError
+
+
+    def sign(self, pkey, digest):
+        raise NotImplementedError
+
+
+    def get_signature_algorithm(self):
+        raise NotImplementedError
+
+
+    def digest(self, digest_name):
+        raise NotImplementedError
+
+
+    def subject_name_hash(self):
+        raise NotImplementedError
+
+
+    def set_serial_number(self, serial):
+        raise NotImplementedError
+
+
+    def get_serial_number(self):
+        raise NotImplementedError
+
+
+    def gmtime_adj_notAfter(self, amount):
+        raise NotImplementedError
+
+
+    def gmtime_adj_notBefore(self, amount):
+        raise NotImplementedError
+
+
+    def has_expired(self):
+        raise NotImplementedError
+
+
+    def get_notBefore(self):
+        raise NotImplementedError
+
+
+    def set_notBefore(self, when):
+        raise NotImplementedError
+
+
+    def get_notAfter(self):
+        raise NotImplementedError
+
+
+    def set_notAfter(self, when):
+        raise NotImplementedError
+
+
+    def _get_name(self, which):
+        raise NotImplementedError
+
+
+    def _set_name(self, which, name):
+        raise NotImplementedError
+
+
+    def get_issuer(self):
+        raise NotImplementedError
+
+
+    def set_issuer(self, issuer):
+        raise NotImplementedError
+
+
+    def get_subject(self):
+        &quot;&quot;&quot;
+        Use Security.framework to extract the componentized SubjectName field and map OID
+        values to strings and store in an L{X509Name} object.
+        &quot;&quot;&quot;
+        keys = CFArrayRef.fromList([CFStringRef.fromRef(security.kSecOIDX509V1SubjectName)])
+        error = ffi.new(&quot;CFErrorRef *&quot;)
+        values = security.SecCertificateCopyValues(self.certificate.ref(), keys.ref(), error)
+        if values == ffi.NULL:
+            error = CFErrorRef(error[0])
+            raise Error(&quot;Unable to get certificate subject&quot;)
+        values = CFDictionaryRef(values).toDict()
+        value = values[str(CFStringRef.fromRef(security.kSecOIDX509V1SubjectName))]
+
+        components = {}
+        if value[str(CFStringRef.fromRef(security.kSecPropertyKeyType))] == str(CFStringRef.fromRef(security.kSecPropertyTypeSection)):
+            for item in value[str(CFStringRef.fromRef(security.kSecPropertyKeyValue))]:
+                if item[str(CFStringRef.fromRef(security.kSecPropertyKeyType))] == str(CFStringRef.fromRef(security.kSecPropertyTypeString)):
+                    v = item[str(CFStringRef.fromRef(security.kSecPropertyKeyValue))]
+                    k = OID2STR.get(item[str(CFStringRef.fromRef(security.kSecPropertyKeyLabel))], &quot;Unknown&quot;)
+                    components[k] = v
+
+
+        return X509Name(&quot;Subject Name&quot;, components)
+
+
+    def set_subject(self, subject):
+        raise NotImplementedError
+
+
+    def get_extension_count(self):
+        raise NotImplementedError
+
+
+    def add_extensions(self, extensions):
+        raise NotImplementedError
+
+
+    def get_extension(self, index):
+        raise NotImplementedError
+
+
+
+def load_certificate(certtype, buffer):
+    &quot;&quot;&quot;
+    Load a certificate with the supplied identity string.
+
+    @param certtype: ignored
+    @type certtype: -
+    @param buffer: name of the KeyChain item to lookup
+    @type buffer: L{str}
+
+    @return: the certificate
+    @rtype: L{X509}
+    &quot;&quot;&quot;
+
+    # First try to get the identity from the KeyChain
+    name = CFStringRef.fromString(buffer)
+    certificate = security.SecCertificateCopyPreferred(name.ref(), ffi.NULL)
+    if certificate == ffi.NULL:
+        try:
+            identity = _getIdentityCertificate(buffer)
+        except Error:
+            raise Error(&quot;Certificate for preferred name '{}' was not found&quot;.format(buffer))
+        certificate = ffi.new(&quot;SecCertificateRef *&quot;)
+        err = security.SecIdentityCopyCertificate(identity.ref(), certificate)
+        if err != 0:
+            raise Error(&quot;Certificate for preferred name '{}' was not found&quot;.format(buffer))
+        certificate = certificate[0]
+    certificate = CFObjectRef(certificate)
+
+    return X509(certificate)
+
+
+
+def _getIdentityCertificate(subject):
+    &quot;&quot;&quot;
+    Retrieve a SecIdentityRef from the KeyChain with a subject that exactly matches the passed in value.
+
+    @param subject: subject value to match
+    @type subject: L{str}
+
+    @return: matched SecIdentityRef item or L{None}
+    @rtpe: L{CFObjectRef}
+    &quot;&quot;&quot;
+    match = CFDictionaryRef.fromDict({
+        CFStringRef.fromRef(security.kSecClass): CFStringRef.fromRef(security.kSecClassIdentity),
+        CFStringRef.fromRef(security.kSecReturnRef): CFBooleanRef.fromBool(True),
+        CFStringRef.fromRef(security.kSecReturnAttributes): CFBooleanRef.fromBool(True),
+        CFStringRef.fromRef(security.kSecMatchLimit): CFStringRef.fromRef(security.kSecMatchLimitAll),
+    })
+    result = ffi.new(&quot;CFTypeRef *&quot;)
+    err = security.SecItemCopyMatching(
+        match.ref(),
+        result
+    )
+    if err != 0:
+        return None
+
+    result = CFArrayRef(result[0])
+    for item in result.toList():
+        if item[str(CFStringRef.fromRef(security.kSecAttrLabel))] == subject:
+            identity = item[str(CFStringRef.fromRef(security.kSecValueRef))]
+            break
+    else:
+        raise Error(&quot;Certificate with id '{}' was not found in the KeyChain&quot;.format(subject))
+
+    return identity
+
+
+if __name__ == '__main__':
+    x = load_certificate(&quot;&quot;, &quot;APSP:d6e49079-75ba-4380-a2cd-a66191469145&quot;)
+    print(x.get_subject().get_components())
</ins></span></pre></div>
<a id="PySecureTransporttrunkOpenSSLversionpy"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/OpenSSL/version.py (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/OpenSSL/version.py                                (rev 0)
+++ PySecureTransport/trunk/OpenSSL/version.py        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,18 @@
</span><ins>+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+# Fake a pyOpenSSL version that is old
+__version__ = '0.0'
</ins></span></pre></div>
<a id="PySecureTransporttrunkREADME"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/README (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/README                                (rev 0)
+++ PySecureTransport/trunk/README        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,16 @@
</span><ins>+Getting Started
+===============
+
+OS X SecureTransport cffi based API that looks like pyOpenSSL.
+
+
+Copyright and License
+=====================
+
+Copyright (c) 2015 Apple Inc.  All rights reserved.
+
+This software is licensed under the Apache License, Version 2.0.  The
+Apache License is a well-established open source license, enabling
+collaborative open source software development.
+
+See the &quot;LICENSE&quot; file for the full text of the license terms.
</ins></span></pre></div>
<a id="PySecureTransporttrunksetuppy"></a>
<div class="addfile"><h4>Added: PySecureTransport/trunk/setup.py (0 => 15210)</h4>
<pre class="diff"><span>
<span class="info">--- PySecureTransport/trunk/setup.py                                (rev 0)
+++ PySecureTransport/trunk/setup.py        2015-10-21 20:10:47 UTC (rev 15210)
</span><span class="lines">@@ -0,0 +1,29 @@
</span><ins>+##
+#    Copyright (c) 2015 Cyrus Daboo. All rights reserved.
+#
+#    Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+##
+
+from distutils.core import setup
+
+setup(
+    name=&quot;PySecureTransport&quot;,
+    version=&quot;0.1&quot;,
+    description=&quot;SecureTransport API that mimics pyOpenSSL&quot;,
+    license=&quot;Apache 2.0&quot;,
+    platforms=[&quot;any&quot;],
+    package_dir={'OpenSSL': 'OpenSSL'},
+    packages=[
+        'OpenSSL',
+    ],
+)
</ins></span></pre>
</div>
</div>

</body>
</html>