
    Pf,                        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'dS )    N)urljoinurlparse)hazmatx509)InvalidSignature)backends)DSAPublicKey)ECDSAEllipticCurvePublicKey)PKCS1v15)RSAPublicKey)SHA1Hash)EncodingPublicFormat)ocsp)AuthorizationErrorConnectionErrorc                 L   |                                  }	 t          |t                    r5|                    |j        |j        t                      |j                   d S t          |t                    r(|                    |j        |j        |j                   d S t          |t                    r5|                    |j        |j        t          |j                             d S |                    |j        |j                   d S # 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/env/lib/python3.11/site-packages/redis/ocsp.py_verify_responser       sG   ##%%F?fl++ 	UMM'0

6	     -- 	UMM'06    
  677 	UMM'0m<==     MM-1=3STTTTT ? ? ?=>>>?s   AD	  ;D	 AD	 ' D	 	D#Tc                    t          j        |          }|j        t           j        j        k    rt          d          |j        t           j        j        k    rY|j        t           j        j	        k    r>t          dt          |j                                      d          d          d          nt          d          |j        t          j                                        k    rt          d          |j        r6|j        t          j                                        k     rt          d          |j        }|j        }|j        }| }||| j        k    s||k    r| }n|j        }t-          || ||          }		 |	d
         }
n# t.          $ r t          d          w xY w|
j                            t4          j                  }|t4          j        j        j        |j        vrt          d          |
}|rtA          ||           dS )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 successful response from the ocsp responderz)ocsp certificate was issued in the futurez1ocsp certificate has invalid update - in the pastNr   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   s8    /
;;M$(?(LLL !WXXX$(?(JJJ+t/B/GGG!*s=#CDDJJ3OOPQR * * *   H N
 
 	
  H$5$9$9$;$;;;IJJJ 	!S%(9(=(=(?(???QRRR"1N/K"5N""k111[((&*+;
 
	M,Q/NN 	M 	M 	M!"KLLL	M '??@UVV;$(6C39TT!"KLLL) :)=9994s   :F Fc                 N    fd| D             }nfd| D             }|S )Nc                 Z    g | ]'}t          |          k    |j        j        k    %|(S  )_get_pubkey_hashissuerr5   ).0cr   rC   s     r   
<listcomp>z%_get_certificates.<locals>.<listcomp>n   sE     
 
 
""n44[EX9X9X 9X9X9X    c                 J    g | ]}|j         k    |j        j         k    | S rL   )r5   rN   )rO   rP   r   r2   s     r   rQ   z%_get_certificates.<locals>.<listcomp>t   s?     
 
 
yN**qx;;N/N/N /N/N/NrR   rL   )rE   r   r2   rC   r6   s    ``` r   r7   r7   l   so    
 
 
 
 

 
 

 
 
 
 

 
 
 rR   c                 ,   |                                  }t          |t                    r+|                    t          j        t          j                  }njt          |t                    r+|                    t          j	        t          j
                  }n*|                    t          j        t          j                  }t          t                      t          j                              }|                    |           |                                S )N)backend)r   r   r   public_bytesr   DERr   PKCS1r   X962UncompressedPointSubjectPublicKeyInfor   r   r   default_backendupdatefinalize)certificater   hsha1s       r   rM   rM   }   s    ##%%F &,'' Ql.@AA	F2	3	3 Q|/MNNl.OPP 8 : :;;;DKKNNN==??rR   c                    |dv rt          d          d}|                                                                 }|                                 D ]*}|                                }|j        |j        k    r|} n+|t          d          |)t          j        |          }||k    rt          d          t          ||          S )zAn implementation 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.
    )rR   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   rN   r   load_pem_x509_certificaterI   )conr@   expectedr   	peer_certrP   certes           r   ocsp_staple_verifierrl      s     [  8999K((**::<<I$$&&    ""<9+++KE , RSSS*844>>!"STTTk:666rR   c                   D    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 ZdS )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                 >    || _         || _        || _        || _        d S N)SOCKHOSTPORTCA_CERTS)selfsockhostportca_certss        r   __init__zOCSPVerifier.__init__   s"    			 rR   c                     t          j        |          }t          j        |                                t          j                              }|S )z?Convert SSL certificates in a binary (DER) format to ASCII PEM.)sslDER_cert_to_PEM_certr   rf   encoder   r\   )ru   derpemrj   s       r   
_bin2asciizOCSPVerifier._bin2ascii   s<     &s++-cjjllH<T<V<VWWrR   c                     | j                             d          }|du rt          d          |                     |          }|                     |          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)rq   getpeercertr   r   _certificate_components)ru   r   rj   s      r   components_from_socketz#OCSPVerifier.components_from_socket   sV     i##D))%<<!"EFFFs##++D111rR   c                    	 |j                             t          j        j        j                  j        }n,# t          j        j         j        $ r t          d          w xY wd |D             }	 |d         j
        j        }n# t          $ r d}Y nw xY wd |D             }	 |d         j
        j        }n# t          $ r t          d          w xY w|||fS )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 certificatec                 P    g | ]#}|j         t          j        j        j        k    !|$S rL   )access_methodr   r<   AuthorityInformationAccessOID
CA_ISSUERSrO   is     r   rQ   z8OCSPVerifier._certificate_components.<locals>.<listcomp>   s7     
 
 
$("H"SSS SSSrR   r   Nc                 P    g | ]#}|j         t          j        j        j        k    !|$S rL   )r   r   r<   r   OCSPr   s     r   rQ   z8OCSPVerifier._certificate_components.<locals>.<listcomp>   s7     
 
 
$("H"MMM MMMrR   zno ocsp servers in certificate)r9   get_extension_for_oidr   r<   ExtensionOIDAUTHORITY_INFORMATION_ACCESSr?   cryptographyExtensionNotFoundr   access_locationr8   )ru   rj   aiaissuersrN   ocspsr   s          r   r   z$OCSPVerifier._certificate_components   s5   	S/77%B  C  += 	S 	S 	S!"QRRR	S
 

 
 

	QZ/5FF 	 	 	FFF	
 

 
 
	D8+1DD 	D 	D 	D!"BCCC	D VT!!s'   36 )A/B BB!B4 4Cc                     t          j        | j        | j        f| j                  }t          j        |                                t          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.
        )ry   )r|   get_server_certificaterr   rs   rt   r   rf   r~   r   r\   r   )ru   r   rj   s      r   !components_from_direct_connectionz.OCSPVerifier.components_from_direct_connection   s[     ($)TY)?$-XXX-cjjllH<T<V<VWW++D111rR   c                    t          j                    }|                    ||t          j        j        j                                                  }|                                }t          j
        |                    t          j        j        j        j                            }t          ||                    d                    }|S )z#Return the complete url to the ocspascii)r   OCSPRequestBuilderadd_certificater   r   
primitiveshashesSHA256buildbase64	b64encoderV   serializationr   rW   r   decode)ru   serverrj   r   orbrequestpathurls           r   build_certificate_urlz"OCSPVerifier.build_certificate_url   s    %'' !!+|2=DKKMM
 
 ))++  !2!@!I!MNN
 
 fdkk'2233
rR   c                 n   t          j        |          }|j        st          d          |j        }|                     |          }|                     |||          }t          |          j        dd}t          j        ||          }|j        st          d          t          ||j        d          S )z3Checks the validity 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   )	ru   r   rj   
issuer_urlrr   r   ocsp_urlheaders	            r   check_certificatezOCSPVerifier.check_certificate  s     L$$t 	H!"FGGGiooc**--fdKHH X&&-6
 
 L6222t 	F!"DEEE!+qy$???rR   c                 $   	 |                                  \  }}}|t          d          |                     |||          S # t          $ rC |                                 \  }}}|t          d          |                     |||          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.
        Nz%no issuers found in certificate chain)r   r   r   r   r   )ru   rj   r   ocsp_servers       r   is_validzOCSPVerifier.is_valid!  s    		I,0,G,G,I,I)D*k!%&MNNN))+tZHHH! 	I 	I 	I,0,R,R,T,T)D*k!%&MNNN))+tZHHHHH		Is   ?A A
BBrp   )__name__
__module____qualname____doc__rz   r   r   r   r   r   r   r   rL   rR   r   rn   rn      s         ! ! ! !  
2 
2 
2&" &" &"P2 2 2   @ @ @*I I I I IrR   rn   )Trp   )(r   r/   r|   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   rM   rl   rn   rL   rR   r   <module>r      s     



 * * * * * * * * , , , ,  % % % % % % % % 4 4 4 4 4 4 ( ( ( ( ( ( F F F F F F V V V V V V V V F F F F F F F F F F F F < < < < < < < < O O O O O O O O " " " " " " @ @ @ @ @ @ @ @? ? ?88 8 8 8v  "   7 7 7 78JI JI JI JI JI JI JI JI JI JIrR   