
    +h,                     
   d dl Z d dlZd dlZd dlmZmZ d dlZd dlZd dlm	Z	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d d
lmZmZ d dlmZmZ d dlmZ d dlm Z m!Z! d Z"ddZ#d Z$d Z%ddZ& G d d      Z'y)    N)urljoinurlparse)hazmatx509)InvalidSignature)backends)DSAPublicKey)ECDSAEllipticCurvePublicKey)PKCS1v15)RSAPublicKey)SHA1Hash)EncodingPublicFormat)ocsp)AuthorizationErrorConnectionErrorc                 R   | j                         }	 t        |t              r;|j                  |j                  |j
                  t               |j                         y t        |t              r2|j                  |j                  |j
                  |j                         y t        |t              r;|j                  |j                  |j
                  t        |j                               y |j                  |j                  |j
                         y # t        $ r t        d      w xY w)Nzfailed to valid ocsp response)
public_key
isinstancer   verify	signaturetbs_response_bytesr   signature_hash_algorithmr	   r   r
   r   r   )issuer_certocsp_responsepubkeys      =/var/www/html/venv/lib/python3.12/site-packages/redis/ocsp.py_verify_responser       s    ##%F?fl+MM''00
66	 -MM''0066
  67MM''00m<<= MM-11=3S3ST ?=>>?s    A
D AD A
D *&D D&c                 v   t        j                  |      }|j                  t         j                  j                  k(  rt        d      |j                  t         j                  j                  k(  r[|j                  t         j                  j                  k7  r?t        dt        |j                        j                  d      d    d      t        d      |j                  t        j                  j                         k\  rt        d      |j                   r6|j                   t        j                  j                         k  rt        d      |j"                  }|j$                  }|j&                  }| }||| j(                  k(  s||k(  r| }n|j*                  }t-        || ||      }		 |	d	   }
|
j0                  j3                  t4        j6                        }|0t4        j8                  j:                  j<                  |j>                  vrt        d      |
}|rtA        ||       y# t.        $ r t        d
      w xY w)z=A wrapper the return the validity of a known ocsp certificatez4you are not authorized to view this ocsp certificatezReceived an .   z ocsp certificate statusz?failed to retrieve a sucessful response from the ocsp responderz)ocsp certificate was issued in the futurez1ocsp certificate has invalid update - in the pastr   z'no certificates found for the responderz'delegate not autorized for ocsp signingT)!r   load_der_ocsp_responseresponse_statusOCSPResponseStatusUNAUTHORIZEDr   
SUCCESSFULcertificate_statusOCSPCertStatusGOODr   strsplitthis_updatedatetimenownext_updateresponder_nameissuer_key_hashresponder_key_hashsubjectcertificates_get_certificates
IndexError
extensionsget_extension_for_classr   ExtendedKeyUsageoidExtendedKeyUsageOIDOCSP_SIGNINGvaluer    )r   
ocsp_bytesvalidater   r2   issuer_hashresponder_hashcert_to_validatecertsresponder_certsresponder_certexts               r   _check_certificaterI   1   s    //
;M$$(?(?(L(LL !WXX$$(?(?(J(JJ++t/B/B/G/GG!s=#C#CDJJ3OPQRS T* * 
 M
 	
   H$5$5$9$9$;;IJJ 	!!%%(9(9(=(=(??QRR"11N//K"55N""k111[(&**+;
	M,Q/N ''??@U@UV;$((66CC399T!"KLL))=9  	M!"KLL	Ms   'H# #H8c                     |8| D cg c]+  }t        |      |k(  r|j                  |j                  k(  r|- }}|S | D cg c],  }|j                  |k(  r|j                  |j                  k(  r|. }}|S c c}w c c}w N)_get_pubkey_hashissuerr5   )rE   r   r2   rC   cr6   s         r   r7   r7   l   s     
"n4[EXEX9X 
 
 	 
yyN*qxx;;N;N/N 
 
 

s
   0A41A9c                 
   | j                         }t        |t              r/|j                  t        j
                  t        j                        }nmt        |t              r/|j                  t        j                  t        j                        }n.|j                  t        j
                  t        j                        }t        t               t        j                               }|j!                  |       |j#                         S )N)backend)r   r   r   public_bytesr   DERr   PKCS1r   X962UncompressedPointSubjectPublicKeyInfor   r   r   default_backendupdatefinalize)certificater   hsha1s       r   rL   rL   }   s    ##%F &,'l.@.@A	F2	3|/M/MNl.O.OP 8 8 :;DKKN==?    c                 d   |dv rt        d      d}| j                         j                         }| j                         D ]/  }|j                         }|j                  |j
                  k(  s-|} n |t        d      |%t        j                  |      }||k7  rt        d      t        ||      S )zAn implemention of a function for set_ocsp_client_callback in PyOpenSSL.

    This function validates that the provide ocsp_bytes response is valid,
    and matches the expected, stapled responses.
    )r]   Nzno ocsp response presentNz2no matching issuer cert found in certificate chainz/received and expected certificates do not match)	r   get_peer_certificateto_cryptographyget_peer_cert_chainr5   rM   r   load_pem_x509_certificaterI   )conr@   expectedr   	peer_certrN   certes           r   ocsp_staple_verifierrh      s     [ 899K((*::<I$$&   "<<9+++K	 RSS**84>!"STTk:66r]   c                   B    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zy)OCSPVerifiera  A class to verify ssl sockets for RFC6960/RFC6961. This can be used
    when using direct validation of OCSP responses and certificate revocations.

    @see https://datatracker.ietf.org/doc/html/rfc6960
    @see https://datatracker.ietf.org/doc/html/rfc6961
    Nc                 <    || _         || _        || _        || _        y rK   )SOCKHOSTPORTCA_CERTS)selfsockhostportca_certss        r   __init__zOCSPVerifier.__init__   s    			 r]   c                     t        j                  |      }t        j                  |j	                         t        j                               }|S )z?Convert SSL certificates in a binary (DER) format to ASCII PEM.)sslDER_cert_to_PEM_certr   rb   encoder   rW   )rp   derpemrf   s       r   
_bin2asciizOCSPVerifier._bin2ascii   s:     &&s+--cjjlH<T<T<VWr]   c                     | j                   j                  d      }|du rt        d      | j                  |      }| j	                  |      S )zThis function returns the certificate, primary issuer, and primary ocsp
        server in the chain for a socket already wrapped with ssl.
        TFz!no certificate found for ssl peer)rl   getpeercertr   r|   _certificate_components)rp   rz   rf   s      r   components_from_socketz#OCSPVerifier.components_from_socket   sJ     ii##D)%<!"EFFs#++D11r]   c                    	 |j                   j                  t        j                  j                  j
                        j                  }|D cg c]5  }|j                  t        j                  j                  j                  k(  r|7 }}	 |d   j                  j                  }|D cg c]5  }|j                  t        j                  j                  j                  k(  r|7 }}	 |d   j                  j                  }|||fS # t        j                  j                   j                  $ r t        d      w xY wc c}w # t        $ r d}Y w xY wc c}w # t        $ r t        d      w xY w)zGiven an SSL certificate, retract the useful components for
        validating the certificate status with an OCSP server.

        Args:
            cert ([bytes]): A PEM encoded ssl certificate
        z-No AIA information present in ssl certificater   Nzno ocsp servers in certificate)r9   get_extension_for_oidr   r<   ExtensionOIDAUTHORITY_INFORMATION_ACCESSr?   cryptographyExtensionNotFoundr   access_methodAuthorityInformationAccessOID
CA_ISSUERSaccess_locationr8   OCSP)rp   rf   aiaiissuersrM   ocspsr   s           r   r   z$OCSPVerifier._certificate_components   s_   	S//77%%BBe  
$(("H"H"S"SS 
 

	QZ//55F 
$(("H"H"M"MM 
 
	D8++11D VT!!5   ++== 	S!"QRR	S
  	F	
  	D!"BCC	Ds6   AD :D8
D= ':E$E 3D5=E
EE(c                     t        j                  | j                  | j                  f| j                        }t        j                  |j                         t        j                               }| j                  |      S )zReturn the certificate, primary issuer, and primary ocsp server
        from the host defined by the socket. This is useful in cases where
        different certificates are occasionally presented.
        )rt   )rw   get_server_certificaterm   rn   ro   r   rb   ry   r   rW   r   )rp   r{   rf   s      r   !components_from_direct_connectionz.OCSPVerifier.components_from_direct_connection   sY     (($))TYY)?$--X--cjjlH<T<T<VW++D11r]   c                    t        j                         }|j                  ||t        j                  j
                  j                  j                               }|j                         }t        j                  |j                  t        j
                  j                  j                  j                              }t        ||j!                  d            }|S )z#Return the complete url to the ocspascii)r   OCSPRequestBuilderadd_certificater   r   
primitiveshashesSHA256buildbase64	b64encoderQ   serializationr   rR   r   decode)rp   serverrf   r   orbrequestpathurls           r   build_certificate_urlz"OCSPVerifier.build_certificate_url   s    %%' !!+|22==DDKKM
 ))+  !2!2!@!@!I!I!M!MN
 fdkk'23
r]   c                 t   t        j                  |      }|j                  st        d      |j                  }| j                  |      }| j                  |||      }t        |      j                  dd}t        j                  ||      }|j                  st        d      t        ||j                  d      S )z5Checks the validitity of an ocsp server for an issuerz"failed to fetch issuer certificatezapplication/ocsp-request)HostzContent-Type)headersz failed to fetch ocsp certificateT)
requestsgetokr   contentr|   r   r   netlocrI   )	rp   r   rf   
issuer_urlrrz   r   ocsp_urlheaders	            r   check_certificatezOCSPVerifier.check_certificate  s     LL$tt!"FGGiiooc*--fdKH X&--6
 LL62tt!"DEE!+qyy$??r]   c                     	 | j                         \  }}}|t        d      | j                  |||      S # t        $ r7 | j	                         \  }}}|t        d      | j                  |||      cY S w xY w)aD  Returns the validity of the certificate wrapping our socket.
        This first retrieves for validate the certificate, issuer_url,
        and ocsp_server for certificate validate. Then retrieves the
        issuer certificate from the issuer_url, and finally checks
        the validity of OCSP revocation status.
        z%no issuers found in certificate chain)r   r   r   r   r   )rp   rf   r   ocsp_servers       r   is_validzOCSPVerifier.is_valid!  s    		I,0,G,G,I)D*k!%&MNN))+tZHH! 	I,0,R,R,T)D*k!%&MNN))+tZHH		Is   36 =A65A6rK   )__name__
__module____qualname____doc__ru   r|   r   r   r   r   r   r    r]   r   rj   rj      s2    !
2&"P2 @*Ir]   rj   )TrK   )(r   r/   rw   urllib.parser   r   %cryptography.hazmat.primitives.hashesr   r   r   r   cryptography.exceptionsr   cryptography.hazmatr   -cryptography.hazmat.primitives.asymmetric.dsar	   ,cryptography.hazmat.primitives.asymmetric.ecr
   r   1cryptography.hazmat.primitives.asymmetric.paddingr   -cryptography.hazmat.primitives.asymmetric.rsar   r   r   ,cryptography.hazmat.primitives.serializationr   r   cryptography.x509r   redis.exceptionsr   r   r    rI   r7   rL   rh   rj   r   r]   r   <module>r      s`      
 * ,  % 4 ( F V F F < O " @?88v" 78JI JIr]   