[CalendarServer-changes] [15210] PySecureTransport/trunk

source_changes at macosforge.org source_changes at macosforge.org
Wed Oct 21 13:10:47 PDT 2015


Revision: 15210
          http://trac.calendarserver.org//changeset/15210
Author:   cdaboo at apple.com
Date:     2015-10-21 13:10:47 -0700 (Wed, 21 Oct 2015)
Log Message:
-----------
Initial commit.

Added Paths:
-----------
    PySecureTransport/trunk/LICENSE
    PySecureTransport/trunk/OpenSSL/
    PySecureTransport/trunk/OpenSSL/SSL.py
    PySecureTransport/trunk/OpenSSL/__init__.py
    PySecureTransport/trunk/OpenSSL/crypto.py
    PySecureTransport/trunk/OpenSSL/version.py
    PySecureTransport/trunk/README
    PySecureTransport/trunk/setup.py

Property Changed:
----------------
    PySecureTransport/trunk/


Property changes on: PySecureTransport/trunk
___________________________________________________________________
Added: svn:ignore
   + .project
.pydevproject


Added: PySecureTransport/trunk/LICENSE
===================================================================
--- PySecureTransport/trunk/LICENSE	                        (rev 0)
+++ PySecureTransport/trunk/LICENSE	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" 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,
+      "control" 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.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" 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.
+
+      "Work" 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).
+
+      "Derivative Works" 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.
+
+      "Contribution" 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, "submitted"
+      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 "Not a Contribution."
+
+      "Contributor" 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 "NOTICE" 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 "AS IS" 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 "[]"
+      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 "printed page" 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 "License");
+   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 "AS IS" 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.

Added: PySecureTransport/trunk/OpenSSL/SSL.py
===================================================================
--- PySecureTransport/trunk/OpenSSL/SSL.py	                        (rev 0)
+++ PySecureTransport/trunk/OpenSSL/SSL.py	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,489 @@
+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# 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 "AS IS" 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.
+##
+
+"""
+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.
+"""
+
+from osx._corefoundation import ffi, lib as security
+from osx.corefoundation import CFArrayRef
+
+from OpenSSL.crypto import _getIdentityCertificate
+
+
+class Error(Exception):
+    """
+    An error occurred in an `OpenSSL.SSL` API.
+    """
+    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):
+    """
+    Equivalent of an pyOpenSSL OpenSSL.SSL.Context object, with many of the methods stubbed out.
+    """
+
+    def __init__(self, method):
+        """
+        The L{method} value is actually ignored for SecureTransport.
+
+        @param method: one of the *_METHOD values
+        @type method: L{int}
+        """
+        self.method = method
+        self.identity = None
+        self.options = set()
+
+
+    def set_options(self, option):
+        """
+        Add an option to this context.
+
+        @param option: the OP_* value to add
+        @type option: L{int}
+        """
+        self.options.add(option)
+
+
+    def use_certificate_file(self, certificateFileName):
+        """
+        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}
+        """
+        if self.identity is None and certificateFileName:
+            self.identity = _getIdentityCertificate(certificateFileName)
+
+
+    def use_privatekey_file(self, privateKeyFileName):
+        """
+        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}
+        """
+        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):
+        """
+        We are going to rely on SecureTransport's own KeyChain based verification rather than overriding with
+        our own.
+        """
+        pass
+
+
+    def set_verify_depth(self, depth):
+        """
+        We are going to rely on SecureTransport's own KeyChain based verification rather than overriding with
+        our own.
+        """
+        pass
+
+
+    def add_client_ca(self, certificate_authority):
+        pass
+
+
+
+class Connection(object):
+    """
+    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.
+    """
+
+    engines = {}
+    next_engine_id = 1
+
+    def __init__(self, context, socket=None):
+        """
+        @param context: the context to use for the connection settings
+        @type context: L{Context}
+        @param socket: ignored
+        @type socket: L{None}
+        """
+        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):
+        """
+        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}
+        """
+        self.protocol = protocol
+
+
+    def set_connect_state(self):
+        """
+        Called when a client connection needs to be initiated.
+        """
+        self.is_client = True
+        self.connect()
+
+
+    def set_accept_state(self):
+        """
+        Called when a server connection needs to be initiated.
+        """
+        self.is_client = False
+        self.connect()
+
+
+    @staticmethod
+    @ffi.callback("OSStatus (*) ( SSLConnectionRef connection, void *data, size_t *dataLength )")
+    def _read(fdptr, data, dataLength):
+        """
+        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 *)
+        """
+
+        # Get the associated L{Connection} object
+        engine_id = ffi.cast("int *", 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("OSStatus (*) ( SSLConnectionRef connection, const void *data, size_t *dataLength )")
+    def _write(fdptr, data, dataLength):
+        """
+        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 *)
+        """
+
+        # Get the associated L{Connection} object
+        engine_id = ffi.cast("int *", 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):
+        """
+        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}
+        """
+
+        read = ffi.new("char[]", bytes)
+        processed = ffi.new("size_t *")
+        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):
+        """
+        Wrapper for SecureTransport SSLWrite method.
+
+        @param data: data to write
+        @type data: L{str}
+        """
+
+        processed = ffi.new("size_t *")
+        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):
+        """
+        Create the SecureTransport SSLContextRef object and initialize it.
+        """
+
+        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("int *", self.engine_id)
+        err = security.SSLSetConnection(self.ctx, ffi.cast("SSLConnectionRef", 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("No certificate")
+
+        # 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):
+        """
+        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.
+        """
+        if self.ctx is None:
+            raise Error("No context")
+        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 ("null",)
+
+
+    def shutdown(self):
+        """
+        Wrapper for SecureTransport SSLCLose method
+        """
+        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):
+        """
+        We always send immediately so there is nothing to do here.
+        """
+        raise WantReadError
+
+
+    def bio_write(self, bytes):
+        """
+        Just append to our internal buffer so that the next SSLRead will can retrieve the "raw" SSL bytes
+        from the buffer and decode them into actual "application" data.
+
+        @param bytes: data to write
+        @type bytes: L{str}
+        """
+        self.bytes.append(bytes)
+
+
+    def bio_shutdown(self):
+        self.shutdown()
+
+
+    def recv(self, bytes):
+        """
+        Retrieve application level data from SSL.
+        """
+        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):
+        """
+        Send application level data to SSL.
+        """
+        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):
+        """
+        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}
+        """
+        self.bytes = ["".join(self.bytes)]
+        if len(self.bytes[0]) >= blen:
+            buf[:] = self.bytes[0][:blen]
+            self.bytes[0] = self.bytes[0][blen:]
+            return blen
+        else:
+            return None

Added: PySecureTransport/trunk/OpenSSL/__init__.py
===================================================================
--- PySecureTransport/trunk/OpenSSL/__init__.py	                        (rev 0)
+++ PySecureTransport/trunk/OpenSSL/__init__.py	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,22 @@
+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# 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 "AS IS" 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__'
+]

Added: PySecureTransport/trunk/OpenSSL/crypto.py
===================================================================
--- PySecureTransport/trunk/OpenSSL/crypto.py	                        (rev 0)
+++ PySecureTransport/trunk/OpenSSL/crypto.py	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,272 @@
+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# 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 "AS IS" 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.
+##
+
+"""
+An API compatible replace for pyOpenSSL's OpenSSL.crypto module that uses Security.frameowork.
+"""
+
+from osx._corefoundation import ffi, lib as security
+from osx.corefoundation import CFDictionaryRef, CFStringRef, CFArrayRef, \
+    CFBooleanRef, CFObjectRef, CFErrorRef
+
+userIDOID = "0.9.2342.19200300.100.1.1"
+
+OID2STR = {
+    str(CFStringRef.fromRef(security.kSecOIDCommonName)): "CN",
+    str(CFStringRef.fromRef(security.kSecOIDCountryName)): "C",
+    str(CFStringRef.fromRef(security.kSecOIDEmailAddress)): "emailAddress",
+    str(CFStringRef.fromRef(security.kSecOIDLocalityName)): "L",
+    str(CFStringRef.fromRef(security.kSecOIDOrganizationName)): "O",
+    str(CFStringRef.fromRef(security.kSecOIDOrganizationalUnitName)): "OU",
+    str(CFStringRef.fromRef(security.kSecOIDStateProvinceName)): "ST",
+    userIDOID: "UID",
+}
+
+FILETYPE_PEM = 1
+FILETYPE_ASN1 = 2
+FILETYPE_DEFAULT = 3
+
+TYPE_RSA = 6
+TYPE_DSA = 116
+
+class Error(Exception):
+    """
+    An error occurred in an `OpenSSL.crypto` API.
+    """
+    pass
+
+
+
+class X509Name(object):
+    """
+    Equivalent of an pyOpenSSL OpenSSL.crypto.X509Name object.
+    """
+    def __init__(self, name, components=None):
+        self.name = name
+        self.components = components
+
+
+    def get_components(self):
+        return self.components.items()
+
+
+
+class X509(object):
+    """
+    Equivalent of an pyOpenSSL OpenSSL.crypto.X509Name object, with many methods unimplemented.
+    """
+
+    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):
+        """
+        Use Security.framework to extract the componentized SubjectName field and map OID
+        values to strings and store in an L{X509Name} object.
+        """
+        keys = CFArrayRef.fromList([CFStringRef.fromRef(security.kSecOIDX509V1SubjectName)])
+        error = ffi.new("CFErrorRef *")
+        values = security.SecCertificateCopyValues(self.certificate.ref(), keys.ref(), error)
+        if values == ffi.NULL:
+            error = CFErrorRef(error[0])
+            raise Error("Unable to get certificate subject")
+        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))], "Unknown")
+                    components[k] = v
+
+
+        return X509Name("Subject Name", 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):
+    """
+    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}
+    """
+
+    # 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("Certificate for preferred name '{}' was not found".format(buffer))
+        certificate = ffi.new("SecCertificateRef *")
+        err = security.SecIdentityCopyCertificate(identity.ref(), certificate)
+        if err != 0:
+            raise Error("Certificate for preferred name '{}' was not found".format(buffer))
+        certificate = certificate[0]
+    certificate = CFObjectRef(certificate)
+
+    return X509(certificate)
+
+
+
+def _getIdentityCertificate(subject):
+    """
+    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}
+    """
+    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("CFTypeRef *")
+    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("Certificate with id '{}' was not found in the KeyChain".format(subject))
+
+    return identity
+
+
+if __name__ == '__main__':
+    x = load_certificate("", "APSP:d6e49079-75ba-4380-a2cd-a66191469145")
+    print(x.get_subject().get_components())

Added: PySecureTransport/trunk/OpenSSL/version.py
===================================================================
--- PySecureTransport/trunk/OpenSSL/version.py	                        (rev 0)
+++ PySecureTransport/trunk/OpenSSL/version.py	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,18 @@
+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# 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 "AS IS" 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'

Added: PySecureTransport/trunk/README
===================================================================
--- PySecureTransport/trunk/README	                        (rev 0)
+++ PySecureTransport/trunk/README	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,16 @@
+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 "LICENSE" file for the full text of the license terms.

Added: PySecureTransport/trunk/setup.py
===================================================================
--- PySecureTransport/trunk/setup.py	                        (rev 0)
+++ PySecureTransport/trunk/setup.py	2015-10-21 20:10:47 UTC (rev 15210)
@@ -0,0 +1,29 @@
+##
+#    Copyright (c) 2015 Cyrus Daboo. All rights reserved.
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    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 "AS IS" 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="PySecureTransport",
+    version="0.1",
+    description="SecureTransport API that mimics pyOpenSSL",
+    license="Apache 2.0",
+    platforms=["any"],
+    package_dir={'OpenSSL': 'OpenSSL'},
+    packages=[
+        'OpenSSL',
+    ],
+)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20151021/d01f05dc/attachment-0001.html>


More information about the calendarserver-changes mailing list