Ejemplo n.º 1
0
 def set_signing_source(self,
                        source: str,
                        alg: Optional[str] = None) -> None:
     """Set token signer source"""
     with open(source) as jwk_file:
         jwk_dict = json.load(jwk_file)
         self.signing_key = key_from_jwk_dict(jwk_dict)
     self.signing_alg = alg or self.get_default_sig_alg(self.signing_key)
Ejemplo n.º 2
0
 def from_response(cls, response: dict) -> "TokenInformation":
     if "serial" not in response:
         raise ValueError("Token serial missing")
     if "publicKey" not in response:
         raise ValueError("Token public key missing")
     tpk = key_from_jwk_dict(response["publicKey"], private=False)
     return cls(
         serial=response["serial"],
         public_key=tpk,
         thumbprint=tpk.thumbprint("SHA-256").decode(),
         revoked=response.get("revoked", False),
     )
Ejemplo n.º 3
0
    def __init__(self, conf: Dict) -> None:
        self.logger = configure_logging(settings.LOGGING)

        # OIDC provider configuration
        self.conf = conf
        self.op = conf.get('op')

        # TODO: here manage static clients without dyn registration enabled
        # self.oidc_clients = conf.get('oidc_clients', {})

        # session key
        self.session_jwk = conf.get('session_jwk')
        if self.session_jwk is not None:
            self.logger.debug("Reading session signer from %s",
                              self.session_jwk)
            try:
                with open(self.session_jwk) as jwk_file:
                    jwk_dict = json.loads(jwk_file.read())
                    self.session_key = key_from_jwk_dict(jwk_dict).k
            except Exception:
                self.logger.critical("Failed reading session signer from %s",
                                     self.session_jwk)
                sys.exit(-1)
        else:
            self.logger.debug("Generating random session signer")
            self.session_key = SYMKey(key=rnd_token(32)).k

        # set OP session key
        if self.op is not None:
            if self.op['server_info'].get('password') is None:
                key = self.session_key
                self.op['server_info']['password'] = key
                self.logger.debug("Set server password to %s", key)

        # templates environment
        self.template_dir = os.path.abspath(
            conf.get('template_dir', 'templates'))
Ejemplo n.º 4
0
    def __init__(self, conf: Dict) -> None:
        self.logger = configure_logging(
            config=conf.get('logging')).getChild(__name__)

        # OIDC provider configuration
        self.op = conf.get('op')
        self.webserver = conf.get('webserver')
        # self.oidc_clients = conf.get('oidc_clients', {})

        # session key
        self.session_jwk = conf.get('session_jwk')
        if self.session_jwk is not None:
            self.logger.debug("Reading session signer from %s",
                              self.session_jwk)
            try:
                with open(self.session_jwk) as jwk_file:
                    jwk_dict = json.loads(jwk_file.read())
                    self.session_key = key_from_jwk_dict(jwk_dict).k
            except Exception:
                self.logger.critical("Failed reading session signer from %s",
                                     self.session_jwk)
                sys.exit(-1)
        else:
            self.logger.debug("Generating random session signer")
            self.session_key = SYMKey(key=rnd_token(32)).k

        # set OP session key
        if self.op is not None:
            if self.op['server_info'].get('password') is None:
                key = self.session_key
                self.op['server_info']['password'] = key
                self.logger.debug("Set server password to %s", key)

        # templates and Jinja environment
        self.template_dir = os.path.abspath(
            conf.get('template_dir', 'templates'))
        self.jinja_env = conf.get('jinja_env', {})
Ejemplo n.º 5
0
def jwk_from_file(filename: str, private: bool = True) -> JWK:
    """Read JWK from file"""
    with open(filename, mode="rt") as input_file:
        jwk_dict = json.loads(input_file.read())
    return key_from_jwk_dict(jwk_dict, private=private)
Ejemplo n.º 6
0
def main():
    """Main function"""

    parser = argparse.ArgumentParser(description="JWS verifier")

    parser.add_argument(
        "--trusted",
        dest="trusted",
        metavar="filename",
        help="Trusted keys (JWKS)",
        required=False,
    )
    parser.add_argument(
        "--input",
        dest="jws_input",
        metavar="filename",
        help="JWS file input",
        required=True,
    )
    parser.add_argument(
        "--output",
        dest="output",
        metavar="filename",
        help="Output",
        required=False,
    )
    parser.add_argument(
        "--headers",
        dest="headers_output",
        metavar="filename",
        help="Headers output",
        required=False,
    )
    parser.add_argument("--debug",
                        dest="debug",
                        action="store_true",
                        help="Enable debugging")

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    trusted_keys = []
    if args.trusted:
        with open(args.trusted) as input_file:
            trusted_payload = json.load(input_file)
            if isinstance(trusted_payload, dict):
                trusted_keys.append(key_from_jwk_dict(trusted_payload))
            elif isinstance(trusted_payload, dict):
                for jwk_dict in trusted_payload["keys"]:
                    trusted_keys.append(
                        key_from_jwk_dict(jwk_dict, private=False))
            else:
                raise ValueError("Unknown trusted list format")

    with open(args.jws_input, "rt") as input_file:
        jws_file = input_file.read()

    protected_headers = []
    jws_dict = json.loads(jws_file)

    if args.trusted:
        jws = JWS()
        message = jws.verify_json(jws_file, keys=trusted_keys)
    else:
        message = json.loads(b64d(jws_dict["payload"].encode()).decode())

    for signatures in jws_dict["signatures"]:
        if "protected" in signatures:
            protected_headers.append(extract_headers(signatures["protected"]))

    if args.headers_output:
        with open(args.headers_output, "wt") as output_file:
            print(json.dumps(protected_headers, indent=4), file=output_file)
    else:
        if args.trusted:
            print("# JWS PROTECTED HEADERS (VERIFIED)")
        else:
            print("# JWS PROTECTED HEADERS (NOT VERIFIED)")
        print(json.dumps(protected_headers, indent=4, sort_keys=True))

    if args.output:
        with open(args.output, "wt") as output_file:
            print(json.dumps(message, indent=4), file=output_file)
    else:
        if args.trusted:
            print("# JWS CONTENTS (VERIFIED)")
        else:
            print("# JWS CONTENTS (NOT VERIFIED)")
        print(json.dumps(message, indent=4, sort_keys=True))