|
| 1 | +import base64 |
| 2 | +import requests |
| 3 | +import subprocess # nosec B404 |
| 4 | +import shlex |
| 5 | +import xmltodict |
| 6 | + |
| 7 | +from tempfile import TemporaryDirectory as TempD |
| 8 | + |
| 9 | +from django.conf import settings |
| 10 | + |
| 11 | +from .helpers import logger |
| 12 | + |
| 13 | +# GeneraConstancia Payload |
| 14 | +REQUEST_CERTIFICATE = """<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" \ |
| 15 | +xmlns:xw="www.XMLWebServiceSoapHeaderAuth.net"> |
| 16 | + <soap:Header> |
| 17 | + <xw:AuthSoapHd> |
| 18 | + <xw:Usuario>{user}</xw:Usuario> |
| 19 | + <xw:Clave>{passwd}</xw:Clave> |
| 20 | + <xw:Entidad>{entity}</xw:Entidad> |
| 21 | + </xw:AuthSoapHd> |
| 22 | + </soap:Header> |
| 23 | + <soap:Body> |
| 24 | + <xw:GeneraConstancia> |
| 25 | + <xw:referencia>{reference}</xw:referencia> |
| 26 | + <xw:solicitud>{doc_base64}</xw:solicitud> |
| 27 | + </xw:GeneraConstancia> |
| 28 | + </soap:Body> |
| 29 | +</soap:Envelope>""" |
| 30 | + |
| 31 | +# ValidaConstancia Payload |
| 32 | +REQUEST_VALIDATE = """<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" \ |
| 33 | +xmlns:xw="www.XMLWebServiceSoapHeaderAuth.net"> |
| 34 | + <soap:Header> |
| 35 | + <xw:AuthSoapHd> |
| 36 | + <xw:Usuario>{user}</xw:Usuario> |
| 37 | + <xw:Clave>{passwd}</xw:Clave> |
| 38 | + <xw:Entidad>{entity}</xw:Entidad> |
| 39 | + </xw:AuthSoapHd> |
| 40 | + </soap:Header> |
| 41 | + <soap:Body> |
| 42 | + <xw:ValidaConstancia> |
| 43 | + <xw:referencia>{reference}</xw:referencia> |
| 44 | + <xw:constancia>{certificate}</xw:constancia> |
| 45 | + </xw:ValidaConstancia> |
| 46 | + </soap:Body> |
| 47 | +</soap:Envelope>""" |
| 48 | + |
| 49 | + |
| 50 | +class ReachCore: |
| 51 | + """ |
| 52 | + Class to handle rich core methods and connections |
| 53 | + referencia = "merkleroot" as a valid str sha256 hash |
| 54 | + solicitud = doc_file as a valid base64 str |
| 55 | + """ |
| 56 | + |
| 57 | + ENTITY = settings.REACHCORE_ENTITY |
| 58 | + USER = settings.REACHCORE_USER |
| 59 | + PASS = settings.REACHCORE_PASS |
| 60 | + |
| 61 | + TIMEOUT = 10 |
| 62 | + HEADERS = {'content-type': 'text/xml'} |
| 63 | + |
| 64 | + def __init__(self, **kwargs): |
| 65 | + """ Initialize vars and settings """ |
| 66 | + |
| 67 | + if settings.PRODUCTION: |
| 68 | + self.BASE = "https://nom151.advantage-security.com/wsnom151/webservice.asmx?WSDL" |
| 69 | + self.POLICY = "2.16.484.101.10.316.2.1.1.2.1" |
| 70 | + else: |
| 71 | + self.BASE = "https://pilot-psc.reachcore.com/wsnom151/webservice.asmx?WSDL" |
| 72 | + self.POLICY = "1.16.484.101.10.316.1.2" |
| 73 | + |
| 74 | + def generate_proof(self, merkleroot): |
| 75 | + """ |
| 76 | + ReachCore endpoint [GeneraConstancia] |
| 77 | + merkleroot : Must be a valid sha256 str, as the merkle root is |
| 78 | + """ |
| 79 | + # Generates a temp directory where manipulate docs |
| 80 | + |
| 81 | + with TempD() as temp_dir: |
| 82 | + doc_path = temp_dir + "/doc_body.tsq" |
| 83 | + request_file = None |
| 84 | + # Prepare the command for the request file |
| 85 | + command = (F"openssl ts -query -digest {merkleroot} -sha256 -no_nonce " |
| 86 | + F"-tspolicy {self.POLICY} -out {doc_path}") |
| 87 | + args = shlex.split(command) |
| 88 | + try: |
| 89 | + # Pass security params as check=True and shell = False - More details in Bandit B603 |
| 90 | + process = subprocess.run(args, check=True, shell=False) # nosec B603 |
| 91 | + except Exception as e: |
| 92 | + logger.info(F"[Error:{e} Generating File Request], stdout={process.stdout}") |
| 93 | + return None |
| 94 | + else: |
| 95 | + logger.info("Success Generated Request File") |
| 96 | + |
| 97 | + # Read the file |
| 98 | + with open(doc_path, 'rb') as f: |
| 99 | + request_file = base64.b64encode(f.read()) |
| 100 | + request_file = request_file.decode() |
| 101 | + |
| 102 | + # Create body content |
| 103 | + body = REQUEST_CERTIFICATE.format(user=self.USER, passwd=self.PASS, entity=self.ENTITY, |
| 104 | + reference=merkleroot, doc_base64=request_file) |
| 105 | + # For debug only |
| 106 | + # logger.info(body) |
| 107 | + |
| 108 | + try: |
| 109 | + # Send requests and get the content |
| 110 | + r = requests.post(self.BASE, data=body, headers=self.HEADERS, timeout=self.TIMEOUT) |
| 111 | + logger.info(F"Response: {r.status_code}") |
| 112 | + logger.info(F"{r.content}") |
| 113 | + |
| 114 | + if r.status_code == 200: |
| 115 | + # Parse the file and generate readable json metadata |
| 116 | + parsed_result = xmltodict.parse(r.text) |
| 117 | + body = parsed_result["soap:Envelope"]["soap:Body"] |
| 118 | + metadata = body["GeneraConstanciaResponse"]["GeneraConstanciaResult"] |
| 119 | + metadata["xml_raw"] = r.text |
| 120 | + return metadata |
| 121 | + else: |
| 122 | + # TODO Try to generate next block |
| 123 | + # Execute a default behauvior or try to do it in other time |
| 124 | + return None |
| 125 | + |
| 126 | + except Exception as e: |
| 127 | + logger.error(F"[Generate Proof Error]: {e}, type: {type(e)}, merkleroot: {merkleroot}") |
| 128 | + |
| 129 | + def validate(self, certificate, merkleroot): |
| 130 | + """ Validate certificate using Reachcore validate endpoints """ |
| 131 | + try: |
| 132 | + body = REQUEST_VALIDATE.format(user=self.USER, passwd=self.PASS, entity=self.ENTITY, |
| 133 | + reference=merkleroot, certificate=certificate) |
| 134 | + r = requests.post(self.BASE, data=body, headers=self.HEADERS, timeout=self.TIMEOUT) |
| 135 | + logger.info(F"Response: {r.status_code}") |
| 136 | + logger.info(F"{r.content}") |
| 137 | + if r.status_code == 200: |
| 138 | + parsed_result = xmltodict.parse(r.text) |
| 139 | + body = parsed_result["soap:Envelope"]["soap:Body"] |
| 140 | + metadata = body["ValidaConstanciaResponse"]["ValidaConstanciaResult"] |
| 141 | + metadata["xml_raw"] = r.text |
| 142 | + return metadata |
| 143 | + |
| 144 | + else: |
| 145 | + # We might ask to user to try again |
| 146 | + return None |
| 147 | + |
| 148 | + except Exception as e: |
| 149 | + logger.error(F"[Validate Certificate Fails]: {e}, type: {type(e)}, merkleroot: {merkleroot}") |
0 commit comments