Exemplo n.º 1
0
    def setUpClass(cls):
        cls.g_config = {}
        with open("../src/config/config.json") as j:
            cls.g_config = json.load(j)

        wkh = WellKnownHandler(cls.g_config["auth_server_url"], secure=False)
        cls.__TOKEN_ENDPOINT = wkh.get(TYPE_OIDC, KEY_OIDC_TOKEN_ENDPOINT)

        _rsajwk = RSAKey(kid="RSA1",
                         key=import_rsa_key_from_file("../src/private.pem"))
        _payload = {
            "iss": cls.g_config["client_id"],
            "sub": cls.g_config["client_id"],
            "aud": cls.__TOKEN_ENDPOINT,
            "user_name": "admin",
            "jti": datetime.datetime.today().strftime('%Y%m%d%s'),
            "exp": int(time.time()) + 3600,
            "isOperator": False
        }
        _jws = JWS(_payload, alg="RS256")

        cls.jwt = _jws.sign_compact(keys=[_rsajwk])

        cls.scopes = 'protected_access'
        cls.PDP_HOST = "http://" + cls.g_config["host"]
        cls.PDP_PORT = cls.g_config["port"]
        cls.UID = cls.g_config["client_id"]
Exemplo n.º 2
0
    def test_jws(self):
        keys = [
            SYMKey(key=TestMDQHandler.SYM_KEY_PHRASE, alg="HS256"),
            RSAKey(key=import_rsa_key_from_file(
                full_test_path("test_data/certs/rsa2048.pub"))),
            TestMDQHandler.EC_KEY
        ]

        # Test support for algorithms with supplied keys are working
        for alg in TestMDQHandler.SIGNING_ALGS_SUPPORTED:
            response = requests.get(
                TestMDQHandler.URL,
                params={MDQHandler.SIGNING_ALG_QUERY_PARAM: alg},
                headers=TestMDQHandler.HEADERS)

            payload = JWS().verify_compact(response.text, keys)
            assert json.loads(payload) == TestMDQHandler.METADATA_FROM_FILE[
                TestMDQHandler.CLIENT_ID]

        # Unsupported signing algorithm
        response = requests.get(
            TestMDQHandler.URL,
            params={MDQHandler.SIGNING_ALG_QUERY_PARAM: "PS256"},
            headers=TestMDQHandler.HEADERS)
        assert response.status_code == 400

        # Request signing with MDQ server without keys
        TestMDQHandler.MDQ = MDQHandler(TestMDQHandler.file_name, 36000)
        response = requests.get(
            TestMDQHandler.URL,
            params={MDQHandler.SIGNING_ALG_QUERY_PARAM: "PS256"},
            headers=TestMDQHandler.HEADERS)
        assert response.status_code == 400
Exemplo n.º 3
0
    def verify_JWT_token(self, token, key):
        try:
            header = str(token).split(".")[0]
            paddedHeader = header + '=' * (4 - len(header) % 4)
            decodedHeader = base64.b64decode(paddedHeader)
            #to remove byte-code
            decodedHeader_format = decodedHeader.decode('utf-8')
            decoded_str_header = json.loads(decodedHeader_format)

            payload = str(token).split(".")[1]
            paddedPayload = payload + '=' * (4 - len(payload) % 4)
            decoded = base64.b64decode(paddedPayload)
            #to remove byte-code
            decoded = decoded.decode('utf-8')
            decoded_str = json.loads(decoded)

            if self.getVerificationConfig() == True:
                if decoded_str_header['kid'] != "RSA1":
                    verificator = JWT_Verification()
                    result = verificator.verify_signature_JWT(token)
                else:
                    #validate signature for rpt
                    rsajwk = RSAKey(
                        kid="RSA1",
                        key=import_rsa_key_from_file("config/public.pem"))
                    dict_rpt_values = JWS().verify_compact(token,
                                                           keys=[rsajwk],
                                                           sigalg="RS256")

                    if dict_rpt_values == decoded_str:
                        result = True
                    else:
                        result = False

                if result == False:
                    self.logger.debug(
                        "Verification of the signature for the JWT failed!")
                    raise Exception
                else:
                    self.logger.debug("Signature verification is correct!")

            user_value = None
            if decoded_str.get(key):
                user_value = decoded_str[key]
            elif decoded_str.get("pct_claims"):
                if decoded_str.get("pct_claims").get(key):
                    user_value = decoded_str['pct_claims'][key]
            if isinstance(user_value,
                          list) and len(user_value) != 0 and user_value[0]:
                user_value = user_value[0]
            if user_value is None:
                raise Exception

            return user_value
        except Exception as e:
            self.logger.debug(
                "Authenticated RPT Resource. No Valid JWT id token passed! " +
                str(e))
            return None
Exemplo n.º 4
0
def test_serialize_rsa_priv_key():
    rsakey = RSAKey(key=import_rsa_key_from_file(full_path("rsa.key")))
    assert rsakey.d

    d_rsakey = rsakey.serialize(private=True)
    restored_key = RSAKey(**d_rsakey)

    assert rsa_eq(restored_key, rsakey)
Exemplo n.º 5
0
def test_serialize_rsa_priv_key():
    rsakey = RSAKey(key=import_rsa_key_from_file(full_path("rsa.key")))
    assert rsakey.d

    d_rsakey = rsakey.serialize(private=True)
    restored_key = RSAKey(**d_rsakey)

    assert rsa_eq(restored_key, rsakey)
Exemplo n.º 6
0
def test_signer_ps384():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS384")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS()
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 7
0
def test_signer_ps384():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS384")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS()
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 8
0
def test_signer_ps512():
    payload = "Please take a moment to register today"
    # Key has to be big enough  > 512+512+2
    keys = [RSAKey(key=import_rsa_key_from_file(full_path("./size2048.key")))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS512")
    _jwt = _jws.sign_compact(keys)

    _rj = factory(_jwt)
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 9
0
def test_signer_ps512():
    payload = "Please take a moment to register today"
    # Key has to be big enough  > 512+512+2
    keys = [RSAKey(key=import_rsa_key_from_file(full_path("./size2048.key")))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS521")
    _jwt = _jws.sign_compact(keys)

    _rj = JWS()
    info = _rj.verify_compact(_jwt, keys)
    assert info == payload
Exemplo n.º 10
0
def test():
    # The needed key is the private key, not for encryption but for decryption
    _key = import_rsa_key_from_file("mykey.pem")

    idp_conf = config_factory("idp", "idp_conf")

    generate_metadata = MetadataGeneration(idp_proxy_conf.SERVICE, _key,
                                           idp_conf, idp_conf.xmlsec_path)

    sps = idp_conf.metadata.service_providers()
    qs = {
        "entityId": sps[0],
        "secret": {
            "Google": {
                "key": "lingon",
                "secret": "aaaaa"
            },
            "Facebook": {
                "key": "hallon",
                "secret": "bbbbb"
            },
            "Twitter": {
                "key": "jordgubb",
                "secret": "ccccc"
            }
        }
    }

    res = generate_metadata.handle_metadata_save(
        {
            'wsgi.url_scheme': "https",
            'HTTP_HOST': "example.com"
        }, None, qs)

    s = res[0].index("<mdattr:EntityAttributes")
    e = res[0].index("</mdattr:EntityAttributes>")

    snippet = res[0][s:e + len("</mdattr:EntityAttributes>")]

    entity_attributes = mdattr.entity_attributes_from_string(snippet)

    entdescr = idp_conf.metadata.metadata["./sp/sp.xml"].entity_descr

    ext = element_to_extension_element(entity_attributes)
    entdescr.spsso_descriptor[0].extensions.extension_elements.append(ext)
    print entity_attributes

    qs = {secret.CONST_BODY: json.dumps({"xml": "%s" % entdescr})}

    generate_metadata.handle_metadata_verify_json(
        {
            'wsgi.url_scheme': "https",
            'HTTP_HOST': "example.com"
        }, None, qs)
Exemplo n.º 11
0
def test_signer_ps256_fail():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS256")
    _jwt = _jws.sign_compact(keys)[:-1] + "a"

    _rj = JWS()
    try:
        _rj.verify_compact(_jwt, keys)
    except jwkest.BadSignature:
        pass
    else:
        assert False
Exemplo n.º 12
0
def test_signer_ps256_fail():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    #keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS256")
    _jwt = _jws.sign_compact(keys)[:-5] + 'abcde'

    _rj = JWS()
    try:
        _rj.verify_compact(_jwt, keys)
    except jwkest.BadSignature:
        pass
    else:
        assert False
Exemplo n.º 13
0
def test():
    # The needed key is the private key, not for encryption but for decryption
    _key = import_rsa_key_from_file("mykey.pem")

    idp_conf = config_factory("idp", "idp_conf")

    generate_metadata = MetadataGeneration(
        idp_proxy_conf.SERVICE, _key, idp_conf,
        idp_conf.xmlsec_path)

    sps = idp_conf.metadata.service_providers()
    qs = {
        "entityId": sps[0],
        "secret": {
            "Google": {
                "key": "lingon",
                "secret": "aaaaa"},
            "Facebook": {
                "key": "hallon",
                "secret": "bbbbb"},
            "Twitter":  {
                "key": "jordgubb",
                "secret": "ccccc"}
        }
    }

    res = generate_metadata.handle_metadata_save({'wsgi.url_scheme': "https",
                                                  'HTTP_HOST': "example.com"},
                                                 None, qs)

    s = res[0].index("<mdattr:EntityAttributes")
    e = res[0].index("</mdattr:EntityAttributes>")

    snippet = res[0][s:e+len("</mdattr:EntityAttributes>")]

    entity_attributes = mdattr.entity_attributes_from_string(snippet)

    entdescr = idp_conf.metadata.metadata["./sp/sp.xml"].entity_descr

    ext = element_to_extension_element(entity_attributes)
    entdescr.spsso_descriptor[0].extensions.extension_elements.append(ext)
    print entity_attributes

    qs = {secret.CONST_BODY: json.dumps({"xml": "%s" % entdescr})}

    generate_metadata.handle_metadata_verify_json({'wsgi.url_scheme':"https",
                                                  'HTTP_HOST': "example.com"},
                                                  None, qs)
Exemplo n.º 14
0
 def __create_jwt(self):
     if self.jks_path != None:
         _rsajwk = RSAKey(kid=self._kid,
                          key=import_rsa_key_from_file(self.jks_path))
     else:
         _rsajwk = RSAKey(kid=self._kid,
                          key=import_rsa_key(self.__getRSAPrivateKey()))
     _payload = {
         "iss": self.client_id,
         "sub": self.client_id,
         "aud": self.__TOKEN_ENDPOINT,
         "jti": datetime.datetime.today().strftime('%Y%m%d%s'),
         "exp": int(time.time()) + 3600
     }
     _jws = JWS(_payload, alg="RS256")
     return _jws.sign_compact(keys=[_rsajwk])
Exemplo n.º 15
0
def test_rs256_rm_signature():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="RS256")
    _jwt = _jws.sign_compact(keys)

    p = _jwt.split('.')
    _jwt = '.'.join(p[:-1])

    _rj = JWS()
    try:
        _ = _rj.verify_compact(_jwt, keys)
    except jwkest.WrongNumberOfParts:
        pass
    else:
        assert False
Exemplo n.º 16
0
def test_rs256_rm_signature():
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY))]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="RS256")
    _jwt = _jws.sign_compact(keys)

    p = _jwt.split('.')
    _jwt = '.'.join(p[:-1])

    _rj = JWS()
    try:
        _ = _rj.verify_compact(_jwt, keys)
    except jwkest.WrongNumberOfParts:
        pass
    else:
        assert False
Exemplo n.º 17
0
def deploy_default_resources():
    try:
        path = g_config["default_resource_path"]
        kube_resources= get_default_resources(path)
        if(not kube_resources):
            logger.info("==========No Default resources detected==========")
            return
        logger.info("==========Default resources operation started==========")
        for k in kube_resources['default_resources']:
            try:
                id_res=""
                owship=None
                if "default_owner" in k:
                    owship=k["default_owner"]
                else:
                    owship="0000000000000"
                _rsajwk = RSAKey(kid="RSA1", key=import_rsa_key_from_file("config/private.pem"))
                _payload_ownership = { 
                    "iss": g_config["client_id"],
                    "sub": str(owship),
                    "aud": "",
                    "user_name": "admin",
                    "jti": datetime.datetime.today().strftime('%Y%m%d%s'),
                    "exp": int(time.time())+3600,
                    "isOperator": True
                }
                _jws_ownership = JWS(_payload_ownership, alg="RS256")
                jwt = _jws_ownership.sign_compact(keys=[_rsajwk])
                headers = { 'content-type': "application/json", "Authorization": "Bearer "+ str(jwt) }
                payload = { "resource_scopes": k["scopes"], "icon_uri": k["resource_uri"], "name":k["name"], "description":k["description"] }
                res = post("http://"+g_config["service_host"]+":"+str(g_config["resources_service_port"])+"/resources", headers=headers, json=payload, verify=False)
                id_res = res.text
                logger.info("==========New Resource for URI: \""+k["resource_uri"]+"\" with ID: \""+id_res+"\"==========")
            except Exception as e:
                logger.info("==========Default resources operation threw an exception for resource "+k["name"]+"==========")
                logger.info(str(e))
        logger.info("==========Default resources operation completed==========")
            
    except Exception as e:
        
        logger.info("==========Couldnt process the default resources==========")
        logger.info("==========Reason: "+str(e)+"==========")
Exemplo n.º 18
0
    def setUpClass(cls):
        cls.g_config = {}
        with open("../src/config/config.json") as j:
            cls.g_config = json.load(j)

        wkh = WellKnownHandler(cls.g_config["auth_server_url"], secure=False)
        cls.__TOKEN_ENDPOINT = wkh.get(TYPE_OIDC, KEY_OIDC_TOKEN_ENDPOINT)

        _rsajwk = RSAKey(
            kid="RSA1",
            key=import_rsa_key_from_file("../src/config/private.pem"))
        _payload = {
            "iss": cls.g_config["client_id"],
            "sub": cls.g_config["client_id"],
            "aud": cls.__TOKEN_ENDPOINT,
            "user_name": "admin",
            "jti": datetime.datetime.today().strftime('%Y%m%d%s'),
            "exp": int(time.time()) + 3600,
            "isOperator": False
        }
        _jws = JWS(_payload, alg="RS256")

        _payload_ownership = {
            "iss": cls.g_config["client_id"],
            "sub": "54d10251-6cb5-4aee-8e1f-f492f1105c94",
            "aud": cls.__TOKEN_ENDPOINT,
            "user_name": "admin",
            "jti": datetime.datetime.today().strftime('%Y%m%d%s'),
            "exp": int(time.time()) + 3600,
            "isOperator": False
        }
        _jws_ownership = JWS(_payload_ownership, alg="RS256")

        cls.jwt = _jws.sign_compact(keys=[_rsajwk])
        cls.jwt_rotest = _jws_ownership.sign_compact(keys=[_rsajwk])
        #cls.scopes = 'public_access'
        cls.scopes = 'protected_access'
        cls.resourceName = "TestResourcePEP"
        cls.PEP_HOST = "http://localhost:5566"
        cls.PEP_RES_HOST = "http://localhost:5576"
Exemplo n.º 19
0
    def setUpClass(cls):
        cls.file_name = full_test_path("test_data/clients.json")
        with open(full_test_path("test_data/clients.json")) as f:
            cls.METADATA_FROM_FILE = json.load(f)

        sym_key = SYMKey(key=TestMDQHandler.SYM_KEY_PHRASE)
        rsa_key = RSAKey(key=import_rsa_key_from_file(
            full_test_path("test_data/certs/rsa2048")))
        cls.EC_KEY = ECKey().load_key(P256)

        signing_keys = {
            "HS256": sym_key,
            "RS256": rsa_key,
            "ES256": cls.EC_KEY
        }

        cls.SIGNING_ALGS_SUPPORTED = signing_keys.keys()
        cls.MDQ = MDQHandler(cls.file_name, 36000, signing_keys)

        cherrypy.config.update({"environment": "test_suite"})
        cherrypy.server.socket_host = "0.0.0.0"
        cherrypy.server.socket_port = cls.SERVER_PORT
        cherrypy.tree.mount(cls.MDQ, "/", CHERRYPY_CONFIG)
        cherrypy.engine.start()
Exemplo n.º 20
0
    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = load_jwks_from_url(args.jwk_url, {})
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        # load_x509_cert returns list of 2-tuples
        keys = [RSAKey(key=x) for x, y in load_x509_cert(lrequest,
                                                         args.x509_url)]
        for key in keys:
            key.serialize()
    elif args.x509_file:
        # import_rsa_key_from_file returns RSA key instance
        _key = RSAKey(key=import_rsa_key_from_file(args.x509_file))
        _key.serialize()
        keys = [_key]
    elif args.rsa_file:
        _key = RSAKey(key=rsa_load(args.rsa_file))
        _key.serialize()
        keys = [_key]
    else:
        print >> sys.stderr, "Needs encryption key"
        exit()

    if not args.enc or not args.alg:
        print >> sys.stderr, "There are no default encryption methods"
        exit()

    if args.enc not in SUPPORTED["enc"]:
Exemplo n.º 21
0
from jwkest.jws import JWS
from jwkest.jwk import RSAKey, import_rsa_key_from_file
from tower import ugettext_lazy as _lazy

import amo
from amo.utils import paginate, urlparams
from mkt.constants import apps
from mkt.purchase.models import Contribution
from mkt.site.helpers import absolutify
from mkt.site.models import manual_order
from mkt.translations.query import order_by_translation
from mkt.webapps.models import Webapp
from mkt.webapps.views import BaseFilter


PREVERIFY_KEY = RSAKey(key=import_rsa_key_from_file(
    settings.PREVERIFIED_ACCOUNT_KEY), kid=1)


def get_token_expiry(expiry):
    expire_time = datetime.datetime.now() + expiry
    return time.mktime(expire_time.timetuple())


def fxa_preverify_token(user, expiry):
    """
    Takes a user and a timedelta and generates a preverify token for FxA OAuth.
    See https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#preverifytoken
    for details.
    """
    msg = {
        'exp': get_token_expiry(expiry),
Exemplo n.º 22
0
    keys = {}
    if args.jwk_url:
        keys = load_jwks_from_url(args.jwk_url, {})
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        # load_x509_cert returns list of 2-tuples
        keys = [
            RSAKey(key=x) for x, y in load_x509_cert(lrequest, args.x509_url)
        ]
        for key in keys:
            key.serialize()
    elif args.x509_file:
        # import_rsa_key_from_file returns RSA key instance
        _key = RSAKey(key=import_rsa_key_from_file(args.x509_file))
        _key.serialize()
        keys = [_key]
    elif args.rsa_file:
        _key = RSAKey(key=rsa_load(args.rsa_file))
        _key.serialize()
        keys = [_key]
    else:
        print >> sys.stderr, "Needs encryption key"
        exit()

    if not args.enc or not args.alg:
        print >> sys.stderr, "There are no default encryption methods"
        exit()

    if args.enc not in SUPPORTED["enc"]:
Exemplo n.º 23
0
# create one. On linux, just type in the project folder the following command:
# $ ssh-keygen -t rsa -b 4096
# and provide the foo filename with requested.
#
# Now a JWS can be created as follow:
# - retrieve the rsa key (the example below will also print it in the JWK section)
# - use the JWS object to create the token specifying the algorithm to be used for signing
# - call the method sign_compact providing an array of keys (eventually containing 1 key only) to be used for signing
# - the example belows shows the content of the JWT, by printing it
# - the signature can be verified with the method verify_compact (of course providing the same keys used for signing)

payload = {"iss": "jow",
           "exp": 1300819380,
           "http://example.com/is_root": True}

keys = [RSAKey(key=import_rsa_key_from_file("foo"))]
jws = JWS(payload, alg="RS512").sign_compact(keys)
print "jwt signed:", jws
print

########################################

jwt_received = JWT()
jwt_received.unpack(jws)
print "jwt headers:", jwt_received.headers
print "jwt part 1:", jwt_received.part[1]
print

_rj = JWS()
info = _rj.verify_compact(jws, keys)
print "Verified info:", info
Exemplo n.º 24
0
def test_pick_alg_dont_get_alg_from_single_key_if_already_specified():
    expected_alg = "RS512"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY), alg="RS256")]

    alg = JWS(alg=expected_alg)._pick_alg(keys)
    assert alg == expected_alg
Exemplo n.º 25
0
def test_pick_alg_dont_get_alg_from_single_key_if_already_specified():
    expected_alg = "RS512"
    keys = [RSAKey(key=import_rsa_key_from_file(KEY), alg="RS256")]

    alg = JWS(alg=expected_alg)._pick_alg(keys)
    assert alg == expected_alg
Exemplo n.º 26
0
    parser.add_argument('-j', dest="jwk", help="JSON Web Key")
    parser.add_argument('-J', dest="jwks", help="JSON Web Keys")
    parser.add_argument('-i', dest="kid", help="key id")
    parser.add_argument('-l', dest="log", help="logfile name")
    parser.add_argument("message", nargs="?", help="The message")

    args = parser.parse_args()

    if args.log:
        setup_logging(args.log)

    _kid = args.kid
    keys = []
    if args.rsa_file:
        keys.append(
            RSAKey(key=import_rsa_key_from_file(args.rsa_file), kid=_kid))
    if args.hmac_key:
        keys.append(SYMKey(key=args.hmac_key))

    if args.jwk:
        kspec = json.loads(open(args.jwk).read())
        keys.append(keyrep(kspec))

    if args.jwks:
        txt = open(args.jwks).read()
        keys.extend(jwks_load(txt))

    if not keys:
        exit(-1)

    if args.msg_file:
Exemplo n.º 27
0
                         help="Print runtime information")
    _parser.add_argument('-r', dest="rsa_file",
                         help="A file containing a RSA key")
    _parser.add_argument('-p', dest="rsa_public_file",
                         help="A file containing a public RSA key")
    _parser.add_argument("config", nargs="?", help="Server configuration")

    args = _parser.parse_args()

    if args.rsa_file:
        key = rsa_load(args.rsa_file)
    else:
        key = None

    if args.rsa_file:
        _key = import_rsa_key_from_file(args.rsa_file)
    elif args.rsa_public_file:
        _key = import_rsa_key_from_file(args.rsa_public_file)
    else:
        _key = None

    #noinspection PyUnboundLocalVariable
    _idp = setup_server_env(idp_proxy_conf, args.config, key)

    if _key:
        GENERATE_METADATA = MetadataGeneration(
            idp_proxy_conf.SERVICE, _key,
            idp_conf=_idp.config, xmlsec_path=_idp.config.xmlsec_path)

    print SERVER_ENV["base_url"]
    SRV = wsgiserver.CherryPyWSGIServer(('0.0.0.0', SERVER_ENV["PORT"]),
Exemplo n.º 28
0
    parser.add_argument('-r', dest="rsa_file",
                        help="File containing a RSA key")
    parser.add_argument('-k', dest="hmac_key",
                        help="If using a HMAC algorithm this is the key")
    parser.add_argument('-a', dest="alg",
                        help="The signing algorithm")
    parser.add_argument('-j', dest="jwk", help="JSON Web Key")
    parser.add_argument('-J', dest="jwks", help="JSON Web Keys")
    parser.add_argument("message", nargs="?", help="The message")


    args = parser.parse_args()

    keys = []
    if args.rsa_file:
        keys = [RSAKey(key=import_rsa_key_from_file(args.rsa_file))]
    elif args.hmac_key:
        keys = [SYMKey(key=args.hmac_key)]

    if args.jwk:
        kspec = json.loads(open(args.jwk).read())
        keys.append(keyrep(kspec))

    if args.jwks:
        keys.extend(load_jwks(open(args.jwk).read()))

    if not keys:
        exit(-1)

    if args.msg_file:
        if args.msg_file == "A.2.1":
Exemplo n.º 29
0
                        help="A file containing a RSA key")
    parser.add_argument("-i", dest="int", help="Integrity method")
    parser.add_argument("-f", dest="file", help="File with the message")
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = assign(load_jwks_from_url(lrequest, args.jwk_url))
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        keys = load_x509_cert(lrequest, args.x509_url)
    elif args.x509_file:
        keys = [import_rsa_key_from_file(args.x509_file)]
    elif args.rsa_file:
        key = rsa_load(args.rsa_file)
        rsa_key = RSAKey(key=key)
        rsa_key.serialize()
        keys = [rsa_key]
    else:
        print("Needs encryption key")
        exit()

    if args.file:
        msg = open(args.file).read()
        msg = msg.strip("\n\r")
    else:
        msg = args.message
Exemplo n.º 30
0
                        help="The encryption enc algorithm")
    parser.add_argument('-j', dest="jwk", help="JSON Web Key")
    parser.add_argument('-J', dest="jwks", help="JSON Web Keys")
    parser.add_argument('-i', dest="kid", help="key id")
    parser.add_argument('-l', dest="log", help="logfile name")
    parser.add_argument("message", nargs="?", help="The message")

    args = parser.parse_args()

    if args.log:
        setup_logging(args.log)

    _kid = args.kid
    keys = []
    if args.rsa_file:
        keys.append(RSAKey(key=import_rsa_key_from_file(args.rsa_file),
                           kid=_kid))
    if args.hmac_key:
        keys.append(SYMKey(key=args.hmac_key))

    if args.jwk:
        kspec = json.loads(open(args.jwk).read())
        keys.append(keyrep(kspec))

    if args.jwks:
        _k = KEYS()
        _k.load_jwks(open(args.jwks).read())
        keys.extend(_k._keys)

    if not keys:
        exit(-1)
Exemplo n.º 31
0
                        help="A file containing a RSA key")
    parser.add_argument("-i", dest="int", help="Integrity method")
    parser.add_argument("-f", dest="file", help="File with the message")
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = load_jwks_from_url(args.jwk_url)
    elif args.jwk_file:
        keys = load_jwks(open(args.jwk_file).read())
    elif args.x509_url:
        keys = load_x509_cert(args.x509_url, {})
    elif args.x509_file:
        keys = [import_rsa_key_from_file(args.x509_file)]
    elif args.rsa_file:
        key = rsa_load(args.rsa_file)
        rsa_key = RSAKey(key=key)
        rsa_key.serialize()
        keys = [rsa_key]
    else:
        print("Needs encryption key")
        exit()

    if args.file:
        msg = open(args.file).read()
        msg = msg.strip("\n\r")
    else:
        msg = args.message
Exemplo n.º 32
0
#! /usr/bin/env python3

from argparse import ArgumentParser

from jwkest.jwk import RSAKey, import_rsa_key_from_file
from oic import rndstr

from oidc_fed.util import write_private_key_to_jwk, write_key_to_jwk

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("hostname")
    parser.add_argument("keypath")
    parser.add_argument("--pretty", action="store_true", default=False, help="add newlines in the output JWKs'")
    args = parser.parse_args()

    key = RSAKey(
        key=import_rsa_key_from_file(args.keypath), kid="{}/{}".format(args.hostname, rndstr()), use="sig", alg="RS256"
    )
    write_private_key_to_jwk(key, args.hostname + ".jwk", pretty_format=args.pretty)
    write_key_to_jwk(key, args.hostname + ".pub.jwk", pretty_format=args.pretty)
Exemplo n.º 33
0
    parser.add_argument('-J', dest="jwks", help="JSON Web Keys")
    parser.add_argument('-i', dest="kid", help="key id")
    parser.add_argument('-l', dest="log", help="logfile name")
    parser.add_argument('-t', dest="msgtype", help="JWT message type")
    parser.add_argument('-u', dest="jwks_url", help="JSON Web Keys URL")
    parser.add_argument("message", nargs="?", help="The message")

    args = parser.parse_args()

    if args.log:
        setup_logging(args.log)

    _kid = args.kid
    keys = []
    if args.rsa_file:
        keys.append(RSAKey(key=import_rsa_key_from_file(args.rsa_file),
                           kid=_kid))
    if args.hmac_key:
        keys.append(SYMKey(key=args.hmac_key))

    if args.jwk:
        kspec = json.loads(open(args.jwk).read())
        keys.append(keyrep(kspec))

    if args.jwks:
        _k = KEYS()
        _k.load_jwks(open(args.jwks).read())
        keys.extend(_k._keys)

    if args.jwks_url:
        _k = KEYS()
Exemplo n.º 34
0
                         dest="rsa_file",
                         help="A file containing a RSA key")
    _parser.add_argument('-p',
                         dest="rsa_public_file",
                         help="A file containing a public RSA key")
    _parser.add_argument("config", nargs="?", help="Server configuration")

    args = _parser.parse_args()

    if args.rsa_file:
        key = rsa_load(args.rsa_file)
    else:
        key = None

    if args.rsa_file:
        _key = import_rsa_key_from_file(args.rsa_file)
    elif args.rsa_public_file:
        _key = import_rsa_key_from_file(args.rsa_public_file)
    else:
        _key = None

    #noinspection PyUnboundLocalVariable
    _idp = setup_server_env(idp_proxy_conf, args.config, key)

    if _key:
        GENERATE_METADATA = MetadataGeneration(
            idp_proxy_conf.SERVICE,
            _key,
            idp_conf=_idp.config,
            xmlsec_path=_idp.config.xmlsec_path)
Exemplo n.º 35
0
    parser.add_argument("-e", dest="enc", help="The encryption method")
    parser.add_argument("-m", dest="mode", default="public", help="Whether a public or private key should be used")
    parser.add_argument("-f", dest="file", help="File to be encrypted")
    parser.add_argument("message", nargs="?", help="The message to encrypt")

    args = parser.parse_args()

    keys = {}
    if args.jwk_url:
        keys = assign(load_jwks_from_url(args.jwk_url, {}))
    elif args.jwk_file:
        keys = assign(load_jwks(open(args.jwk_file).read()))
    elif args.x509_url:
        keys = assign(load_x509_cert(lrequest, args.x509_url))
    elif args.x509_file:
        keys = {"RSA": [import_rsa_key_from_file(args.x509_file)]}
    elif args.rsa_file:
        keys = {"RSA": [rsa_load(args.rsa_file)]}
        mode = ""
    else:
        print >> sys.stderr, "Needs encryption key"
        exit()

    if not args.enc or not args.alg:
        print >> sys.stderr, "There are no default encryption methods"
        exit()

    if args.enc not in SUPPORTED["enc"]:
        print >> sys.stderr, "Encryption method %s not supported" % args.enc
        print >> sys.stderr, "Methods supported: %s" % SUPPORTED["enc"]
        exit()