aboutsummaryrefslogtreecommitdiffstats
path: root/Demos/Host/GenericHIDHost/GenericHIDHost.c
blob: 605fc6f678867cc75dfce6f1ef6df1db18457661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
             LUFA Library
     Copyright (C) Dean Camera, 2009.
              
  dean [at] fourwalledcubicle [dot] com
      www.fourwalledcubicle.com
*/

/*
  Copyright 2009  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, and distribute this software
  and its documentation for any purpose and without fee is hereby
  granted, provided that the above copyright notice appear in all
  copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Main source file for the GenericHIDHost demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */
 
#include "GenericHIDHost.h"

/* Project Tags, for reading out using the ButtLoad project */
BUTTLOADTAG(ProjName,    "LUFA GenHid Host App");
BUTTLOADTAG(BuildTime,   __TIME__);
BUTTLOADTAG(BuildDate,   __DATE__);
BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);

/* Scheduler Task List */
TASK_LIST
{
	{ Task: USB_USBTask          , TaskStatus: TASK_STOP },
	{ Task: USB_HID_Host         , TaskStatus: TASK_STOP },
};


/** Main program entry point. This routine configures the hardware required by the application, then
 *  starts the scheduler to run the application tasks.
 */
int main(void)
{
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
	
	/* Hardware Initialization */
	SerialStream_Init(9600, false);
	LEDs_Init();
	
	/* Indicate USB not ready */
	UpdateStatus(Status_USBNotReady);
	
	/* Initialize Scheduler so that it can be used */
	Scheduler_Init();

	/* Initialize USB Subsystem */
	USB_Init();

	/* Start-up message */
	puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
	       "Generic HID Host Demo running.\r\n" ESC_INVERSE_OFF));
		   
	/* Scheduling - routine never returns, so put this last in the main function */
	Scheduler_Start();
}

/** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
EVENT_HANDLER(USB_DeviceAttached)
{
	puts_P(PSTR("Device Attached.\r\n"));
	UpdateStatus(Status_USBEnumerating);

	/* Start USB management task to enumerate the device */
	Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
}

/** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
 *  stops the library USB task management process.
 */
EVENT_HANDLER(USB_DeviceUnattached)
{
	/* Stop HID and USB management task */
	Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
	Scheduler_SetTaskMode(USB_HID_Host, TASK_STOP);

	puts_P(PSTR("Device Unattached.\r\n"));
	UpdateStatus(Status_USBNotReady);
}

/** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
 *  enumerated by the host and is now ready to be used by the application.
 */
EVENT_HANDLER(USB_DeviceEnumerationComplete)
{
	/* Start HID Host task */
	Scheduler_SetTaskMode(USB_HID_Host, TASK_RUN);

	/* Indicate device enumeration complete */
	UpdateStatus(Status_USBReady);
}

/** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
EVENT_HANDLER(USB_HostError)
{
	USB_ShutDown();

	puts_P(PSTR(ESC_BG_RED "Host Mode Error\r\n"));
	printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);

	UpdateStatus(Status_HardwareError);
	for(;;);
}

/** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
 *  enumerating an attached USB device.
 */
EVENT_HANDLER(USB_DeviceEnumerationFailed)
{
	puts_P(PSTR(ESC_BG_RED "Dev Enum Error\r\n"));
	printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode);
	printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode);
	printf_P(PSTR(" -- In State %d\r\n"), USB_HostState);

	UpdateStatus(Status_EnumerationError);
}

/** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
 *  log to a serial port, or anything else that is suitable for status updates.
 *
 *  \param CurrentStatus  Current status of the system, from the GenericHIDHost_StatusCodes_t enum
 */
void UpdateStatus(uint8_t CurrentStatus)
{
	uint8_t LEDMask = LEDS_NO_LEDS;
	
	/* Set the LED mask to the appropriate LED mask based on the given status code */
	switch (CurrentStatus)
	{
		case Status_USBNotReady:
			LEDMask = (LEDS_LED1);
			break;
		case Status_USBEnumerating:
			LEDMask = (LEDS_LED1 | LEDS_LED2);
			break;
		case Status_USBReady:
			LEDMask = (LEDS_LED2);
			break;
		case Status_EnumerationError:
		case Status_HardwareError:
			LEDMask = (LEDS_LED1 | LEDS_LED3);
			break;
	}
	
	/* Set the board LEDs to the new LED mask */
	LEDs_SetAllLEDs(LEDMask);
}

/** Reads in and processes the next report from the attached device, displaying the report
 *  contents on the board LEDs and via the serial port.
 */
void ReadNextReport(void)
{
	/* Select and unfreeze HID data IN pipe */
	Pipe_SelectPipe(HID_DATA_IN_PIPE);
	Pipe_Unfreeze();

	/* Ensure pipe contains data and is ready to be read before continuing */
	if (!(Pipe_ReadWriteAllowed()))
	{
		#if !defined(INTERRUPT_DATA_PIPE)
		/* Refreeze HID data IN pipe */
		Pipe_Freeze();
		#endif
		
		return;
	}
	
	uint8_t ReportINData[Pipe_BytesInPipe()];

	/* Read in HID report data */
	Pipe_Read_Stream_LE(&ReportINData, sizeof(ReportINData));				
		
	/* Clear the IN endpoint, ready for next data packet */
	Pipe_ClearCurrentBank();
	
	/* Print report data through the serial port */
	for (uint16_t CurrByte = 0; CurrByte < sizeof(ReportINData); CurrByte++)
	  printf_P(PSTR("0x%02X "), ReportINData[CurrByte]);
	
	puts_P(PSTR("\r\n"));
	
	#if !defined(INTERRUPT_DATA_PIPE)
	/* Refreeze HID data IN pipe */
	Pipe_Freeze();
	#endif
}

/** Writes a report to the attached device.
 *
 *  \param ReportOUTData  Buffer containing the report to send to the device
 *  \param ReportLength  Length of the report to send
 */
void WriteNextReport(uint8_t* ReportOUTData, uint16_t ReportLength)
{
	/* Select and unfreeze HID data OUT pipe */
	Pipe_SelectPipe(HID_DATA_OUT_PIPE);
	
	/* Not all HID devices have an OUT endpoint (some require OUT reports to be sent over the
	 * control endpoint instead) - check to see if the OUT endpoint has been initialized */
	if (Pipe_IsConfigured())
	{
		Pipe_Unfreeze();

		/* Ensure pipe is ready to be written to before continuing */
		if (!(Pipe_ReadWriteAllowed()))
		{
			/* Refreeze the data OUT pipe */
			Pipe_Freeze();
			
			return;
		}

		/* Read in HID report data */
		Pipe_Write_Stream_LE(ReportOUTData, ReportLength);				
			
		/* Clear the OUT endpoint, send last data packet */
		Pipe_ClearCurrentBank();

		/* Refreeze the data OUT pipe */
		Pipe_Freeze();
	}
	else
	{
		/* Class specific request to send a HID report to the device */
		USB_HostRequest = (USB_Host_Request_Header_t)
			{
				bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
				bRequest:      REQ_SetReport,
				wValue:        0,
				wIndex:        0,
				wLength:       ReportLength,
			};

		/* Send the request to the device */
		USB_Host_SendControlRequest(ReportOUTData);
	}
}

/** Task to set the configuration of the attached device after it has been enumerated, and to read and process
 *  HID reports from the device and to send reports if desired.
 */
TASK(USB_HID_Host)
{
	uint8_t ErrorCode;

	/* Switch to determine what user-application handled host state the host state machine is in */
	switch (USB_HostState)
	{
		case HOST_STATE_Addressed:
			/* Standard request to set the device configuration to configuration 1 */
			USB_HostRequest = (USB_Host_Request_Header_t)
				{
					bmRequestType: (REQDIR_HOSTTODEVICE | REQTYPE_STANDARD | REQREC_DEVICE),
					bRequest:      REQ_SetConfiguration,
					wValue:        1,
					wIndex:        0,
					wLength:       0,
				};

			/* Send the request, display error and wait for device detach if request fails */
			if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
			{
				puts_P(PSTR("Control Error (Set Configuration).\r\n"));
				printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);

				/* Indicate error status */
				UpdateStatus(Status_EnumerationError);
				
				/* Wait until USB device disconnected */
				while (USB_IsConnected);
				break;
			}
			
			USB_HostState = HOST_STATE_Configured;
			break;
		case HOST_STATE_Configured:
			puts_P(PSTR("Getting Config Data.\r\n"));
		
			/* Get and process the configuration descriptor data */
			if ((ErrorCode = ProcessConfigurationDescriptor()) != SuccessfulConfigRead)
			{
				if (ErrorCode == ControlError)
				  puts_P(PSTR("Control Error (Get Configuration).\r\n"));
				else
				  puts_P(PSTR("Invalid Device.\r\n"));

				printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode);
				
				/* Indicate error status */
				UpdateStatus(Status_EnumerationError);

				/* Wait until USB device disconnected */
				while (USB_IsConnected);
				break;
			}
		
			#if defined(INTERRUPT_DATA_PIPE)					
			/* Select and unfreeze HID data IN pipe */
			Pipe_SelectPipe(HID_DATA_IN_PIPE);
			Pipe_Unfreeze();
			#endif

			puts_P(PSTR("HID Device Enumerated.\r\n"));
					
			USB_HostState = HOST_STATE_Ready;
			break;
		#if !defined(INTERRUPT_DATA_PIPE)
		case HOST_STATE_Ready:
			ReadNextReport();

			break;
		#endif
	}
}

#if defined(INTERRUPT_DATA_PIPE)
/** Interrupt handler for the Endpoint/Pipe interrupt vector. This interrupt fires each time an enabled
 *  pipe interrupt occurs on a pipe which has had that interrupt enabled.
 */
ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
{
	/* Save previously selected pipe before selecting a new pipe */
	uint8_t PrevSelectedPipe = Pipe_GetCurrentPipe();

	/* Check to see if the HID data IN pipe has caused the interrupt */
	if (Pipe_HasPipeInterrupted(HID_DATA_IN_PIPE))
	{
		/* Clear the pipe interrupt, and select the data IN pipe */
		Pipe_ClearPipeInterrupt(HID_DATA_IN_PIPE);
		Pipe_SelectPipe(HID_DATA_IN_PIPE);	

		/* Check to see if the pipe IN interrupt has fired */
		if (USB_INT_HasOccurred(PIPE_INT_IN) && USB_INT_IsEnabled(PIPE_INT_IN))
		{
			/* Clear interrupt flag */
			USB_INT_Clear(PIPE_INT_IN);		

			/* Read and process the next report from the device */
			ReadNextReport();
		}
	}

	/* Restore previously selected pipe */
	Pipe_SelectPipe(PrevSelectedPipe);
}
#endif
critical. * ``bc_path_length_zero.pem`` - An RSA 2048 bit self-signed certificate containing a basic constraints extension with a path length of zero. * ``unsupported_extension.pem`` - An RSA 2048 bit self-signed certificate containing an unsupported extension type. The OID was encoded as "1.2.3.4" with an ``extnValue`` of "value". * ``unsupported_extension_2.pem`` - A ``secp256r1`` certificate containing two unsupported extensions. The OIDs are ``1.3.6.1.4.1.41482.2`` with an ``extnValue`` of ``1.3.6.1.4.1.41482.1.2`` and ``1.3.6.1.4.1.45724.2.1.1`` with an ``extnValue`` of ``\x03\x02\x040`` * ``unsupported_extension_critical.pem`` - An RSA 2048 bit self-signed certificate containing an unsupported extension type marked critical. The OID was encoded as "1.2.3.4" with an ``extnValue`` of "value". * ``san_email_dns_ip_dirname_uri.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with the following general names: ``rfc822Name``, ``dNSName``, ``iPAddress``, ``directoryName``, and ``uniformResourceIdentifier``. * ``san_empty_hostname.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative extension with an empty ``dNSName`` general name. * ``san_other_name.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with the ``otherName`` general name. * ``san_registered_id.pem`` - An RSA 1024 bit certificate containing a subject alternative name extension with the ``registeredID`` general name. * ``all_key_usages.pem`` - An RSA 2048 bit self-signed certificate containing a key usage extension with all nine purposes set to true. * ``extended_key_usage.pem`` - An RSA 2048 bit self-signed certificate containing an extended key usage extension with eight usages. * ``san_idna_names.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with ``rfc822Name``, ``dNSName``, and ``uniformResourceIdentifier`` general names with IDNA (:rfc:`5895`) encoding. * ``san_wildcard_idna.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with a ``dNSName`` general name with a wildcard IDNA (:rfc:`5895`) domain. * ``san_idna2003_dnsname.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with an IDNA 2003 (:rfc:`3490`) ``dNSName``. * ``san_rfc822_names.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with various ``rfc822Name`` values. * ``san_rfc822_idna.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with an IDNA ``rfc822Name``. * ``san_uri_with_port.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with various ``uniformResourceIdentifier`` values. * ``san_ipaddr.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with an ``iPAddress`` value. * ``san_dirname.pem`` - An RSA 2048 bit self-signed certificate containing a subject alternative name extension with a ``directoryName`` value. * ``inhibit_any_policy_5.pem`` - An RSA 2048 bit self-signed certificate containing an inhibit any policy extension with the value 5. * ``inhibit_any_policy_negative.pem`` - An RSA 2048 bit self-signed certificate containing an inhibit any policy extension with the value -1. * ``authority_key_identifier.pem`` - An RSA 2048 bit self-signed certificate containing an authority key identifier extension with key identifier, authority certificate issuer, and authority certificate serial number fields. * ``authority_key_identifier_no_keyid.pem`` - An RSA 2048 bit self-signed certificate containing an authority key identifier extension with authority certificate issuer and authority certificate serial number fields. * ``aia_ocsp_ca_issuers.pem`` - An RSA 2048 bit self-signed certificate containing an authority information access extension with two OCSP and one CA issuers entry. * ``aia_ocsp.pem`` - An RSA 2048 bit self-signed certificate containing an authority information access extension with an OCSP entry. * ``aia_ca_issuers.pem`` - An RSA 2048 bit self-signed certificate containing an authority information access extension with a CA issuers entry. * ``cdp_empty_hostname.pem`` - An RSA 2048 bit self-signed certificate containing a CRL distribution point extension with ``fullName`` URI without a hostname. * ``cdp_fullname_reasons_crl_issuer.pem`` - An RSA 1024 bit certificate containing a CRL distribution points extension with ``fullName``, ``cRLIssuer``, and ``reasons`` data. * ``cdp_crl_issuer.pem`` - An RSA 1024 bit certificate containing a CRL distribution points extension with ``cRLIssuer`` data. * ``cdp_all_reasons.pem`` - An RSA 1024 bit certificate containing a CRL distribution points extension with all ``reasons`` bits set. * ``cdp_reason_aa_compromise.pem`` - An RSA 1024 bit certificate containing a CRL distribution points extension with the ``AACompromise`` ``reasons`` bit set. * ``nc_permitted_excluded.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with both permitted and excluded elements. Contains ``IPv4`` and ``IPv6`` addresses with network mask as well as ``dNSName`` with a leading period. * ``nc_permitted_excluded_2.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with both permitted and excluded elements. Unlike ``nc_permitted_excluded.pem``, the general names do not contain any name constraints specific values. * ``nc_permitted.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with permitted elements. * ``nc_permitted_2.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with permitted elements that do not contain any name constraints specific values. * ``nc_excluded.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with excluded elements. * ``nc_invalid_ip_netmask.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with a permitted element that has an ``IPv6`` IP and an invalid network mask. * ``nc_single_ip_netmask.pem`` - An RSA 2048 bit self-signed certificate containing a name constraints extension with a permitted element that has two IPs with ``/32`` and ``/128`` network masks. * ``cp_user_notice_with_notice_reference.pem`` - An RSA 2048 bit self-signed certificate containing a certificate policies extension with a notice reference in the user notice. * ``cp_user_notice_with_explicit_text.pem`` - An RSA 2048 bit self-signed certificate containing a certificate policies extension with explicit text and no notice reference. * ``cp_cps_uri.pem`` - An RSA 2048 bit self-signed certificate containing a certificate policies extension with a CPS URI and no user notice. * ``cp_user_notice_no_explicit_text.pem`` - An RSA 2048 bit self-signed certificate containing a certificate policies extension with a user notice with no explicit text. * ``cp_invalid.pem`` - An RSA 2048 bit self-signed certificate containing a certificate policies extension with invalid data. * ``ian_uri.pem`` - An RSA 2048 bit certificate containing an issuer alternative name extension with a ``URI`` general name. * ``ocsp_nocheck.pem`` - An RSA 2048 bit self-signed certificate containing an ``OCSPNoCheck`` extension. * ``pc_inhibit_require.pem`` - An RSA 2048 bit self-signed certificate containing a policy constraints extension with both inhibit policy mapping and require explicit policy elements. * ``pc_inhibit.pem`` - An RSA 2048 bit self-signed certificate containing a policy constraints extension with an inhibit policy mapping element. * ``pc_require.pem`` - An RSA 2048 bit self-signed certificate containing a policy constraints extension with a require explicit policy element. * ``unsupported_subject_public_key_info.pem`` - A certificate whose public key is an unknown OID (``1.3.6.1.4.1.8432.1.1.2``). * ``policy_constraints_explicit.pem`` - A self-signed certificate containing a ``policyConstraints`` extension with a ``requireExplicitPolicy`` value. * ``freshestcrl.pem`` - A self-signed certificate containing a ``freshestCRL`` extension. * ``ca/ca.pem`` - A self-signed certificate with ``basicConstraints`` set to true. Its private key is ``ca/ca_key.pem``. This certificate is encoded in several of the PKCS12 custom vectors. * ``negative_serial.pem`` - A certificate with a serial number that is a negative number. * ``rsa_pss.pem`` - A certificate with an RSA PSS signature. Custom X.509 Request Vectors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * ``dsa_sha1.pem`` and ``dsa_sha1.der`` - Contain a certificate request using 1024-bit DSA parameters and SHA1 generated using OpenSSL. * ``rsa_md4.pem`` and ``rsa_md4.der`` - Contain a certificate request using 2048 bit RSA and MD4 generated using OpenSSL. * ``rsa_sha1.pem`` and ``rsa_sha1.der`` - Contain a certificate request using 2048 bit RSA and SHA1 generated using OpenSSL. * ``rsa_sha256.pem`` and ``rsa_sha256.der`` - Contain a certificate request using 2048 bit RSA and SHA256 generated using OpenSSL. * ``ec_sha256.pem`` and ``ec_sha256.der`` - Contain a certificate request using EC (``secp384r1``) and SHA256 generated using OpenSSL. * ``san_rsa_sha1.pem`` and ``san_rsa_sha1.der`` - Contain a certificate request using RSA and SHA1 with a subject alternative name extension generated using OpenSSL. * ``two_basic_constraints.pem`` - A certificate signing request for an RSA 2048 bit key containing two basic constraints extensions. * ``unsupported_extension.pem`` - A certificate signing request for an RSA 2048 bit key containing containing an unsupported extension type. The OID was encoded as "1.2.3.4" with an ``extnValue`` of "value". * ``unsupported_extension_critical.pem`` - A certificate signing request for an RSA 2048 bit key containing containing an unsupported extension type marked critical. The OID was encoded as "1.2.3.4" with an ``extnValue`` of "value". * ``basic_constraints.pem`` - A certificate signing request for an RSA 2048 bit key containing a basic constraints extension marked as critical. * ``invalid_signature.pem`` - A certificate signing request for an RSA 1024 bit key containing an invalid signature with correct padding. * ``challenge.pem`` - A certificate signing request for an RSA 2048 bit key containing a challenge password. Custom X.509 Certificate Revocation List Vectors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * ``crl_all_reasons.pem`` - Contains a CRL with 12 revoked certificates, whose serials match their list position. It includes one revocation without any entry extensions, 10 revocations with every supported reason code and one revocation with an unsupported, non-critical entry extension with the OID value set to "1.2.3.4". * ``crl_dup_entry_ext.pem`` - Contains a CRL with one revocation which has a duplicate entry extension. * ``crl_md2_unknown_crit_entry_ext.pem`` - Contains a CRL with one revocation which contains an unsupported critical entry extension with the OID value set to "1.2.3.4". The CRL uses an unsupported MD2 signature algorithm. * ``crl_unsupported_reason.pem`` - Contains a CRL with one revocation which has an unsupported reason code. * ``crl_inval_cert_issuer_entry_ext.pem`` - Contains a CRL with one revocation which has one entry extension for certificate issuer with an empty value. * ``crl_empty.pem`` - Contains a CRL with no revoked certificates. * ``crl_ian_aia_aki.pem`` - Contains a CRL with ``IssuerAlternativeName``, ``AuthorityInformationAccess``, ``AuthorityKeyIdentifier`` and ``CRLNumber`` extensions. * ``valid_signature.pem`` - Contains a CRL with the public key which was used to generate it. * ``invalid_signature.pem`` - Contains a CRL with the last signature byte incremented by 1 to produce an invalid signature, and the public key which was used to generate it. * ``crl_delta_crl_indicator.pem`` - Contains a CRL with the ``DeltaCRLIndicator`` extension. * ``crl_idp_fullname_only.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension with only a ``fullname`` for the distribution point. * ``crl_idp_only_ca.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that is only valid for CA certificate revocation. * ``crl_idp_fullname_only_aa.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that sets a ``fullname`` and is only valid for attribute certificate revocation. * ``crl_idp_fullname_only_user.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that sets a ``fullname`` and is only valid for user certificate revocation. * ``crl_idp_fullname_indirect_crl.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that sets a ``fullname`` and the indirect CRL flag. * ``crl_idp_reasons_only.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that is only valid for revocations with the ``keyCompromise`` reason. * ``crl_idp_relative_user_all_reasons.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension that sets all revocation reasons as allowed. * ``crl_idp_relativename_only.pem`` - Contains a CRL with an ``IssuingDistributionPoints`` extension with only a ``relativename`` for the distribution point. X.509 OCSP Test Vectors ~~~~~~~~~~~~~~~~~~~~~~~ * ``x509/ocsp/resp-sha256.der`` - An OCSP response for ``cryptography.io`` with a SHA256 signature. * ``x509/ocsp/resp-unauthorized.der`` - An OCSP response with an unauthorized status. * ``x509/ocsp/resp-revoked.der`` - An OCSP response for ``revoked.badssl.com`` with a revoked status. * ``x509/ocsp/resp-delegate-unknown-cert.der`` - An OCSP response for an unknown cert from ``AC Camerafirma``. This response also contains a delegate certificate. * ``x509/ocsp/resp-responder-key-hash.der`` - An OCSP response from the ``DigiCert`` OCSP responder that uses a key hash for the responder ID. * ``x509/ocsp/resp-revoked-reason.der`` - An OCSP response from the ``QuoVadis`` OCSP responder that contains a revoked certificate with a revocation reason. * ``x509/ocsp/resp-revoked-no-next-update.der`` - An OCSP response that contains a revoked certificate and no ``nextUpdate`` value. * ``x509/ocsp/resp-invalid-signature-oid.der`` - An OCSP response that was modified to contain an MD2 signature algorithm object identifier. Custom X.509 OCSP Test Vectors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * ``x509/ocsp/req-sha1.der`` - An OCSP request containing a single request and using SHA1 as the hash algorithm. * ``x509/ocsp/req-multi-sha1.der`` - An OCSP request containing multiple requests. * ``x509/ocsp/req-invalid-hash-alg.der`` - An OCSP request containing an invalid hash algorithm OID. * ``x509/ocsp/req-ext-nonce.der`` - An OCSP request containing a nonce extension. Custom PKCS12 Test Vectors ~~~~~~~~~~~~~~~~~~~~~~~~~~ * ``pkcs12/cert-key-aes256cbc.p12`` - A PKCS12 file containing a cert (``x509/custom/ca/ca.pem``) and key (``x509/custom/ca/ca_key.pem``) both encrypted with AES 256 CBC with the password ``cryptography``. * ``pkcs12/cert-none-key-none.p12`` - A PKCS12 file containing a cert (``x509/custom/ca/ca.pem``) and key (``x509/custom/ca/ca_key.pem``) with no encryption. The password (used for integrity checking only) is ``cryptography``. * ``pkcs12/cert-rc2-key-3des.p12`` - A PKCS12 file containing a cert (``x509/custom/ca/ca.pem``) encrypted with RC2 and key (``x509/custom/ca/ca_key.pem``) encrypted via 3DES with the password ``cryptography``. * ``pkcs12/no-password.p12`` - A PKCS12 file containing a cert (``x509/custom/ca/ca.pem``) and key (``x509/custom/ca/ca_key.pem``) with no encryption and no password. * ``pkcs12/no-cert-key-aes256cbc.p12`` - A PKCS12 file containing a key (``x509/custom/ca/ca_key.pem``) encrypted via AES 256 CBC with the password ``cryptography`` and no certificate. * ``pkcs12/cert-aes256cbc-no-key.p12`` - A PKCS12 file containing a cert (``x509/custom/ca/ca.pem``) encrypted via AES 256 CBC with the password ``cryptography`` and no private key. Hashes ~~~~~~ * MD5 from :rfc:`1321`. * RIPEMD160 from the `RIPEMD website`_. * SHA1 from `NIST CAVP`_. * SHA2 (224, 256, 384, 512, 512/224, 512/256) from `NIST CAVP`_. * SHA3 (224, 256, 384, 512) from `NIST CAVP`_. * SHAKE (128, 256) from `NIST CAVP`_. * Blake2s and Blake2b from OpenSSL `test/evptests.txt`_. HMAC ~~~~ * HMAC-MD5 from :rfc:`2202`. * HMAC-SHA1 from :rfc:`2202`. * HMAC-RIPEMD160 from :rfc:`2286`. * HMAC-SHA2 (224, 256, 384, 512) from :rfc:`4231`. Key derivation functions ~~~~~~~~~~~~~~~~~~~~~~~~ * HKDF (SHA1, SHA256) from :rfc:`5869`. * PBKDF2 (HMAC-SHA1) from :rfc:`6070`. * scrypt from the `draft RFC`_. * X9.63 KDF from `NIST CAVP`_. * SP 800-108 Counter Mode KDF (HMAC-SHA1, HMAC-SHA224, HMAC-SHA256, HMAC-SHA384, HMAC-SHA512) from `NIST CAVP`_. Key wrapping ~~~~~~~~~~~~ * AES key wrap (AESKW) and 3DES key wrap test vectors from `NIST CAVP`_. * AES key wrap with padding vectors from `Botan's key wrap vectors`_. Recipes ~~~~~~~ * Fernet from its `specification repository`_. Symmetric ciphers ~~~~~~~~~~~~~~~~~ * AES (CBC, CFB, ECB, GCM, OFB, CCM) from `NIST CAVP`_. * AES CTR from :rfc:`3686`. * 3DES (CBC, CFB, ECB, OFB) from `NIST CAVP`_. * ARC4 (KEY-LENGTH: 40, 56, 64, 80, 128, 192, 256) from :rfc:`6229`. * ARC4 (KEY-LENGTH: 160) generated by this project. See: :doc:`/development/custom-vectors/arc4` * Blowfish (CBC, CFB, ECB, OFB) from `Bruce Schneier's vectors`_. * Camellia (ECB) from NTT's `Camellia page`_ as linked by `CRYPTREC`_. * Camellia (CBC, CFB, OFB) from `OpenSSL's test vectors`_. * CAST5 (ECB) from :rfc:`2144`. * CAST5 (CBC, CFB, OFB) generated by this project. See: :doc:`/development/custom-vectors/cast5` * ChaCha20 from :rfc:`7539`. * ChaCha20Poly1305 from :rfc:`7539`, `OpenSSL's evpciph.txt`_, and the `BoringSSL ChaCha20Poly1305 tests`_. * IDEA (ECB) from the `NESSIE IDEA vectors`_ created by `NESSIE`_. * IDEA (CBC, CFB, OFB) generated by this project. See: :doc:`/development/custom-vectors/idea` * SEED (ECB) from :rfc:`4269`. * SEED (CBC) from :rfc:`4196`. * SEED (CFB, OFB) generated by this project. See: :doc:`/development/custom-vectors/seed` Two factor authentication ~~~~~~~~~~~~~~~~~~~~~~~~~ * HOTP from :rfc:`4226` * TOTP from :rfc:`6238` (Note that an `errata`_ for the test vectors in RFC 6238 exists) CMAC ~~~~ * AES-128, AES-192, AES-256, 3DES from `NIST SP-800-38B`_ Poly1305 ~~~~~~~~ * Test vectors from :rfc:`7539`. Creating test vectors --------------------- When official vectors are unavailable ``cryptography`` may choose to build its own using existing vectors as source material. Created Vectors ~~~~~~~~~~~~~~~ .. toctree:: :maxdepth: 1 custom-vectors/arc4 custom-vectors/cast5 custom-vectors/idea custom-vectors/seed custom-vectors/hkdf If official test vectors appear in the future the custom generated vectors should be discarded. Any vectors generated by this method must also be prefixed with the following header format (substituting the correct information): .. code-block:: python # CAST5 CBC vectors built for https://github.com/pyca/cryptography # Derived from the AESVS MMT test data for CBC # Verified against the CommonCrypto and Go crypto packages # Key Length : 128 .. _`NIST`: https://www.nist.gov/ .. _`IETF`: https://www.ietf.org/ .. _`Project Wycheproof`: https://github.com/google/wycheproof .. _`NIST CAVP`: https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program .. _`Bruce Schneier's vectors`: https://www.schneier.com/code/vectors.txt .. _`Camellia page`: https://info.isl.ntt.co.jp/crypt/eng/camellia/ .. _`CRYPTREC`: https://www.cryptrec.go.jp .. _`OpenSSL's test vectors`: https://github.com/openssl/openssl/blob/97cf1f6c2854a3a955fd7dd3a1f113deba00c9ef/crypto/evp/evptests.txt#L232 .. _`OpenSSL's evpciph.txt`: https://github.com/openssl/openssl/blob/5a7bc0be97dee9ac715897fe8180a08e211bc6ea/test/evpciph.txt#L2362 .. _`BoringSSL ChaCha20Poly1305 tests`: https://boringssl.googlesource.com/boringssl/+/2e2a226ac9201ac411a84b5e79ac3a7333d8e1c9/crypto/cipher_extra/test/chacha20_poly1305_tests.txt .. _`BoringSSL evp tests`: https://boringssl.googlesource.com/boringssl/+/ce3773f9fe25c3b54390bc51d72572f251c7d7e6/crypto/evp/evp_tests.txt .. _`RIPEMD website`: https://homes.esat.kuleuven.be/~bosselae/ripemd160.html .. _`draft RFC`: https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01 .. _`Specification repository`: https://github.com/fernet/spec .. _`errata`: https://www.rfc-editor.org/errata_search.php?rfc=6238 .. _`OpenSSL example key`: https://github.com/openssl/openssl/blob/d02b48c63a58ea4367a0e905979f140b7d090f86/test/testrsa.pem .. _`GnuTLS key parsing tests`: https://gitlab.com/gnutls/gnutls/commit/f16ef39ef0303b02d7fa590a37820440c466ce8d .. _`enc-rsa-pkcs8.pem`: https://gitlab.com/gnutls/gnutls/blob/f8d943b38bf74eaaa11d396112daf43cb8aa82ae/tests/pkcs8-decode/encpkcs8.pem .. _`enc2-rsa-pkcs8.pem`: https://gitlab.com/gnutls/gnutls/blob/f8d943b38bf74eaaa11d396112daf43cb8aa82ae/tests/pkcs8-decode/enc2pkcs8.pem .. _`unenc-rsa-pkcs8.pem`: https://gitlab.com/gnutls/gnutls/blob/f8d943b38bf74eaaa11d396112daf43cb8aa82ae/tests/pkcs8-decode/unencpkcs8.pem .. _`pkcs12_s2k_pem.c`: https://gitlab.com/gnutls/gnutls/blob/f8d943b38bf74eaaa11d396112daf43cb8aa82ae/tests/pkcs12_s2k_pem.c .. _`Botan's ECC private keys`: https://github.com/randombit/botan/tree/4917f26a2b154e841cd27c1bcecdd41d2bdeb6ce/src/tests/data/ecc .. _`GnuTLS example keys`: https://gitlab.com/gnutls/gnutls/commit/ad2061deafdd7db78fd405f9d143b0a7c579da7b .. _`NESSIE IDEA vectors`: https://www.cosic.esat.kuleuven.be/nessie/testvectors/bc/idea/Idea-128-64.verified.test-vectors .. _`NESSIE`: https://en.wikipedia.org/wiki/NESSIE .. _`Ed25519 website`: https://ed25519.cr.yp.to/software.html .. _`NIST SP-800-38B`: https://csrc.nist.gov/publications/detail/sp/800-38b/archive/2005-05-01 .. _`NIST PKI Testing`: https://csrc.nist.gov/Projects/PKI-Testing .. _`testx509.pem`: https://github.com/openssl/openssl/blob/master/test/testx509.pem .. _`DigiCert Global Root G3`: http://cacerts.digicert.com/DigiCertGlobalRootG3.crt .. _`root data`: https://hg.mozilla.org/projects/nss/file/25b2922cc564/security/nss/lib/ckfw/builtins/certdata.txt#l2053 .. _`asymmetric/public/PKCS1/dsa.pub.pem`: https://github.com/ruby/ruby/blob/4ccb387f3bc436a08fc6d72c4931994f5de95110/test/openssl/test_pkey_dsa.rb#L53 .. _`Mozilla bug`: https://bugzilla.mozilla.org/show_bug.cgi?id=233586 .. _`Russian CA`: https://e-trust.gosuslugi.ru/MainCA .. _`test/evptests.txt`: https://github.com/openssl/openssl/blob/2d0b44126763f989a4cbffbffe9d0c7518158bb7/test/evptests.txt .. _`unknown signature OID`: https://bugzilla.mozilla.org/show_bug.cgi?id=405966 .. _`botan`: https://github.com/randombit/botan/blob/57789bdfc55061002b2727d0b32587612829a37c/src/tests/data/pubkey/dh.vec .. _`DHKE`: https://sandilands.info/sgordon/diffie-hellman-secret-key-exchange-with-openssl .. _`Botan's key wrap vectors`: https://github.com/randombit/botan/blob/737f33c09a18500e044dca3e2ae13bd2c08bafdd/src/tests/data/keywrap/nist_key_wrap.vec .. _`root-ed25519.pem`: https://github.com/openssl/openssl/blob/2a1e2fe145c6eb8e75aa2e1b3a8c3a49384b2852/test/certs/root-ed25519.pem .. _`server-ed25519-cert.pem`: https://github.com/openssl/openssl/blob/2a1e2fe145c6eb8e75aa2e1b3a8c3a49384b2852/test/certs/server-ed25519-cert.pem