.. hazmat:: Two-factor authentication ========================= .. currentmodule:: cryptography.hazmat.primitives.twofactor This module contains algorithms related to two-factor authentication. Currently, it contains an algorithm for generating and verifying one time password values based on Hash-based message authentication codes (HMAC). .. class:: InvalidToken This is raised when the verify method of a one time password function's computed token does not match the expected token. .. currentmodule:: cryptography.hazmat.primitives.twofactor.hotp .. class:: HOTP(key, length, algorithm, backend, enforce_key_length=True) .. versionadded:: 0.3 HOTP objects take a ``key``, ``length`` and ``algorithm`` parameter. The ``key`` should be :doc:`randomly generated bytes ` and is recommended to be 160 bits in length. The ``length`` parameter controls the length of the generated one time password and must be >= 6 and <= 8. This is an implementation of :rfc:`4226`. .. doctest:: >>> import os >>> from cryptography.hazmat.backends import default_backend >>> from cryptography.hazmat.primitives.twofactor.hotp import HOTP >>> from cryptography.hazmat.primitives.hashes import SHA1 >>> key = os.urandom(20) >>> hotp = HOTP(key, 6, SHA1(), backend=default_backend()) >>> hotp_value = hotp.generate(0) >>> hotp.verify(hotp_value, 0) :param bytes key: Per-user secret key. This value must be kept secret and be at least 128 bits. It is recommended that the key be 160 bits. :param int length: Length of generated one time password as ``int``. :param cryptography.hazmat.primitives.hashes.HashAlgorithm algorithm: A :class:`~cryptography.hazmat.primitives.hashes` instance. :param backend: A :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` instance. :param enforce_key_length: A boolean flag defaulting to True that toggles whether a minimum key length of 128 bits is enforced. This exists to work around the fact that as documented in `Issue #2915`_, the Google Authenticator PAM module by default generates 80 bit keys. If this flag is set to False, the application develop should implement additional checks of the key length before passing it into :class:`~cryptography.hazmat.primitives.twofactor.hotp.HOTP`. .. versionadded:: 1.5 :raises ValueError: This is raised if the provided ``key`` is shorter than 128 bits or if the ``length`` parameter is not 6, 7 or 8. :raises TypeError: This is raised if the provided ``algorithm`` is not :class:`~cryptography.hazmat.primitives.hashes.SHA1()`, :class:`~cryptography.hazmat.primitives.hashes.SHA256()` or :class:`~cryptography.hazmat.primitives.hashes.SHA512()` or if the ``length`` parameter is not an integer. :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the provided ``backend`` does not implement :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` .. method:: generate(counter) :param int counter: The counter value used to generate the one time password. :return bytes: A one time password value. .. method:: verify(hotp, counter) :param bytes hotp: The one time password value to validate. :param int counter: The counter value to validate against. :raises cryptography.hazmat.primitives.twofactor.InvalidToken: This is raised when the supplied HOTP does not match the expected HOTP. .. method:: get_provisioning_uri(account_name, counter, issuer) .. versionadded:: 1.0 :param account_name: The display name of account, such as ``'Alice Smith'`` or ``'alice@example.com'``. :type account_name: :term:`text` :param issuer: The optional display name of issuer. This is typically the provider or service the user wants to access using the OTP token. :type issuer: :term:`text` or `None` :param int counter: The current value of counter. :return: A URI string. Throttling ~~~~~~~~~~ Due to the fact that the HOTP algorithm generates rather short tokens that are 6 - 8 digits long, brute force attacks are possible. It is highly recommended that the server that validates the token implement a throttling scheme that locks out the account for a period of time after a number of failed attempts. The number of allowed attempts should be as low as possible while still ensuring that usability is not significantly impacted. Re-synchronization of the counter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The server's counter value should only be incremented on a successful HOTP authentication. However, the counter on the client is incremented every time a new HOTP value is requested. This can lead to the counter value being out of synchronization between the client and server. Due to this, it is highly recommended that the server sets a look-ahead window that allows the server to calculate the next ``x`` HOTP values and check them against the supplied HOTP value. This can be accomplished with something similar to the following code. .. code-block:: python def verify(hotp, counter, look_ahead): assert look_ahead >= 0 correct_counter = None otp = HOTP(key, 6, default_backend()) for count in range(counter, counter + look_ahead): try: otp.verify(hotp, count) correct_counter = count except InvalidToken: pass return correct_counter .. currentmodule:: cryptography.hazmat.primitives.twofactor.totp .. class:: TOTP(key, length, algorithm, time_step, backend, enforce_key_length=True) TOTP objects take a ``key``, ``length``, ``algorithm`` and ``time_step`` parameter. The ``key`` should be :doc:`randomly generated bytes ` and is recommended to be as long as your hash function's output (e.g 256-bit for SHA256). The ``length`` parameter controls the length of the generated one time password and must be >= 6 and <= 8. This is an implementation of :rfc:`6238`. .. doctest:: >>> import os >>> import time >>> from cryptography.hazmat.backends import default_backend >>> from cryptography.hazmat.primitives.twofactor.totp import TOTP >>> from cryptography.hazmat.primitives.hashes import SHA1 >>> key = os.urandom(20) >>> totp = TOTP(key, 8, SHA1(), 30, backend=default_backend()) >>> time_value = time.time() >>> totp_value = totp.generate(time_value) >>> totp.verify(totp_value, time_value) :param bytes key: Per-user secret key. This value must be kept secret and be at least 128 bits. It is recommended that the key be 160 bits. :param int length: Length of generated one time password as ``int``. :param cryptography.hazmat.primitives.hashes.HashAlgorithm algorithm: A :class:`~cryptography.hazmat.primitives.hashes` instance. :param int time_step: The time step size. The recommended size is 30. :param backend: A :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` instance. :param enforce_key_length: A boolean flag defaulting to True that toggles whether a minimum key length of 128 bits is enforced. This exists to work around the fact that as documented in `Issue #2915`_, the Google Authenticator PAM module by default generates 80 bit keys. If this flag is set to False, the application develop should implement additional checks of the key length before passing it into :class:`~cryptography.hazmat.primitives.twofactor.totp.TOTP`. .. versionadded:: 1.5 :raises ValueError: This is raised if the provided ``key`` is shorter than 128 bits or if the ``length`` parameter is not 6, 7 or 8. :raises TypeError: This is raised if the provided ``algorithm`` is not :class:`~cryptography.hazmat.primitives.hashes.SHA1()`, :class:`~cryptography.hazmat.primitives.hashes.SHA256()` or :class:`~cryptography.hazmat.primitives.hashes.SHA512()` or if the ``length`` parameter is not an integer. :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the provided ``backend`` does not implement :class:`~cryptography.hazmat.backends.interfaces.HMACBackend` .. method:: generate(time) :param int time: The time value used to generate the one time password. :return bytes: A one time password value. .. method:: verify(totp, time) :param bytes totp: The one time password value to validate. :param int time: The time value to validate against. :raises cryptography.hazmat.primitives.twofactor.InvalidToken: This is raised when the supplied TOTP does not match the expected TOTP. .. method:: get_provisioning_uri(account_name, issuer) .. versionadded:: 1.0 :param account_name: The display name of account, such as ``'Alice Smith'`` or ``'alice@example.com'``. :type: :term:`text` :param issuer: The optional display name of issuer. This is typically the provider or service the user wants to access using the OTP token. :type issuer: :term:`text` or `None` :return: A URI string. Provisioning URI ~~~~~~~~~~~~~~~~ The provisioning URI of HOTP and TOTP is not actual the part of RFC 4226 and RFC 6238, but a `spec of Google Authenticator`_. It is widely supported by web sites and mobile applications which are using Two-Factor authentication. For generating a provisioning URI, you could use the ``get_provisioning_uri`` method of HOTP/TOTP instances. .. code-block:: python counter = 5 account_name = 'alice@example.com' issuer_name = 'Example Inc' hotp_uri = hotp.get_provisioning_uri(account_name, counter, issuer_name) totp_uri = totp.get_provisioning_uri(account_name, issuer_name) A common usage is encoding the provisioning URI into QR code and guiding users to scan it with Two-Factor authentication applications in their mobile devices. .. _`spec of Google Authenticator`: https://github.com/google/google-authenticator/wiki/Key-Uri-Format .. _`Issue #2915`: https://github.com/pyca/cryptography/issues/2915 ' href='#n236'>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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
/*
 * This file is subject to the terms of the GFX License. If a copy of
 * the license was not distributed with this file, you can obtain one at:
 *
 *              http://ugfx.org/license.html
 */

/**
 * @file    src/gos/raw32.c
 * @brief   GOS Raw (bare metal) support.
 */
#include "gfx.h"

#if GFX_USE_OS_RAW32

#include <string.h>				// Prototype for memcpy()

#if GOS_RAW_HEAP_SIZE != 0
	static void _gosHeapInit(void);
#else
	#define _gosHeapInit()
#endif
static void _gosThreadsInit(void);

/*********************************************************
 * Initialise
 *********************************************************/

void _gosInit(void)
{
	// Set up the heap allocator
	_gosHeapInit();

	// Start the scheduler
	_gosThreadsInit();
}

void _gosDeinit(void)
{
	/* ToDo */
}

/*********************************************************
 * For WIn32 emulation - automatically add the tick functions
 * the user would normally have to provide for bare metal.
 *********************************************************/

#if defined(WIN32)
	#undef Red
	#undef Green
	#undef Blue
	#define WIN32_LEAN_AND_MEAN
	#include <stdio.h>
	#include <windows.h>
	systemticks_t gfxSystemTicks(void)						{ return GetTickCount(); }
	systemticks_t gfxMillisecondsToTicks(delaytime_t ms)	{ return ms; }
#endif

/*********************************************************
 * Exit everything functions
 *********************************************************/

void gfxHalt(const char *msg) {
	#if defined(WIN32)
		fprintf(stderr, "%s\n", msg);
		ExitProcess(1);
	#else
		volatile uint32_t	dummy;
		(void)				msg;

		while(1)
			dummy++;
	#endif
}

void gfxExit(void) {
	#if defined(WIN32)
		ExitProcess(0);
	#else
		volatile uint32_t	dummy;

		while(1)
			dummy++;
	#endif
}

/*********************************************************
 * Head allocation functions
 *********************************************************/

#if GOS_RAW_HEAP_SIZE == 0
	#include <stdlib.h>				// Prototype for malloc(), realloc() and free()

	void *gfxAlloc(size_t sz) {
		return malloc(sz);
	}

	void *gfxRealloc(void *ptr, size_t oldsz, size_t newsz) {
		(void) oldsz;
		return realloc(ptr, newsz);
	}

	void gfxFree(void *ptr) {
		free(ptr);
	}

#else

	// Slot structure - user memory follows
	typedef struct memslot {
		struct memslot *next;		// The next memslot
		size_t			sz;			// Includes the size of this memslot.
		} memslot;

	// Free Slot - immediately follows the memslot structure
	typedef struct freeslot {
		memslot *nextfree;			// The next free slot
	} freeslot;

	#define GetSlotSize(sz)		((((sz) + (sizeof(freeslot) - 1)) & ~(sizeof(freeslot) - 1)) + sizeof(memslot))
	#define NextFree(pslot)		((freeslot *)Slot2Ptr(pslot))->nextfree
	#define Ptr2Slot(p)			((memslot *)(p) - 1)
	#define Slot2Ptr(pslot)		((pslot)+1)

	static memslot *			firstSlot;
	static memslot *			lastSlot;
	static memslot *			freeSlots;
	static char					heap[GOS_RAW_HEAP_SIZE];

	static void _gosHeapInit(void) {
		lastSlot = 0;
		gfxAddHeapBlock(heap, GOS_RAW_HEAP_SIZE);
	}

	void gfxAddHeapBlock(void *ptr, size_t sz) {
		if (sz < sizeof(memslot)+sizeof(freeslot))
			return;

		if (lastSlot)
			lastSlot->next = (memslot *)ptr;
		else
			firstSlot = lastSlot = freeSlots = (memslot *)ptr;

		lastSlot->next = 0;
		lastSlot->sz = sz;
		NextFree(lastSlot) = 0;
	}

	void *gfxAlloc(size_t sz) {
		register memslot *prev, *p, *new;

		if (!sz) return 0;
		sz = GetSlotSize(sz);
		for (prev = 0, p = freeSlots; p != 0; prev = p, p = NextFree(p)) {
			// Loop till we have a block big enough
			if (p->sz < sz)
				continue;
			// Can we save some memory by splitting this block?
			if (p->sz >= sz + sizeof(memslot)+sizeof(freeslot)) {
				new = (memslot *)((char *)p + sz);
				new->next = p->next;
				p->next = new;
				new->sz = p->sz - sz;
				p->sz = sz;
				if (lastSlot == p)
					lastSlot = new;
				NextFree(new) = NextFree(p);
				NextFree(p) = new;
			}
			// Remove it from the free list
			if (prev)
				NextFree(prev) = NextFree(p);
			else
				freeSlots = NextFree(p);
			// Return the result found
			return Slot2Ptr(p);
		}
		// No slots large enough
		return 0;
	}

	void *gfxRealloc(void *ptr, size_t oldsz, size_t sz) {
		register memslot *prev, *p, *new;
		(void) oldsz;

		if (!ptr)
			return gfxAlloc(sz);
		if (!sz) {
			gfxFree(ptr);
			return 0;
		}

		p = Ptr2Slot(ptr);
		sz = GetSlotSize(sz);

		// If the next slot is free (and contiguous) merge it into this one
		if ((char *)p + p->sz == (char *)p->next) {
			for (prev = 0, new = freeSlots; new != 0; prev = new, new = NextFree(new)) {
				if (new == p->next) {
					p->next = new->next;
					p->sz += new->sz;
					if (prev)
						NextFree(prev) = NextFree(new);
					else
						freeSlots = NextFree(new);
					if (lastSlot == new)
						lastSlot = p;
					break;
				}
			}
		}

		// If this block is large enough we are nearly done
		if (sz < p->sz) {
			// Can we save some memory by splitting this block?
			if (p->sz >= sz + sizeof(memslot)+sizeof(freeslot)) {
				new = (memslot *)((char *)p + sz);
				new->next = p->next;
				p->next = new;
				new->sz = p->sz - sz;
				p->sz = sz;
				if (lastSlot == p)
					lastSlot = new;
				NextFree(new) = freeSlots;
				freeSlots = new;
			}
			return Slot2Ptr(p);
		}

		// We need to do this the hard way
		if ((new = gfxAlloc(sz)))
			return 0;
		memcpy(new, ptr, p->sz - sizeof(memslot));
		gfxFree(ptr);
		return new;
	}

	void gfxFree(void *ptr) {
		register memslot *prev, *p, *new;

		if (!ptr)
			return;

		p = Ptr2Slot(ptr);

		// If the next slot is free (and contiguous) merge it into this one
		if ((char *)p + p->sz == (char *)p->next) {
			for (prev = 0, new = freeSlots; new != 0; prev = new, new = NextFree(new)) {
				if (new == p->next) {
					p->next = new->next;
					p->sz += new->sz;
					if (prev)
						NextFree(prev) = NextFree(new);
					else
						freeSlots = NextFree(new);
					if (lastSlot == new)
						lastSlot = p;
					break;
				}
			}
		}

		// Add it into the free chain
		NextFree(p) = freeSlots;
		freeSlots = p;
	}
#endif

/*********************************************************
 * Semaphores and critical region functions
 *********************************************************/

#if !defined(INTERRUPTS_OFF) || !defined(INTERRUPTS_ON)
	#define INTERRUPTS_OFF()
	#define INTERRUPTS_ON()
#endif

void gfxSystemLock(void) {
	INTERRUPTS_OFF();
}

void gfxSystemUnlock(void) {
	INTERRUPTS_ON();
}

void gfxMutexInit(gfxMutex *pmutex) {
	pmutex[0] = 0;
}

void gfxMutexEnter(gfxMutex *pmutex) {
	INTERRUPTS_OFF();
	while (pmutex[0]) {
		INTERRUPTS_ON();
		gfxYield();
		INTERRUPTS_OFF();
	}
	pmutex[0] = 1;
	INTERRUPTS_ON();
}

void gfxMutexExit(gfxMutex *pmutex) {
	pmutex[0] = 0;
}

void gfxSemInit(gfxSem *psem, semcount_t val, semcount_t limit) {
	psem->cnt = val;
	psem->limit = limit;
}

bool_t gfxSemWait(gfxSem *psem, delaytime_t ms) {
	systemticks_t	starttm, delay;

	// Convert our delay to ticks
	switch (ms) {
	case TIME_IMMEDIATE:
		delay = TIME_IMMEDIATE;
		break;
	case TIME_INFINITE:
		delay = TIME_INFINITE;
		break;
	default:
		delay = gfxMillisecondsToTicks(ms);
		if (!delay) delay = 1;
		starttm = gfxSystemTicks();
	}

	INTERRUPTS_OFF();
	while (psem->cnt <= 0) {
		INTERRUPTS_ON();
		// Check if we have exceeded the defined delay
		switch (delay) {
		case TIME_IMMEDIATE:
			return FALSE;
		case TIME_INFINITE:
			break;
		default:
			if (gfxSystemTicks() - starttm >= delay)
				return FALSE;
			break;
		}
		gfxYield();
		INTERRUPTS_OFF();
	}
	psem->cnt--;