You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@warble.apache.org by hu...@apache.org on 2018/06/25 22:35:09 UTC

[incubator-warble-node] branch master updated (e6bc4cc -> 0832848)

This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git.


    from e6bc4cc  fix formatting
     new e561bfa  py3.4 -> py3
     new 114c371  Add a basic crypto lib
     new 120d651  use crypto lib, ditch py version specificity
     new 0c9fbfb  add funcs for loading and exporting keys via PEM format
     new d89388f  on first run, gen a key pair for comms, save PEM
     new 954d970  update gitignore
     new 0832848  add in crypto tests

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .gitignore                 |   4 +-
 node.py                    |  32 +++++++-
 plugins/basics/__init__.py |   1 +
 plugins/basics/crypto.py   | 199 +++++++++++++++++++++++++++++++++++++++++++++
 plugins/basics/misc.py     |   2 +-
 plugins/basics/socket.py   |   2 +-
 plugins/tests/http.py      |   2 +-
 7 files changed, 235 insertions(+), 7 deletions(-)
 create mode 100644 plugins/basics/crypto.py


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 01/07: py3.4 -> py3

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit e561bfa9e6c5ccbf7ed5d4c28ad25d3a38f2cbd9
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 16:55:56 2018 -0500

    py3.4 -> py3
---
 plugins/basics/misc.py   | 2 +-
 plugins/basics/socket.py | 2 +-
 plugins/tests/http.py    | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/plugins/basics/misc.py b/plugins/basics/misc.py
index a59376b..d780d3c 100644
--- a/plugins/basics/misc.py
+++ b/plugins/basics/misc.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3.4
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Licensed to the Apache Software Foundation (ASF) under one or more
 # contributor license agreements.  See the NOTICE file distributed with
diff --git a/plugins/basics/socket.py b/plugins/basics/socket.py
index 860a058..8cd5f6e 100644
--- a/plugins/basics/socket.py
+++ b/plugins/basics/socket.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3.4
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Licensed to the Apache Software Foundation (ASF) under one or more
 # contributor license agreements.  See the NOTICE file distributed with
diff --git a/plugins/tests/http.py b/plugins/tests/http.py
index 687692d..3cc4daa 100644
--- a/plugins/tests/http.py
+++ b/plugins/tests/http.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3.4
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Licensed to the Apache Software Foundation (ASF) under one or more
 # contributor license agreements.  See the NOTICE file distributed with


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 02/07: Add a basic crypto lib

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit 114c371c5971032db6337c5a08f0c11689099f91
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 16:56:30 2018 -0500

    Add a basic crypto lib
---
 plugins/basics/__init__.py |   1 +
 plugins/basics/crypto.py   | 163 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 164 insertions(+)

diff --git a/plugins/basics/__init__.py b/plugins/basics/__init__.py
index 8f21a81..c9184a3 100644
--- a/plugins/basics/__init__.py
+++ b/plugins/basics/__init__.py
@@ -1,5 +1,6 @@
 import plugins.basics.socket
 import plugins.basics.misc
+import plugins.basics.crypto
 
 __all__ = [
     'misc',
diff --git a/plugins/basics/crypto.py b/plugins/basics/crypto.py
new file mode 100644
index 0000000..9902c54
--- /dev/null
+++ b/plugins/basics/crypto.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+
+""" This is the library for basic cryptographic features in
+    Apache Warble (incubating) nodes. It includes wrappers for
+    encrypting, decrypting, signing and verifying using RSA async key
+    pairs.
+    
+    NB: Ideally we'd use SHA256 for hashing, but as that still isn't
+    widely supported, we're resorting to SHA1 for now.
+"""
+
+import cryptography.hazmat.backends
+import cryptography.hazmat.primitives
+import cryptography.hazmat.primitives.asymmetric.rsa
+import cryptography.hazmat.primitives.asymmetric.utils
+import cryptography.hazmat.primitives.asymmetric.padding
+import cryptography.hazmat.primitives.hashes
+
+def keypair(bits = 4096):
+    """ Generate a private+public key pair for encryption/signing """
+    private_key = cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
+        public_exponent=65537,
+        key_size=bits, # Minimum hould be 4096, puhlease.
+        backend=cryptography.hazmat.backends.default_backend()
+    )
+    return private_key
+
+def decrypt(key, text):
+    """ Decrypt a message encrypted with the public key, by using the private key on-disk """
+    retval = b""
+    i = 0
+    txtl = len(text)
+    ks = int(key.key_size / 8) # bits -> bytes, room for padding
+    # Process the data in chunks the size of the key, as per the encryption
+    # model used below.
+    while i < txtl:
+        chunk = text[i:i+ks]
+        i += ks
+        ciphertext = key.decrypt(
+            chunk,
+            cryptography.hazmat.primitives.asymmetric.padding.OAEP(
+                mgf=cryptography.hazmat.primitives.asymmetric.padding.MGF1(
+                    algorithm=cryptography.hazmat.primitives.hashes.SHA1()
+                    ),
+                algorithm=cryptography.hazmat.primitives.hashes.SHA1(),
+                label=None
+            )
+        )
+        retval += ciphertext
+    return retval
+
+def encrypt(key, text):
+    """ Encrypt a message using the public key, for decryption with the private key """
+    retval = b""
+    i = 0
+    txtl = len(text)
+    ks = int(key.key_size / 8) - 64 # bits -> bytes, room for padding
+    # Process data in chunks no larger than the key, leave some room for padding.
+    while i < txtl:
+        chunk = text[i:i+ks-1]
+        i += ks
+        ciphertext = key.encrypt(
+            chunk.encode('utf-8'),
+            cryptography.hazmat.primitives.asymmetric.padding.OAEP(
+                mgf=cryptography.hazmat.primitives.asymmetric.padding.MGF1(
+                    algorithm=cryptography.hazmat.primitives.hashes.SHA1()
+                    ),
+                algorithm=cryptography.hazmat.primitives.hashes.SHA1(),
+                label=None
+            )
+        )
+        retval += ciphertext
+    return retval
+
+
+def sign(key, text):
+    """ Signs a string with the private key """
+    hashver = cryptography.hazmat.primitives.hashes.SHA1()
+    hasher = cryptography.hazmat.primitives.hashes.Hash(hashver, cryptography.hazmat.backends.default_backend())
+    retval = b""
+    i = 0
+    txtl = len(text)
+    ks = int(key.key_size / 8)
+    while i < txtl:
+        chunk = text[i:i+ks-1]
+        i += ks
+        hasher.update(chunk.encode('utf-8'))
+    digest = hasher.finalize()
+    sig = key.sign(
+        digest,
+        cryptography.hazmat.primitives.asymmetric.padding.PSS(
+            mgf=cryptography.hazmat.primitives.asymmetric.padding.MGF1(cryptography.hazmat.primitives.hashes.SHA1()),
+            salt_length=cryptography.hazmat.primitives.asymmetric.padding.PSS.MAX_LENGTH
+        ),
+        cryptography.hazmat.primitives.asymmetric.utils.Prehashed(hashver)
+    )
+    return sig
+
+def verify(key, sig, text):
+    """ Verifies a signature of a text using the public key """
+    hashver = cryptography.hazmat.primitives.hashes.SHA1()
+    hasher = cryptography.hazmat.primitives.hashes.Hash(hashver, cryptography.hazmat.backends.default_backend())
+    retval = b""
+    i = 0
+    txtl = len(text)
+    ks = int(key.key_size / 8)
+    while i < txtl:
+        chunk = text[i:i+ks-1]
+        i += ks
+        hasher.update(chunk.encode('utf-8'))
+    digest = hasher.finalize()
+    try:
+        key.verify(
+            sig,
+            digest,
+            cryptography.hazmat.primitives.asymmetric.padding.PSS(
+                mgf=cryptography.hazmat.primitives.asymmetric.padding.MGF1(cryptography.hazmat.primitives.hashes.SHA1()),
+                salt_length=cryptography.hazmat.primitives.asymmetric.padding.PSS.MAX_LENGTH
+            ),
+            cryptography.hazmat.primitives.asymmetric.utils.Prehashed(hashver)
+        )
+        return True
+    except cryptography.exceptions.InvalidSignature as err:
+        return False
+
+def test():
+    """ Tests for the crypto lib """
+    
+    # Generate a key pair, agree on a string to test with
+    privkey = keypair()
+    pubkey = privkey.public_key()
+    mystring = "Bob was here, his burgers were great."
+    
+    # Test encrypting
+    etxt = encrypt(pubkey, mystring)
+    
+    # Test decrypting
+    dtxt = decrypt(privkey, etxt)
+    assert(mystring == str(dtxt, 'utf-8'))
+    
+    # Test signing
+    xx = sign(privkey, mystring)
+    
+    # Test verification
+    assert( verify(pubkey, xx, mystring))
+    
+    print("Crypto lib works as intended!")
+


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 03/07: use crypto lib, ditch py version specificity

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit 120d6518916ddfe0ba0879b05eb3ffcd5588a8b2
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 16:57:07 2018 -0500

    use crypto lib, ditch py version specificity
---
 node.py | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/node.py b/node.py
index 4de0eeb..e58fe75 100644
--- a/node.py
+++ b/node.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3.4
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 # Licensed to the Apache Software Foundation (ASF) under one or more
 # contributor license agreements.  See the NOTICE file distributed with
@@ -31,10 +31,12 @@ import argparse
 # Warble-specific libraries
 import plugins.tests
 import plugins.basics.misc
+import plugins.basics.crypto
 
 basepath = os.path.dirname(os.path.realpath(__file__))
 configpath = "%s/conf/node.yaml" % basepath
 
+
 if __name__ == "__main__":
     
     parser = argparse.ArgumentParser(description = "Run-time configuration options for Apache Warble (incubating)")


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 07/07: add in crypto tests

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit 08328487e3601065447c963f82a91dbaa204ff8c
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 17:33:32 2018 -0500

    add in crypto tests
---
 node.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/node.py b/node.py
index 20b1014..5550c92 100644
--- a/node.py
+++ b/node.py
@@ -89,7 +89,10 @@ if __name__ == "__main__":
 
     # Unit test mode?
     if args.test:
-        print("Running tests...")
+        print("Testing crypto library")
+        plugins.basics.crypto.test()
+                
+        print("Running unit tests...")
         import plugins.basics.unittests
         gconf['version'] = _VERSION
         plugins.basics.unittests.run(gconf)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 06/07: update gitignore

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit 954d970113b34032b25f0eedf9cbface4e51699d
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 17:26:30 2018 -0500

    update gitignore
---
 .gitignore | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/.gitignore b/.gitignore
index c20c2ab..1f98712 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,4 @@
 __pycache__
-
+conf/*.pem
+conf/*.pub
+conf/*.yaml


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 04/07: add funcs for loading and exporting keys via PEM format

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit 0c9fbfbacc09e2d47f45dfeae6a1c3a282a5123d
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 17:22:41 2018 -0500

    add funcs for loading and exporting keys via PEM format
---
 plugins/basics/crypto.py | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/plugins/basics/crypto.py b/plugins/basics/crypto.py
index 9902c54..af662a9 100644
--- a/plugins/basics/crypto.py
+++ b/plugins/basics/crypto.py
@@ -26,6 +26,7 @@
 
 import cryptography.hazmat.backends
 import cryptography.hazmat.primitives
+import cryptography.hazmat.primitives.serialization
 import cryptography.hazmat.primitives.asymmetric.rsa
 import cryptography.hazmat.primitives.asymmetric.utils
 import cryptography.hazmat.primitives.asymmetric.padding
@@ -40,6 +41,41 @@ def keypair(bits = 4096):
     )
     return private_key
 
+def loadprivate(filepath):
+    """ Loads a private key from a file path """
+    with open(filepath, "rb") as key_file:
+        private_key = cryptography.hazmat.primitives.serialization.load_pem_private_key(
+            key_file.read(),
+            password=None,
+            backend=cryptography.hazmat.backends.default_backend()
+        )
+        return private_key
+
+def loadpublic(filepath):
+    """ Loads a public key from a file path """
+    with open(filepath, "rb") as key_file:
+        public_key = cryptography.hazmat.primitives.serialization.load_pem_public_key(
+            key_file.read(),
+            backend=cryptography.hazmat.backends.default_backend()
+        )
+        return public_key
+
+def pem(key):
+    """ Turn a key (public or private) into PEM format """
+    # Private key?
+    if hasattr(key, 'decrypt'):
+        return key.private_bytes(
+            encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
+            format=cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8,
+            encryption_algorithm=cryptography.hazmat.primitives.serialization.NoEncryption()
+         )
+    # Public key?
+    else:
+        return key.public_bytes(
+            encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
+            format=cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
+         )
+    
 def decrypt(key, text):
     """ Decrypt a message encrypted with the public key, by using the private key on-disk """
     retval = b""


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org


[incubator-warble-node] 05/07: on first run, gen a key pair for comms, save PEM

Posted by hu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

humbedooh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-warble-node.git

commit d89388f5053e03e4555827c8528bb73e2bfef497
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Mon Jun 25 17:25:25 2018 -0500

    on first run, gen a key pair for comms, save PEM
---
 node.py | 25 +++++++++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)

diff --git a/node.py b/node.py
index e58fe75..20b1014 100644
--- a/node.py
+++ b/node.py
@@ -36,7 +36,6 @@ import plugins.basics.crypto
 basepath = os.path.dirname(os.path.realpath(__file__))
 configpath = "%s/conf/node.yaml" % basepath
 
-
 if __name__ == "__main__":
     
     parser = argparse.ArgumentParser(description = "Run-time configuration options for Apache Warble (incubating)")
@@ -57,7 +56,7 @@ if __name__ == "__main__":
         else:
             print("Bork: --config passed to program, but could not find config file %s" % args.config)
             sys.exit(-1)
-        
+
     # Init yaml, load configuration.
     # We use ruamel.yaml here, because it preserves the existing structure and
     # comments, unlike the traditional yaml library.
@@ -66,6 +65,28 @@ if __name__ == "__main__":
     conftext = open(configpath).read()
     gconf = yaml.load(conftext)
     
+    # On first run, or in the case of removing/forgetting the encryption
+    # key pair, we need to generate a new pair for communication
+    # purposes. This requires read+write access to the conf/ dir. In
+    # subsequent runs, we can just load the existing (registered) key.
+    privkey = None
+    keypath = "%s/conf/privkey.pem" % basepath
+
+    # If key exists, load it...
+    if os.path.exists(keypath):
+        print("Loading private key from %s" % keypath)
+        privkey = plugins.basics.crypto.loadprivate(keypath)
+
+    # Otherwise, generate using the crypto lib and save in PEM format
+    else:
+        print("Generating 4096 bit async encryption key pair as %s..." % keypath)
+        privkey = plugins.basics.crypto.keypair(bits = 4096)
+        privpem = plugins.basics.crypto.pem(privkey)
+        with open(keypath, "wb") as f:
+            f.write(privpem)
+            f.close()
+        print("Key pair successfully generated and saved!")
+
     # Unit test mode?
     if args.test:
         print("Running tests...")


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@warble.apache.org
For additional commands, e-mail: commits-help@warble.apache.org