pyOpenSSL.tex 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. \documentclass{howto}
  2. \title{Python OpenSSL Manual}
  3. \release{0.13}
  4. \author{Jean-Paul Calderone}
  5. \authoraddress{\email{exarkun@twistedmatrix.com}}
  6. \usepackage[english]{babel}
  7. \usepackage[T1]{fontenc}
  8. \begin{document}
  9. \maketitle
  10. \begin{abstract}
  11. \noindent
  12. This module is a rather thin wrapper around (a subset of) the OpenSSL library.
  13. With thin wrapper I mean that a lot of the object methods do nothing more than
  14. calling a corresponding function in the OpenSSL library.
  15. \end{abstract}
  16. \tableofcontents
  17. \section{Introduction \label{intro}}
  18. The reason pyOpenSSL was created is that the SSL support in the socket module
  19. in Python 2.1 (the contemporary version of Python when the pyOpenSSL project
  20. was begun) was severely limited. Other OpenSSL wrappers for Python at the time
  21. were also limited, though in different ways. Unfortunately, Python's standard
  22. library SSL support has remained weak, although other packages (such as
  23. M2Crypto\footnote{See \url{http://chandlerproject.org/Projects/MeTooCrypto}})
  24. have made great advances and now equal or exceed pyOpenSSL's functionality.
  25. The reason pyOpenSSL continues to be maintained is that there is a significant
  26. user community around it, as well as a large amount of software which depends
  27. on it. It is a great benefit to many people for pyOpenSSL to continue to exist
  28. and advance.
  29. \section{Building and Installing \label{building}}
  30. These instructions can also be found in the file \verb|INSTALL|.
  31. I have tested this on Debian Linux systems (woody and sid), Solaris 2.6 and
  32. 2.7. Others have successfully compiled it on Windows and NT.
  33. \subsection{Building the Module on a Unix System \label{building-unix}}
  34. pyOpenSSL uses distutils, so there really shouldn't be any problems. To build
  35. the library:
  36. \begin{verbatim}
  37. python setup.py build
  38. \end{verbatim}
  39. If your OpenSSL header files aren't in \verb|/usr/include|, you may need to
  40. supply the \verb|-I| flag to let the setup script know where to look. The same
  41. goes for the libraries of course, use the \verb|-L| flag. Note that
  42. \verb|build| won't accept these flags, so you have to run first
  43. \verb|build_ext| and then \verb|build|! Example:
  44. \begin{verbatim}
  45. python setup.py build_ext -I/usr/local/ssl/include -L/usr/local/ssl/lib
  46. python setup.py build
  47. \end{verbatim}
  48. Now you should have a directory called \verb|OpenSSL| that contains e.g.
  49. \verb|SSL.so| and \verb|__init__.py| somewhere in the build dicrectory,
  50. so just:
  51. \begin{verbatim}
  52. python setup.py install
  53. \end{verbatim}
  54. If you, for some arcane reason, don't want the module to appear in the
  55. \verb|site-packages| directory, use the \verb|--prefix| option.
  56. You can, of course, do
  57. \begin{verbatim}
  58. python setup.py --help
  59. \end{verbatim}
  60. to find out more about how to use the script.
  61. \subsection{Building the Module on a Windows System \label{building-windows}}
  62. Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with
  63. Windows build instructions. Same as for Unix systems, we have to separate
  64. the \verb|build_ext| and the \verb|build|.
  65. Building the library:
  66. \begin{verbatim}
  67. setup.py build_ext -I ...\openssl\inc32 -L ...\openssl\out32dll
  68. setup.py build
  69. \end{verbatim}
  70. Where \verb|...\openssl| is of course the location of your OpenSSL installation.
  71. Installation is the same as for Unix systems:
  72. \begin{verbatim}
  73. setup.py install
  74. \end{verbatim}
  75. And similarily, you can do
  76. \begin{verbatim}
  77. setup.py --help
  78. \end{verbatim}
  79. to get more information.
  80. \section{\module{OpenSSL} --- Python interface to OpenSSL \label{openssl}}
  81. \declaremodule{extension}{OpenSSL}
  82. \modulesynopsis{Python interface to OpenSSL}
  83. This package provides a high-level interface to the functions in the
  84. OpenSSL library. The following modules are defined:
  85. \begin{datadesc}{crypto}
  86. Generic cryptographic module. Note that if anything is incomplete, this module is!
  87. \end{datadesc}
  88. \begin{datadesc}{rand}
  89. An interface to the OpenSSL pseudo random number generator.
  90. \end{datadesc}
  91. \begin{datadesc}{SSL}
  92. An interface to the SSL-specific parts of OpenSSL.
  93. \end{datadesc}
  94. % % % crypto moduleOpenSSL
  95. \subsection{\module{crypto} --- Generic cryptographic module \label{openssl-crypto}}
  96. \declaremodule{extension}{crypto}
  97. \modulesynopsis{Generic cryptographic module}
  98. \begin{datadesc}{X509Type}
  99. See \class{X509}.
  100. \end{datadesc}
  101. \begin{classdesc}{X509}{}
  102. A class representing X.509 certificates.
  103. \end{classdesc}
  104. \begin{datadesc}{X509NameType}
  105. See \class{X509Name}.
  106. \end{datadesc}
  107. \begin{classdesc}{X509Name}{x509name}
  108. A class representing X.509 Distinguished Names.
  109. This constructor creates a copy of \var{x509name} which should be an
  110. instance of \class{X509Name}.
  111. \end{classdesc}
  112. \begin{datadesc}{X509ReqType}
  113. See \class{X509Req}.
  114. \end{datadesc}
  115. \begin{classdesc}{X509Req}{}
  116. A class representing X.509 certificate requests.
  117. \end{classdesc}
  118. \begin{datadesc}{X509StoreType}
  119. A Python type object representing the X509Store object type.
  120. \end{datadesc}
  121. \begin{datadesc}{PKeyType}
  122. See \class{PKey}.
  123. \end{datadesc}
  124. \begin{classdesc}{PKey}{}
  125. A class representing DSA or RSA keys.
  126. \end{classdesc}
  127. \begin{datadesc}{PKCS7Type}
  128. A Python type object representing the PKCS7 object type.
  129. \end{datadesc}
  130. \begin{datadesc}{PKCS12Type}
  131. A Python type object representing the PKCS12 object type.
  132. \end{datadesc}
  133. \begin{datadesc}{X509ExtensionType}
  134. See \class{X509Extension}.
  135. \end{datadesc}
  136. \begin{classdesc}{X509Extension}{typename, critical, value\optional{, subject}\optional{, issuer}}
  137. A class representing an X.509 v3 certificate extensions.
  138. See \url{http://openssl.org/docs/apps/x509v3_config.html\#STANDARD_EXTENSIONS}
  139. for \var{typename} strings and their options.
  140. Optional parameters \var{subject} and \var{issuer} must be X509 objects.
  141. \end{classdesc}
  142. \begin{datadesc}{NetscapeSPKIType}
  143. See \class{NetscapeSPKI}.
  144. \end{datadesc}
  145. \begin{classdesc}{NetscapeSPKI}{\optional{enc}}
  146. A class representing Netscape SPKI objects.
  147. If the \var{enc} argument is present, it should be a base64-encoded string
  148. representing a NetscapeSPKI object, as returned by the \method{b64_encode}
  149. method.
  150. \end{classdesc}
  151. \begin{classdesc}{CRL}{}
  152. A class representing Certifcate Revocation List objects.
  153. \end{classdesc}
  154. \begin{classdesc}{Revoked}{}
  155. A class representing Revocation objects of CRL.
  156. \end{classdesc}
  157. \begin{datadesc}{FILETYPE_PEM}
  158. \dataline{FILETYPE_ASN1}
  159. File type constants.
  160. \end{datadesc}
  161. \begin{datadesc}{TYPE_RSA}
  162. \dataline{TYPE_DSA}
  163. Key type constants.
  164. \end{datadesc}
  165. \begin{excdesc}{Error}
  166. Generic exception used in the \module{crypto} module.
  167. \end{excdesc}
  168. \begin{funcdesc}{dump_certificate}{type, cert}
  169. Dump the certificate \var{cert} into a buffer string encoded with the type
  170. \var{type}.
  171. \end{funcdesc}
  172. \begin{funcdesc}{dump_certificate_request}{type, req}
  173. Dump the certificate request \var{req} into a buffer string encoded with the
  174. type \var{type}.
  175. \end{funcdesc}
  176. \begin{funcdesc}{dump_privatekey}{type, pkey\optional{, cipher, passphrase}}
  177. Dump the private key \var{pkey} into a buffer string encoded with the type
  178. \var{type}, optionally (if \var{type} is \constant{FILETYPE_PEM}) encrypting it
  179. using \var{cipher} and \var{passphrase}.
  180. \var{passphrase} must be either a string or a callback for providing the
  181. pass phrase.
  182. \end{funcdesc}
  183. \begin{funcdesc}{load_certificate}{type, buffer}
  184. Load a certificate (X509) from the string \var{buffer} encoded with the
  185. type \var{type}.
  186. \end{funcdesc}
  187. \begin{funcdesc}{load_certificate_request}{type, buffer}
  188. Load a certificate request (X509Req) from the string \var{buffer} encoded with
  189. the type \var{type}.
  190. \end{funcdesc}
  191. \begin{funcdesc}{load_privatekey}{type, buffer\optional{, passphrase}}
  192. Load a private key (PKey) from the string \var{buffer} encoded with
  193. the type \var{type} (must be one of \constant{FILETYPE_PEM} and
  194. \constant{FILETYPE_ASN1}).
  195. \var{passphrase} must be either a string or a callback for providing the
  196. pass phrase.
  197. \end{funcdesc}
  198. \begin{funcdesc}{load_crl}{type, buffer}
  199. Load Certificate Revocation List (CRL) data from a string \var{buffer}.
  200. \var{buffer} encoded with the type \var{type}. The type \var{type}
  201. must either \constant{FILETYPE_PEM} or \constant{FILETYPE_ASN1}).
  202. \end{funcdesc}
  203. \begin{funcdesc}{load_pkcs7_data}{type, buffer}
  204. Load pkcs7 data from the string \var{buffer} encoded with the type \var{type}.
  205. \end{funcdesc}
  206. \begin{funcdesc}{load_pkcs12}{buffer\optional{, passphrase}}
  207. Load pkcs12 data from the string \var{buffer}. If the pkcs12 structure is
  208. encrypted, a \var{passphrase} must be included. The MAC is always
  209. checked and thus required.
  210. See also the man page for the C function \function{PKCS12_parse}.
  211. \end{funcdesc}
  212. \begin{funcdesc}{sign}{key, data, digest}
  213. Sign a data string using the given key and message digest.
  214. \var{key} is a \code{PKey} instance. \var{data} is a \code{str} instance.
  215. \var{digest} is a \code{str} naming a supported message digest type, for example
  216. \code{``sha1''}.
  217. \versionadded{0.11}
  218. \end{funcdesc}
  219. \begin{funcdesc}{verify}{certificate, signature, data, digest}
  220. Verify the signature for a data string.
  221. \var{certificate} is a \code{X509} instance corresponding to the private key
  222. which generated the signature. \var{signature} is a \var{str} instance giving
  223. the signature itself. \var{data} is a \var{str} instance giving the data to
  224. which the signature applies. \var{digest} is a \var{str} instance naming the
  225. message digest type of the signature, for example \code{``sha1''}.
  226. \versionadded{0.11}
  227. \end{funcdesc}
  228. \subsubsection{X509 objects \label{openssl-x509}}
  229. X509 objects have the following methods:
  230. \begin{methoddesc}[X509]{get_issuer}{}
  231. Return an X509Name object representing the issuer of the certificate.
  232. \end{methoddesc}
  233. \begin{methoddesc}[X509]{get_pubkey}{}
  234. Return a PKey object representing the public key of the certificate.
  235. \end{methoddesc}
  236. \begin{methoddesc}[X509]{get_serial_number}{}
  237. Return the certificate serial number.
  238. \end{methoddesc}
  239. \begin{methoddesc}[X509]{get_signature_algorithm}{}
  240. Return the signature algorithm used in the certificate. If the algorithm is
  241. undefined, raise \code{ValueError}.
  242. \end{methoddesc}
  243. \begin{methoddesc}[X509]{get_subject}{}
  244. Return an X509Name object representing the subject of the certificate.
  245. \end{methoddesc}
  246. \begin{methoddesc}[X509]{get_version}{}
  247. Return the certificate version.
  248. \end{methoddesc}
  249. \begin{methoddesc}[X509]{get_notBefore}{}
  250. Return a string giving the time before which the certificate is not valid. The
  251. string is formatted as an ASN1 GENERALIZEDTIME:
  252. \begin{verbatim}
  253. YYYYMMDDhhmmssZ
  254. YYYYMMDDhhmmss+hhmm
  255. YYYYMMDDhhmmss-hhmm
  256. \end{verbatim}
  257. If no value exists for this field, \code{None} is returned.
  258. \end{methoddesc}
  259. \begin{methoddesc}[X509]{get_notAfter}{}
  260. Return a string giving the time after which the certificate is not valid. The
  261. string is formatted as an ASN1 GENERALIZEDTIME:
  262. \begin{verbatim}
  263. YYYYMMDDhhmmssZ
  264. YYYYMMDDhhmmss+hhmm
  265. YYYYMMDDhhmmss-hhmm
  266. \end{verbatim}
  267. If no value exists for this field, \code{None} is returned.
  268. \end{methoddesc}
  269. \begin{methoddesc}[X509]{set_notBefore}{when}
  270. Change the time before which the certificate is not valid. \var{when} is a
  271. string formatted as an ASN1 GENERALIZEDTIME:
  272. \begin{verbatim}
  273. YYYYMMDDhhmmssZ
  274. YYYYMMDDhhmmss+hhmm
  275. YYYYMMDDhhmmss-hhmm
  276. \end{verbatim}
  277. \end{methoddesc}
  278. \begin{methoddesc}[X509]{set_notAfter}{when}
  279. Change the time after which the certificate is not valid. \var{when} is a
  280. string formatted as an ASN1 GENERALIZEDTIME:
  281. \begin{verbatim}
  282. YYYYMMDDhhmmssZ
  283. YYYYMMDDhhmmss+hhmm
  284. YYYYMMDDhhmmss-hhmm
  285. \end{verbatim}
  286. \end{methoddesc}
  287. \begin{methoddesc}[X509]{gmtime_adj_notBefore}{time}
  288. Adjust the timestamp (in GMT) when the certificate starts being valid.
  289. \end{methoddesc}
  290. \begin{methoddesc}[X509]{gmtime_adj_notAfter}{time}
  291. Adjust the timestamp (in GMT) when the certificate stops being valid.
  292. \end{methoddesc}
  293. \begin{methoddesc}[X509]{has_expired}{}
  294. Checks the certificate's time stamp against current time. Returns true if the
  295. certificate has expired and false otherwise.
  296. \end{methoddesc}
  297. \begin{methoddesc}[X509]{set_issuer}{issuer}
  298. Set the issuer of the certificate to \var{issuer}.
  299. \end{methoddesc}
  300. \begin{methoddesc}[X509]{set_pubkey}{pkey}
  301. Set the public key of the certificate to \var{pkey}.
  302. \end{methoddesc}
  303. \begin{methoddesc}[X509]{set_serial_number}{serialno}
  304. Set the serial number of the certificate to \var{serialno}.
  305. \end{methoddesc}
  306. \begin{methoddesc}[X509]{set_subject}{subject}
  307. Set the subject of the certificate to \var{subject}.
  308. \end{methoddesc}
  309. \begin{methoddesc}[X509]{set_version}{version}
  310. Set the certificate version to \var{version}.
  311. \end{methoddesc}
  312. \begin{methoddesc}[X509]{sign}{pkey, digest}
  313. Sign the certificate, using the key \var{pkey} and the message digest algorithm
  314. identified by the string \var{digest}.
  315. \end{methoddesc}
  316. \begin{methoddesc}[X509]{subject_name_hash}{}
  317. Return the hash of the certificate subject.
  318. \end{methoddesc}
  319. \begin{methoddesc}[X509]{digest}{digest_name}
  320. Return a digest of the certificate, using the \var{digest_name} method.
  321. \var{digest_name} must be a string describing a digest algorithm supported
  322. by OpenSSL (by EVP_get_digestbyname, specifically). For example,
  323. \constant{"md5"} or \constant{"sha1"}.
  324. \end{methoddesc}
  325. \begin{methoddesc}[X509]{add_extensions}{extensions}
  326. Add the extensions in the sequence \var{extensions} to the certificate.
  327. \end{methoddesc}
  328. \begin{methoddesc}[X509]{get_extension_count}{}
  329. Return the number of extensions on this certificate.
  330. \versionadded{0.12}
  331. \end{methoddesc}
  332. \begin{methoddesc}[X509]{get_extension}{index}
  333. Retrieve the extension on this certificate at the given index.
  334. Extensions on a certificate are kept in order. The index parameter selects
  335. which extension will be returned. The returned object will be an X509Extension
  336. instance.
  337. \versionadded{0.12}
  338. \end{methoddesc}
  339. \subsubsection{X509Name objects \label{openssl-x509name}}
  340. X509Name objects have the following methods:
  341. \begin{methoddesc}[X509Name]{hash}{}
  342. Return an integer giving the first four bytes of the MD5 digest of the DER
  343. representation of the name.
  344. \end{methoddesc}
  345. \begin{methoddesc}[X509Name]{der}{}
  346. Return a string giving the DER representation of the name.
  347. \end{methoddesc}
  348. \begin{methoddesc}[X509Name]{get_components}{}
  349. Return a list of two-tuples of strings giving the components of the name.
  350. \end{methoddesc}
  351. X509Name objects have the following members:
  352. \begin{memberdesc}[X509Name]{countryName}
  353. The country of the entity. \code{C} may be used as an alias for
  354. \code{countryName}.
  355. \end{memberdesc}
  356. \begin{memberdesc}[X509Name]{stateOrProvinceName}
  357. The state or province of the entity. \code{ST} may be used as an alias for
  358. \code{stateOrProvinceName}·
  359. \end{memberdesc}
  360. \begin{memberdesc}[X509Name]{localityName}
  361. The locality of the entity. \code{L} may be used as an alias for
  362. \code{localityName}.
  363. \end{memberdesc}
  364. \begin{memberdesc}[X509Name]{organizationName}
  365. The organization name of the entity. \code{O} may be used as an alias for
  366. \code{organizationName}.
  367. \end{memberdesc}
  368. \begin{memberdesc}[X509Name]{organizationalUnitName}
  369. The organizational unit of the entity. \code{OU} may be used as an alias for
  370. \code{organizationalUnitName}.
  371. \end{memberdesc}
  372. \begin{memberdesc}[X509Name]{commonName}
  373. The common name of the entity. \code{CN} may be used as an alias for
  374. \code{commonName}.
  375. \end{memberdesc}
  376. \begin{memberdesc}[X509Name]{emailAddress}
  377. The e-mail address of the entity.
  378. \end{memberdesc}
  379. \subsubsection{X509Req objects \label{openssl-x509req}}
  380. X509Req objects have the following methods:
  381. \begin{methoddesc}[X509Req]{get_pubkey}{}
  382. Return a PKey object representing the public key of the certificate request.
  383. \end{methoddesc}
  384. \begin{methoddesc}[X509Req]{get_subject}{}
  385. Return an X509Name object representing the subject of the certificate.
  386. \end{methoddesc}
  387. \begin{methoddesc}[X509Req]{set_pubkey}{pkey}
  388. Set the public key of the certificate request to \var{pkey}.
  389. \end{methoddesc}
  390. \begin{methoddesc}[X509Req]{sign}{pkey, digest}
  391. Sign the certificate request, using the key \var{pkey} and the message digest
  392. algorithm identified by the string \var{digest}.
  393. \end{methoddesc}
  394. \begin{methoddesc}[X509Req]{verify}{pkey}
  395. Verify a certificate request using the public key \var{pkey}.
  396. \end{methoddesc}
  397. \begin{methoddesc}[X509Req]{set_version}{version}
  398. Set the version (RFC 2459, 4.1.2.1) of the certificate request to
  399. \var{version}.
  400. \end{methoddesc}
  401. \begin{methoddesc}[X509Req]{get_version}{}
  402. Get the version (RFC 2459, 4.1.2.1) of the certificate request.
  403. \end{methoddesc}
  404. \subsubsection{X509Store objects \label{openssl-x509store}}
  405. The X509Store object has currently just one method:
  406. \begin{methoddesc}[X509Store]{add_cert}{cert}
  407. Add the certificate \var{cert} to the certificate store.
  408. \end{methoddesc}
  409. \subsubsection{PKey objects \label{openssl-pkey}}
  410. The PKey object has the following methods:
  411. \begin{methoddesc}[PKey]{bits}{}
  412. Return the number of bits of the key.
  413. \end{methoddesc}
  414. \begin{methoddesc}[PKey]{generate_key}{type, bits}
  415. Generate a public/private key pair of the type \var{type} (one of
  416. \constant{TYPE_RSA} and \constant{TYPE_DSA}) with the size \var{bits}.
  417. \end{methoddesc}
  418. \begin{methoddesc}[PKey]{type}{}
  419. Return the type of the key.
  420. \end{methoddesc}
  421. \begin{methoddesc}[PKey]{check}{}
  422. Check the consistency of this key, returning True if it is consistent and
  423. raising an exception otherwise. This is only valid for RSA keys. See the
  424. OpenSSL RSA_check_key man page for further limitations.
  425. \end{methoddesc}
  426. \subsubsection{PKCS7 objects \label{openssl-pkcs7}}
  427. PKCS7 objects have the following methods:
  428. \begin{methoddesc}[PKCS7]{type_is_signed}{}
  429. FIXME
  430. \end{methoddesc}
  431. \begin{methoddesc}[PKCS7]{type_is_enveloped}{}
  432. FIXME
  433. \end{methoddesc}
  434. \begin{methoddesc}[PKCS7]{type_is_signedAndEnveloped}{}
  435. FIXME
  436. \end{methoddesc}
  437. \begin{methoddesc}[PKCS7]{type_is_data}{}
  438. FIXME
  439. \end{methoddesc}
  440. \begin{methoddesc}[PKCS7]{get_type_name}{}
  441. Get the type name of the PKCS7.
  442. \end{methoddesc}
  443. \subsubsection{PKCS12 objects \label{openssl-pkcs12}}
  444. PKCS12 objects have the following methods:
  445. \begin{methoddesc}[PKCS12]{export}{\optional{passphrase=None}\optional{, iter=2048}\optional{, maciter=1}}
  446. Returns a PKCS12 object as a string.
  447. The optional \var{passphrase} must be a string not a callback.
  448. See also the man page for the C function \function{PKCS12_create}.
  449. \end{methoddesc}
  450. \begin{methoddesc}[PKCS12]{get_ca_certificates}{}
  451. Return CA certificates within the PKCS12 object as a tuple. Returns
  452. \constant{None} if no CA certificates are present.
  453. \end{methoddesc}
  454. \begin{methoddesc}[PKCS12]{get_certificate}{}
  455. Return certificate portion of the PKCS12 structure.
  456. \end{methoddesc}
  457. \begin{methoddesc}[PKCS12]{get_friendlyname}{}
  458. Return friendlyName portion of the PKCS12 structure.
  459. \end{methoddesc}
  460. \begin{methoddesc}[PKCS12]{get_privatekey}{}
  461. Return private key portion of the PKCS12 structure
  462. \end{methoddesc}
  463. \begin{methoddesc}[PKCS12]{set_ca_certificates}{cacerts}
  464. Replace or set the CA certificates within the PKCS12 object with the sequence \var{cacerts}.
  465. Set \var{cacerts} to \constant{None} to remove all CA certificates.
  466. \end{methoddesc}
  467. \begin{methoddesc}[PKCS12]{set_certificate}{cert}
  468. Replace or set the certificate portion of the PKCS12 structure.
  469. \end{methoddesc}
  470. \begin{methoddesc}[PKCS12]{set_friendlyname}{name}
  471. Replace or set the friendlyName portion of the PKCS12 structure.
  472. \end{methoddesc}
  473. \begin{methoddesc}[PKCS12]{set_privatekey}{pkey}
  474. Replace or set private key portion of the PKCS12 structure
  475. \end{methoddesc}
  476. \subsubsection{X509Extension objects \label{openssl-509ext}}
  477. X509Extension objects have several methods:
  478. \begin{methoddesc}[X509Extension]{get_critical}{}
  479. Return the critical field of the extension object.
  480. \end{methoddesc}
  481. \begin{methoddesc}[X509Extension]{get_short_name}{}
  482. Retrieve the short descriptive name for this extension.
  483. The result is a byte string like \code{``basicConstraints''}.
  484. \versionadded{0.12}
  485. \end{methoddesc}
  486. \begin{methoddesc}[X509Extension]{get_data}{}
  487. Retrieve the data for this extension.
  488. The result is the ASN.1 encoded form of the extension data as a byte string.
  489. \versionadded{0.12}
  490. \end{methoddesc}
  491. \subsubsection{NetscapeSPKI objects \label{openssl-netscape-spki}}
  492. NetscapeSPKI objects have the following methods:
  493. \begin{methoddesc}[NetscapeSPKI]{b64_encode}{}
  494. Return a base64-encoded string representation of the object.
  495. \end{methoddesc}
  496. \begin{methoddesc}[NetscapeSPKI]{get_pubkey}{}
  497. Return the public key of object.
  498. \end{methoddesc}
  499. \begin{methoddesc}[NetscapeSPKI]{set_pubkey}{key}
  500. Set the public key of the object to \var{key}.
  501. \end{methoddesc}
  502. \begin{methoddesc}[NetscapeSPKI]{sign}{key, digest_name}
  503. Sign the NetscapeSPKI object using the given \var{key} and
  504. \var{digest_name}. \var{digest_name} must be a string describing a digest
  505. algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For
  506. example, \constant{"md5"} or \constant{"sha1"}.
  507. \end{methoddesc}
  508. \begin{methoddesc}[NetscapeSPKI]{verify}{key}
  509. Verify the NetscapeSPKI object using the given \var{key}.
  510. \end{methoddesc}
  511. \subsubsection{CRL objects \label{crl}}
  512. CRL objects have the following methods:
  513. \begin{methoddesc}[CRL]{add_revoked}{revoked}
  514. Add a Revoked object to the CRL, by value not reference.
  515. \end{methoddesc}
  516. \begin{methoddesc}[CRL]{export}{cert, key\optional{, type=FILETYPE_PEM}\optional{, days=100}}
  517. Use \var{cert} and \var{key} to sign the CRL and return the CRL as a string.
  518. \var{days} is the number of days before the next CRL is due.
  519. \end{methoddesc}
  520. \begin{methoddesc}[CRL]{get_revoked}{}
  521. Return a tuple of Revoked objects, by value not reference.
  522. \end{methoddesc}
  523. \subsubsection{Revoked objects \label{revoked}}
  524. Revoked objects have the following methods:
  525. \begin{methoddesc}[Revoked]{all_reasons}{}
  526. Return a list of all supported reasons.
  527. \end{methoddesc}
  528. \begin{methoddesc}[Revoked]{get_reason}{}
  529. Return the revocation reason as a str. Can be
  530. None, which differs from "Unspecified".
  531. \end{methoddesc}
  532. \begin{methoddesc}[Revoked]{get_rev_date}{}
  533. Return the revocation date as a str.
  534. The string is formatted as an ASN1 GENERALIZEDTIME.
  535. \end{methoddesc}
  536. \begin{methoddesc}[Revoked]{get_serial}{}
  537. Return a str containing a hex number of the serial of the revoked certificate.
  538. \end{methoddesc}
  539. \begin{methoddesc}[Revoked]{set_reason}{reason}
  540. Set the revocation reason. \var{reason} must
  541. be None or a string, but the values are limited.
  542. Spaces and case are ignored. See \method{all_reasons}.
  543. \end{methoddesc}
  544. \begin{methoddesc}[Revoked]{set_rev_date}{date}
  545. Set the revocation date.
  546. The string is formatted as an ASN1 GENERALIZEDTIME.
  547. \end{methoddesc}
  548. \begin{methoddesc}[Revoked]{set_serial}{serial}
  549. \var{serial} is a string containing a hex number of the serial of the revoked certificate.
  550. \end{methoddesc}
  551. % % % rand module
  552. \subsection{\module{rand} --- An interface to the OpenSSL pseudo random number generator \label{openssl-rand}}
  553. \declaremodule{extension}{rand}
  554. \modulesynopsis{An interface to the OpenSSL pseudo random number generator}
  555. This module handles the OpenSSL pseudo random number generator (PRNG) and
  556. declares the following:
  557. \begin{funcdesc}{add}{string, entropy}
  558. Mix bytes from \var{string} into the PRNG state. The \var{entropy} argument is
  559. (the lower bound of) an estimate of how much randomness is contained in
  560. \var{string}, measured in bytes. For more information, see e.g. \rfc{1750}.
  561. \end{funcdesc}
  562. \begin{funcdesc}{bytes}{num_bytes}
  563. Get some random bytes from the PRNG as a string.
  564. This is a wrapper for the C function \function{RAND_bytes}.
  565. \end{funcdesc}
  566. \begin{funcdesc}{cleanup}{}
  567. Erase the memory used by the PRNG.
  568. This is a wrapper for the C function \function{RAND_cleanup}.
  569. \end{funcdesc}
  570. \begin{funcdesc}{egd}{path\optional{, bytes}}
  571. Query the Entropy Gathering Daemon\footnote{See
  572. \url{http://www.lothar.com/tech/crypto/}} on socket \var{path} for \var{bytes}
  573. bytes of random data and and uses \function{add} to seed the PRNG. The default
  574. value of \var{bytes} is 255.
  575. \end{funcdesc}
  576. \begin{funcdesc}{load_file}{path\optional{, bytes}}
  577. Read \var{bytes} bytes (or all of it, if \var{bytes} is negative) of data from
  578. the file \var{path} to seed the PRNG. The default value of \var{bytes} is -1.
  579. \end{funcdesc}
  580. \begin{funcdesc}{screen}{}
  581. Add the current contents of the screen to the PRNG state.
  582. Availability: Windows.
  583. \end{funcdesc}
  584. \begin{funcdesc}{seed}{string}
  585. This is equivalent to calling \function{add} with \var{entropy} as the length
  586. of the string.
  587. \end{funcdesc}
  588. \begin{funcdesc}{status}{}
  589. Returns true if the PRNG has been seeded with enough data, and false otherwise.
  590. \end{funcdesc}
  591. \begin{funcdesc}{write_file}{path}
  592. Write a number of random bytes (currently 1024) to the file \var{path}. This
  593. file can then be used with \function{load_file} to seed the PRNG again.
  594. \end{funcdesc}
  595. \begin{excdesc}{Error}
  596. If the current RAND method supports any errors, this is raised when needed.
  597. The default method does not raise this when the entropy pool is depleted.
  598. Whenever this exception is raised directly, it has a list of error messages
  599. from the OpenSSL error queue, where each item is a tuple \code{(\var{lib},
  600. \var{function}, \var{reason})}. Here \var{lib}, \var{function} and \var{reason}
  601. are all strings, describing where and what the problem is. See \manpage{err}{3}
  602. for more information.
  603. \end{excdesc}
  604. % % % SSL module
  605. \subsection{\module{SSL} --- An interface to the SSL-specific parts of OpenSSL \label{openssl-ssl}}
  606. \declaremodule{extension}{SSL}
  607. \modulesynopsis{An interface to the SSL-specific parts of OpenSSL}
  608. This module handles things specific to SSL. There are two objects defined:
  609. Context, Connection.
  610. \begin{datadesc}{SSLv2_METHOD}
  611. \dataline{SSLv3_METHOD}
  612. \dataline{SSLv23_METHOD}
  613. \dataline{TLSv1_METHOD}
  614. These constants represent the different SSL methods to use when creating a
  615. context object.
  616. \end{datadesc}
  617. \begin{datadesc}{VERIFY_NONE}
  618. \dataline{VERIFY_PEER}
  619. \dataline{VERIFY_FAIL_IF_NO_PEER_CERT}
  620. These constants represent the verification mode used by the Context
  621. object's \method{set_verify} method.
  622. \end{datadesc}
  623. \begin{datadesc}{FILETYPE_PEM}
  624. \dataline{FILETYPE_ASN1}
  625. File type constants used with the \method{use_certificate_file} and
  626. \method{use_privatekey_file} methods of Context objects.
  627. \end{datadesc}
  628. \begin{datadesc}{OP_SINGLE_DH_USE}
  629. \dataline{OP_EPHEMERAL_RSA}
  630. \dataline{OP_NO_SSLv2}
  631. \dataline{OP_NO_SSLv3}
  632. \dataline{OP_NO_TLSv1}
  633. Constants used with \method{set_options} of Context objects.
  634. \constant{OP_SINGLE_DH_USE} means to always create a new key when using ephemeral
  635. Diffie-Hellman. \constant{OP_EPHEMERAL_RSA} means to always use ephemeral RSA keys
  636. when doing RSA operations. \constant{OP_NO_SSLv2}, \constant{OP_NO_SSLv3} and
  637. \constant{OP_NO_TLSv1} means to disable those specific protocols. This is
  638. interesting if you're using e.g. \constant{SSLv23_METHOD} to get an SSLv2-compatible
  639. handshake, but don't want to use SSLv2.
  640. \end{datadesc}
  641. \begin{datadesc}{SSLEAY_VERSION}
  642. \dataline{SSLEAY_CFLAGS}
  643. \dataline{SSLEAY_BUILT_ON}
  644. \dataline{SSLEAY_PLATFORM}
  645. \dataline{SSLEAY_DIR}
  646. Constants used with \method{SSLeay_version} to specify what OpenSSL version
  647. information to retrieve. See the man page for the \function{SSLeay_version} C
  648. API for details.
  649. \end{datadesc}
  650. \begin{datadesc}{OPENSSL_VERSION_NUMBER}
  651. An integer giving the version number of the OpenSSL library used to build this
  652. version of pyOpenSSL. See the man page for the \function{SSLeay_version} C API
  653. for details.
  654. \end{datadesc}
  655. \begin{funcdesc}{SSLeay_version}{type}
  656. Retrieve a string describing some aspect of the underlying OpenSSL version. The
  657. type passed in should be one of the \constant{SSLEAY_*} constants defined in
  658. this module.
  659. \end{funcdesc}
  660. \begin{datadesc}{ContextType}
  661. See \class{Context}.
  662. \end{datadesc}
  663. \begin{classdesc}{Context}{method}
  664. A class representing SSL contexts. Contexts define the parameters of one or
  665. more SSL connections.
  666. \var{method} should be \constant{SSLv2_METHOD}, \constant{SSLv3_METHOD},
  667. \constant{SSLv23_METHOD} or \constant{TLSv1_METHOD}.
  668. \end{classdesc}
  669. \begin{datadesc}{ConnectionType}
  670. See \class{Connection}.
  671. \end{datadesc}
  672. \begin{classdesc}{Connection}{context, socket}
  673. A class representing SSL connections.
  674. \var{context} should be an instance of \class{Context} and \var{socket}
  675. should be a socket \footnote{Actually, all that is required is an object
  676. that \emph{behaves} like a socket, you could even use files, even though
  677. it'd be tricky to get the handshakes right!} object. \var{socket} may be
  678. \var{None}; in this case, the Connection is created with a memory BIO: see
  679. the \method{bio_read}, \method{bio_write}, and \method{bio_shutdown}
  680. methods.
  681. \end{classdesc}
  682. \begin{excdesc}{Error}
  683. This exception is used as a base class for the other SSL-related
  684. exceptions, but may also be raised directly.
  685. Whenever this exception is raised directly, it has a list of error messages
  686. from the OpenSSL error queue, where each item is a tuple \code{(\var{lib},
  687. \var{function}, \var{reason})}. Here \var{lib}, \var{function} and \var{reason}
  688. are all strings, describing where and what the problem is. See \manpage{err}{3}
  689. for more information.
  690. \end{excdesc}
  691. \begin{excdesc}{ZeroReturnError}
  692. This exception matches the error return code \code{SSL_ERROR_ZERO_RETURN}, and
  693. is raised when the SSL Connection has been closed. In SSL 3.0 and TLS 1.0, this
  694. only occurs if a closure alert has occurred in the protocol, i.e. the
  695. connection has been closed cleanly. Note that this does not necessarily
  696. mean that the transport layer (e.g. a socket) has been closed.
  697. It may seem a little strange that this is an exception, but it does match an
  698. \code{SSL_ERROR} code, and is very convenient.
  699. \end{excdesc}
  700. \begin{excdesc}{WantReadError}
  701. The operation did not complete; the same I/O method should be called again
  702. later, with the same arguments. Any I/O method can lead to this since new
  703. handshakes can occur at any time.
  704. The wanted read is for \emph{dirty} data sent over the network, not the
  705. \emph{clean} data inside the tunnel. For a socket based SSL connection,
  706. \emph{read} means data coming at us over the network. Until that read
  707. succeeds, the attempted \method{OpenSSL.SSL.Connection.recv},
  708. \method{OpenSSL.SSL.Connection.send}, or
  709. \method{OpenSSL.SSL.Connection.do_handshake} is prevented or incomplete. You
  710. probably want to \method{select()} on the socket before trying again.
  711. \end{excdesc}
  712. \begin{excdesc}{WantWriteError}
  713. See \exception{WantReadError}. The socket send buffer may be too full to
  714. write more data.
  715. \end{excdesc}
  716. \begin{excdesc}{WantX509LookupError}
  717. The operation did not complete because an application callback has asked to be
  718. called again. The I/O method should be called again later, with the same
  719. arguments. Note: This won't occur in this version, as there are no such
  720. callbacks in this version.
  721. \end{excdesc}
  722. \begin{excdesc}{SysCallError}
  723. The \exception{SysCallError} occurs when there's an I/O error and OpenSSL's
  724. error queue does not contain any information. This can mean two things: An
  725. error in the transport protocol, or an end of file that violates the protocol.
  726. The parameter to the exception is always a pair \code{(\var{errnum},
  727. \var{errstr})}.
  728. \end{excdesc}
  729. \subsubsection{Context objects \label{openssl-context}}
  730. Context objects have the following methods:
  731. \begin{methoddesc}[Context]{check_privatekey}{}
  732. Check if the private key (loaded with \method{use_privatekey\optional{_file}})
  733. matches the certificate (loaded with \method{use_certificate\optional{_file}}).
  734. Returns \code{None} if they match, raises \exception{Error} otherwise.
  735. \end{methoddesc}
  736. \begin{methoddesc}[Context]{get_app_data}{}
  737. Retrieve application data as set by \method{set_app_data}.
  738. \end{methoddesc}
  739. \begin{methoddesc}[Context]{get_cert_store}{}
  740. Retrieve the certificate store (a X509Store object) that the context uses.
  741. This can be used to add "trusted" certificates without using the.
  742. \method{load_verify_locations()} method.
  743. \end{methoddesc}
  744. \begin{methoddesc}[Context]{get_timeout}{}
  745. Retrieve session timeout, as set by \method{set_timeout}. The default is 300
  746. seconds.
  747. \end{methoddesc}
  748. \begin{methoddesc}[Context]{get_verify_depth}{}
  749. Retrieve the Context object's verify depth, as set by
  750. \method{set_verify_depth}.
  751. \end{methoddesc}
  752. \begin{methoddesc}[Context]{get_verify_mode}{}
  753. Retrieve the Context object's verify mode, as set by \method{set_verify}.
  754. \end{methoddesc}
  755. \begin{methoddesc}[Context]{load_client_ca}{pemfile}
  756. Read a file with PEM-formatted certificates that will be sent to the client
  757. when requesting a client certificate.
  758. \end{methoddesc}
  759. \begin{methoddesc}[Context]{set_client_ca_list}{certificate_authorities}
  760. Replace the current list of preferred certificate signers that would be
  761. sent to the client when requesting a client certificate with the
  762. \var{certificate_authorities} sequence of \class{OpenSSL.crypto.X509Name}s.
  763. \versionadded{0.10}
  764. \end{methoddesc}
  765. \begin{methoddesc}[Context]{add_client_ca}{certificate_authority}
  766. Extract a \class{OpenSSL.crypto.X509Name} from the \var{certificate_authority}
  767. \class{OpenSSL.crypto.X509} certificate and add it to the list of preferred
  768. certificate signers sent to the client when requesting a client certificate.
  769. \versionadded{0.10}
  770. \end{methoddesc}
  771. \begin{methoddesc}[Context]{load_verify_locations}{pemfile, capath}
  772. Specify where CA certificates for verification purposes are located. These
  773. are trusted certificates. Note that the certificates have to be in PEM
  774. format. If capath is passed, it must be a directory prepared using the
  775. \code{c_rehash} tool included with OpenSSL. Either, but not both, of
  776. \var{pemfile} or \var{capath} may be \code{None}.
  777. \end{methoddesc}
  778. \begin{methoddesc}[Context]{set_default_verify_paths}{}
  779. Specify that the platform provided CA certificates are to be used for
  780. verification purposes. This method may not work properly on OS X.
  781. \end{methoddesc}
  782. \begin{methoddesc}[Context]{load_tmp_dh}{dhfile}
  783. Load parameters for Ephemeral Diffie-Hellman from \var{dhfile}.
  784. \end{methoddesc}
  785. \begin{methoddesc}[Context]{set_app_data}{data}
  786. Associate \var{data} with this Context object. \var{data} can be retrieved
  787. later using the \method{get_app_data} method.
  788. \end{methoddesc}
  789. \begin{methoddesc}[Context]{set_cipher_list}{ciphers}
  790. Set the list of ciphers to be used in this context. See the OpenSSL manual for
  791. more information (e.g. ciphers(1))
  792. \end{methoddesc}
  793. \begin{methoddesc}[Context]{set_info_callback}{callback}
  794. Set the information callback to \var{callback}. This function will be called
  795. from time to time during SSL handshakes.
  796. \var{callback} should take three arguments: a Connection object and two
  797. integers. The first integer specifies where in the SSL handshake the function
  798. was called, and the other the return code from a (possibly failed) internal
  799. function call.
  800. \end{methoddesc}
  801. \begin{methoddesc}[Context]{set_options}{options}
  802. Add SSL options. Options you have set before are not cleared!
  803. This method should be used with the \constant{OP_*} constants.
  804. \end{methoddesc}
  805. \begin{methoddesc}[Context]{set_passwd_cb}{callback\optional{, userdata}}
  806. Set the passphrase callback to \var{callback}. This function will be called
  807. when a private key with a passphrase is loaded. \var{callback} must accept
  808. three positional arguments. First, an integer giving the maximum length of
  809. the passphrase it may return. If the returned passphrase is longer than
  810. this, it will be truncated. Second, a boolean value which will be true if
  811. the user should be prompted for the passphrase twice and the callback should
  812. verify that the two values supplied are equal. Third, the value given as the
  813. \var{userdata} parameter to \method{set_passwd_cb}. If an error occurs,
  814. \var{callback} should return a false value (e.g. an empty string).
  815. \end{methoddesc}
  816. \begin{methoddesc}[Context]{set_session_id}{name}
  817. Set the context \var{name} within which a session can be reused for this
  818. Context object. This is needed when doing session resumption, because there is
  819. no way for a stored session to know which Context object it is associated with.
  820. \var{name} may be any binary data.
  821. \end{methoddesc}
  822. \begin{methoddesc}[Context]{set_timeout}{timeout}
  823. Set the timeout for newly created sessions for this Context object to
  824. \var{timeout}. \var{timeout} must be given in (whole) seconds. The default
  825. value is 300 seconds. See the OpenSSL manual for more information (e.g.
  826. SSL_CTX_set_timeout(3)).
  827. \end{methoddesc}
  828. \begin{methoddesc}[Context]{set_verify}{mode, callback}
  829. Set the verification flags for this Context object to \var{mode} and specify
  830. that \var{callback} should be used for verification callbacks. \var{mode}
  831. should be one of \constant{VERIFY_NONE} and \constant{VERIFY_PEER}. If
  832. \constant{VERIFY_PEER} is used, \var{mode} can be OR:ed with
  833. \constant{VERIFY_FAIL_IF_NO_PEER_CERT} and \constant{VERIFY_CLIENT_ONCE} to
  834. further control the behaviour.
  835. \var{callback} should take five arguments: A Connection object, an X509 object,
  836. and three integer variables, which are in turn potential error number, error
  837. depth and return code. \var{callback} should return true if verification passes
  838. and false otherwise.
  839. \end{methoddesc}
  840. \begin{methoddesc}[Context]{set_verify_depth}{depth}
  841. Set the maximum depth for the certificate chain verification that shall be
  842. allowed for this Context object.
  843. \end{methoddesc}
  844. \begin{methoddesc}[Context]{use_certificate}{cert}
  845. Use the certificate \var{cert} which has to be a X509 object.
  846. \end{methoddesc}
  847. \begin{methoddesc}[Context]{add_extra_chain_cert}{cert}
  848. Adds the certificate \var{cert}, which has to be a X509 object, to the
  849. certificate chain presented together with the certificate.
  850. \end{methoddesc}
  851. \begin{methoddesc}[Context]{use_certificate_chain_file}{file}
  852. Load a certificate chain from \var{file} which must be PEM encoded.
  853. \end{methoddesc}
  854. \begin{methoddesc}[Context]{use_privatekey}{pkey}
  855. Use the private key \var{pkey} which has to be a PKey object.
  856. \end{methoddesc}
  857. \begin{methoddesc}[Context]{use_certificate_file}{file\optional{, format}}
  858. Load the first certificate found in \var{file}. The certificate must be in the
  859. format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
  860. \constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
  861. \end{methoddesc}
  862. \begin{methoddesc}[Context]{use_privatekey_file}{file\optional{, format}}
  863. Load the first private key found in \var{file}. The private key must be in the
  864. format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
  865. \constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
  866. \end{methoddesc}
  867. \begin{methoddesc}[Context]{set_tlsext_servername_callback}{callback}
  868. Specify a one-argument callable to use as the TLS extension server name
  869. callback. When a connection using the server name extension is made using this
  870. context, the callback will be invoked with the \code{Connection} instance.
  871. \versionadded{0.13}
  872. \end{methoddesc}
  873. \subsubsection{Connection objects \label{openssl-connection}}
  874. Connection objects have the following methods:
  875. \begin{methoddesc}[Connection]{accept}{}
  876. Call the \method{accept} method of the underlying socket and set up SSL on the
  877. returned socket, using the Context object supplied to this Connection object at
  878. creation. Returns a pair \code{(\var{conn}, \var{address})}. where \var{conn}
  879. is the new Connection object created, and \var{address} is as returned by the
  880. socket's \method{accept}.
  881. \end{methoddesc}
  882. \begin{methoddesc}[Connection]{bind}{address}
  883. Call the \method{bind} method of the underlying socket.
  884. \end{methoddesc}
  885. \begin{methoddesc}[Connection]{close}{}
  886. Call the \method{close} method of the underlying socket. Note: If you want
  887. correct SSL closure, you need to call the \method{shutdown} method first.
  888. \end{methoddesc}
  889. \begin{methoddesc}[Connection]{connect}{address}
  890. Call the \method{connect} method of the underlying socket and set up SSL on the
  891. socket, using the Context object supplied to this Connection object at
  892. creation.
  893. \end{methoddesc}
  894. \begin{methoddesc}[Connection]{connect_ex}{address}
  895. Call the \method{connect_ex} method of the underlying socket and set up SSL on
  896. the socket, using the Context object supplied to this Connection object at
  897. creation. Note that if the \method{connect_ex} method of the socket doesn't
  898. return 0, SSL won't be initialized.
  899. \end{methoddesc}
  900. \begin{methoddesc}[Connection]{do_handshake}{}
  901. Perform an SSL handshake (usually called after \method{renegotiate} or one of
  902. \method{set_accept_state} or \method{set_accept_state}). This can raise the
  903. same exceptions as \method{send} and \method{recv}.
  904. \end{methoddesc}
  905. \begin{methoddesc}[Connection]{fileno}{}
  906. Retrieve the file descriptor number for the underlying socket.
  907. \end{methoddesc}
  908. \begin{methoddesc}[Connection]{listen}{backlog}
  909. Call the \method{listen} method of the underlying socket.
  910. \end{methoddesc}
  911. \begin{methoddesc}[Connection]{get_app_data}{}
  912. Retrieve application data as set by \method{set_app_data}.
  913. \end{methoddesc}
  914. \begin{methoddesc}[Connection]{get_cipher_list}{}
  915. Retrieve the list of ciphers used by the Connection object. WARNING: This API
  916. has changed. It used to take an optional parameter and just return a string,
  917. but not it returns the entire list in one go.
  918. \end{methoddesc}
  919. \begin{methoddesc}[Connection]{get_client_ca_list}{}
  920. Retrieve the list of preferred client certificate issuers sent by the server
  921. as \class{OpenSSL.crypto.X509Name} objects.
  922. If this is a client \class{Connection}, the list will be empty until the
  923. connection with the server is established.
  924. If this is a server \class{Connection}, return the list of certificate
  925. authorities that will be sent or has been sent to the client, as controlled
  926. by this \class{Connection}'s \class{Context}.
  927. \versionadded{0.10}
  928. \end{methoddesc}
  929. \begin{methoddesc}[Connection]{get_context}{}
  930. Retrieve the Context object associated with this Connection.
  931. \end{methoddesc}
  932. \begin{methoddesc}[Connection]{set_context}{context}
  933. Specify a replacement Context object for this Connection.
  934. \end{methoddesc}
  935. \begin{methoddesc}[Connection]{get_peer_certificate}{}
  936. Retrieve the other side's certificate (if any)
  937. \end{methoddesc}
  938. \begin{methoddesc}[Connection]{get_peer_cert_chain}{}
  939. Retrieve the tuple of the other side's certificate chain (if any)
  940. \end{methoddesc}
  941. \begin{methoddesc}[Connection]{getpeername}{}
  942. Call the \method{getpeername} method of the underlying socket.
  943. \end{methoddesc}
  944. \begin{methoddesc}[Connection]{getsockname}{}
  945. Call the \method{getsockname} method of the underlying socket.
  946. \end{methoddesc}
  947. \begin{methoddesc}[Connection]{getsockopt}{level, optname\optional{, buflen}}
  948. Call the \method{getsockopt} method of the underlying socket.
  949. \end{methoddesc}
  950. \begin{methoddesc}[Connection]{pending}{}
  951. Retrieve the number of bytes that can be safely read from the SSL buffer
  952. (\emph{not} the underlying transport buffer).
  953. \end{methoddesc}
  954. \begin{methoddesc}[Connection]{recv}{bufsize}
  955. Receive data from the Connection. The return value is a string representing the
  956. data received. The maximum amount of data to be received at once, is specified
  957. by \var{bufsize}.
  958. \end{methoddesc}
  959. \begin{methoddesc}[Connection]{bio_write}{bytes}
  960. If the Connection was created with a memory BIO, this method can be used to add
  961. bytes to the read end of that memory BIO. The Connection can then read the
  962. bytes (for example, in response to a call to \method{recv}).
  963. \end{methoddesc}
  964. \begin{methoddesc}[Connection]{renegotiate}{}
  965. Renegotiate the SSL session. Call this if you wish to change cipher suites or
  966. anything like that.
  967. \end{methoddesc}
  968. \begin{methoddesc}[Connection]{send}{string}
  969. Send the \var{string} data to the Connection.
  970. \end{methoddesc}
  971. \begin{methoddesc}[Connection]{bio_read}{bufsize}
  972. If the Connection was created with a memory BIO, this method can be used to
  973. read bytes from the write end of that memory BIO. Many Connection methods will
  974. add bytes which must be read in this manner or the buffer will eventually fill
  975. up and the Connection will be able to take no further actions.
  976. \end{methoddesc}
  977. \begin{methoddesc}[Connection]{sendall}{string}
  978. Send all of the \var{string} data to the Connection. This calls \method{send}
  979. repeatedly until all data is sent. If an error occurs, it's impossible to tell
  980. how much data has been sent.
  981. \end{methoddesc}
  982. \begin{methoddesc}[Connection]{set_accept_state}{}
  983. Set the connection to work in server mode. The handshake will be handled
  984. automatically by read/write.
  985. \end{methoddesc}
  986. \begin{methoddesc}[Connection]{set_app_data}{data}
  987. Associate \var{data} with this Connection object. \var{data} can be retrieved
  988. later using the \method{get_app_data} method.
  989. \end{methoddesc}
  990. \begin{methoddesc}[Connection]{set_connect_state}{}
  991. Set the connection to work in client mode. The handshake will be handled
  992. automatically by read/write.
  993. \end{methoddesc}
  994. \begin{methoddesc}[Connection]{setblocking}{flag}
  995. Call the \method{setblocking} method of the underlying socket.
  996. \end{methoddesc}
  997. \begin{methoddesc}[Connection]{setsockopt}{level, optname, value}
  998. Call the \method{setsockopt} method of the underlying socket.
  999. \end{methoddesc}
  1000. \begin{methoddesc}[Connection]{shutdown}{}
  1001. Send the shutdown message to the Connection. Returns true if the shutdown
  1002. message exchange is completed and false otherwise (in which case you call
  1003. \method{recv()} or \method{send()} when the connection becomes
  1004. readable/writeable.
  1005. \end{methoddesc}
  1006. \begin{methoddesc}[Connection]{get_shutdown}{}
  1007. Get the shutdown state of the Connection. Returns a bitvector of either or
  1008. both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
  1009. \end{methoddesc}
  1010. \begin{methoddesc}[Connection]{set_shutdown}{state}
  1011. Set the shutdown state of the Connection. \var{state} is a bitvector of
  1012. either or both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
  1013. \end{methoddesc}
  1014. \begin{methoddesc}[Connection]{sock_shutdown}{how}
  1015. Call the \method{shutdown} method of the underlying socket.
  1016. \end{methoddesc}
  1017. \begin{methoddesc}[Connection]{bio_shutdown}{}
  1018. If the Connection was created with a memory BIO, this method can be used to
  1019. indicate that ``end of file'' has been reached on the read end of that memory
  1020. BIO.
  1021. \end{methoddesc}
  1022. \begin{methoddesc}[Connection]{state_string}{}
  1023. Retrieve a verbose string detailing the state of the Connection.
  1024. \end{methoddesc}
  1025. \begin{methoddesc}[Connection]{client_random}{}
  1026. Retrieve the random value used with the client hello message.
  1027. \end{methoddesc}
  1028. \begin{methoddesc}[Connection]{server_random}{}
  1029. Retrieve the random value used with the server hello message.
  1030. \end{methoddesc}
  1031. \begin{methoddesc}[Connection]{master_key}{}
  1032. Retrieve the value of the master key for this session.
  1033. \end{methoddesc}
  1034. \begin{methoddesc}[Connection]{want_read}{}
  1035. Checks if more data has to be read from the transport layer to complete an
  1036. operation.
  1037. \end{methoddesc}
  1038. \begin{methoddesc}[Connection]{want_write}{}
  1039. Checks if there is data to write to the transport layer to complete an
  1040. operation.
  1041. \end{methoddesc}
  1042. \begin{methoddesc}[Connection]{set_tlsext_host_name}{name}
  1043. Specify the byte string to send as the server name in the client hello message.
  1044. \versionadded{0.13}
  1045. \end{methoddesc}
  1046. \begin{methoddesc}[Connection]{get_servername}{}
  1047. Get the value of the server name received in the client hello message.
  1048. \versionadded{0.13}
  1049. \end{methoddesc}
  1050. \section{Internals \label{internals}}
  1051. We ran into three main problems developing this: Exceptions, callbacks and
  1052. accessing socket methods. This is what this chapter is about.
  1053. \subsection{Exceptions \label{exceptions}}
  1054. We realized early that most of the exceptions would be raised by the I/O
  1055. functions of OpenSSL, so it felt natural to mimic OpenSSL's error code system,
  1056. translating them into Python exceptions. This naturally gives us the exceptions
  1057. \exception{SSL.ZeroReturnError}, \exception{SSL.WantReadError},
  1058. \exception{SSL.WantWriteError}, \exception{SSL.WantX509LookupError} and
  1059. \exception{SSL.SysCallError}.
  1060. For more information about this, see section \ref{openssl-ssl}.
  1061. \subsection{Callbacks \label{callbacks}}
  1062. There are a number of problems with callbacks. First of all, OpenSSL is written
  1063. as a C library, it's not meant to have Python callbacks, so a way around that
  1064. is needed. Another problem is thread support. A lot of the OpenSSL I/O
  1065. functions can block if the socket is in blocking mode, and then you want other
  1066. Python threads to be able to do other things. The real trouble is if you've
  1067. released the global CPython interpreter lock to do a potentially blocking
  1068. operation, and the operation calls a callback. Then we must take the GIL back,
  1069. since calling Python APIs without holding it is not allowed.
  1070. There are two solutions to the first problem, both of which are necessary. The
  1071. first solution to use is if the C callback allows ''userdata'' to be passed to
  1072. it (an arbitrary pointer normally). This is great! We can set our Python
  1073. function object as the real userdata and emulate userdata for the Python
  1074. function in another way. The other solution can be used if an object with an
  1075. ''app_data'' system always is passed to the callback. For example, the SSL
  1076. object in OpenSSL has app_data functions and in e.g. the verification
  1077. callbacks, you can retrieve the related SSL object. What we do is to set our
  1078. wrapper \class{Connection} object as app_data for the SSL object, and we can
  1079. easily find the Python callback.
  1080. The other problem is solved using thread local variables. Whenever the GIL is
  1081. released before calling into an OpenSSL API, the PyThreadState pointer returned
  1082. by \cfunction{PyEval_SaveState} is stored in a global thread local variable
  1083. (using Python's own TLS API, \cfunction{PyThread_set_key_value}). When it is
  1084. necessary to re-acquire the GIL, either after the OpenSSL API returns or in a C
  1085. callback invoked by that OpenSSL API, the value of the thread local variable is
  1086. retrieved (\cfunction{PyThread_get_key_value}) and used to re-acquire the GIL.
  1087. This allows Python threads to execute while OpenSSL APIs are running and allows
  1088. use of any particular pyOpenSSL object from any Python thread, since there is
  1089. no per-thread state associated with any of these objects and since OpenSSL is
  1090. threadsafe (as long as properly initialized, as pyOpenSSL initializes it).
  1091. \subsection{Acessing Socket Methods \label{socket-methods}}
  1092. We quickly saw the benefit of wrapping socket methods in the
  1093. \class{SSL.Connection} class, for an easy transition into using SSL. The
  1094. problem here is that the \module{socket} module lacks a C API, and all the
  1095. methods are declared static. One approach would be to have \module{OpenSSL} as
  1096. a submodule to the \module{socket} module, placing all the code in
  1097. \file{socketmodule.c}, but this is obviously not a good solution, since you
  1098. might not want to import tonnes of extra stuff you're not going to use when
  1099. importing the \module{socket} module. The other approach is to somehow get a
  1100. pointer to the method to be called, either the C function, or a callable Python
  1101. object. This is not really a good solution either, since there's a lot of
  1102. lookups involved.
  1103. The way it works is that you have to supply a ``\class{socket}-like'' transport
  1104. object to the \class{SSL.Connection}. The only requirement of this object is
  1105. that it has a \method{fileno()} method that returns a file descriptor that's
  1106. valid at the C level (i.e. you can use the system calls read and write). If you
  1107. want to use the \method{connect()} or \method{accept()} methods of the
  1108. \class{SSL.Connection} object, the transport object has to supply such
  1109. methods too. Apart from them, any method lookups in the \class{SSL.Connection}
  1110. object that fail are passed on to the underlying transport object.
  1111. Future changes might be to allow Python-level transport objects, that instead
  1112. of having \method{fileno()} methods, have \method{read()} and \method{write()}
  1113. methods, so more advanced features of Python can be used. This would probably
  1114. entail some sort of OpenSSL ``BIOs'', but converting Python strings back and
  1115. forth is expensive, so this shouldn't be used unless necessary. Other nice
  1116. things would be to be able to pass in different transport objects for reading
  1117. and writing, but then the \method{fileno()} method of \class{SSL.Connection}
  1118. becomes virtually useless. Also, should the method resolution be used on the
  1119. read-transport or the write-transport?
  1120. \end{document}