liaison rfid
This commit is contained in:
BIN
composants/byPanda/__pycache__/alarme.cpython-311.pyc
Normal file
BIN
composants/byPanda/__pycache__/alarme.cpython-311.pyc
Normal file
Binary file not shown.
6
flask/.env
Normal file
6
flask/.env
Normal file
@@ -0,0 +1,6 @@
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=python
|
||||
DB_PASSWORD=wolaouais
|
||||
DB_NAME=Utilisateurs
|
||||
DB_CHARSET=utf8mb4
|
||||
@@ -0,0 +1,260 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: RPi.GPIO
|
||||
Version: 0.7.1
|
||||
Summary: A module to control Raspberry Pi GPIO channels
|
||||
Home-page: http://sourceforge.net/projects/raspberry-gpio-python/
|
||||
Author: Ben Croston
|
||||
Author-email: ben@croston.org
|
||||
License: MIT
|
||||
Keywords: Raspberry Pi GPIO
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Topic :: Software Development
|
||||
Classifier: Topic :: Home Automation
|
||||
Classifier: Topic :: System :: Hardware
|
||||
License-File: LICENCE.txt
|
||||
|
||||
This package provides a Python module to control the GPIO on a Raspberry Pi.
|
||||
|
||||
Note that this module is unsuitable for real-time or timing critical applications. This is because you
|
||||
can not predict when Python will be busy garbage collecting. It also runs under the Linux kernel which
|
||||
is not suitable for real time applications - it is multitasking O/S and another process may be given
|
||||
priority over the CPU, causing jitter in your program. If you are after true real-time performance and
|
||||
predictability, buy yourself an Arduino http://www.arduino.cc !
|
||||
|
||||
Note that the current release does not support SPI, I2C, hardware PWM or serial functionality on the RPi yet.
|
||||
This is planned for the near future - watch this space! One-wire functionality is also planned.
|
||||
|
||||
Although hardware PWM is not available yet, software PWM is available to use on all channels.
|
||||
|
||||
For examples and documentation, visit http://sourceforge.net/p/raspberry-gpio-python/wiki/Home/
|
||||
|
||||
Change Log
|
||||
==========
|
||||
|
||||
0.7.1
|
||||
-------
|
||||
- Better RPi board + peri_addr detection (issue 190 / 191)
|
||||
- Fix PyEval_InitThreads deprecation warning for Python 3.9 (issue 188)
|
||||
- Fix build using GCC 10 (issue 187)
|
||||
- Fix docstrings to not include licence
|
||||
- Remove Debian/Raspbian stretch packaging support
|
||||
- Use setuptools instead of distutils
|
||||
- Added detection of Zero 2 W
|
||||
- Tested and working with Python 2.7, 3.7, 3.8, 3.9, 3.10
|
||||
|
||||
0.7.0
|
||||
-----
|
||||
- Updated RPI_INFO to include RPi 4B
|
||||
- Fixed pull up/down for Pi4 (issue 168)
|
||||
- Fix spelling mistake in docstrings
|
||||
- Tested and working on Raspbian Buster + Python 3.8.0b2
|
||||
- Fix board detection for aarch64 (Issues 161 / 165)
|
||||
- Fix checking mmap return value in c_gpio.c (issue 166)
|
||||
|
||||
0.6.5
|
||||
-----
|
||||
- Fix exception on re-export of /sys/class/gpio/gpioNN
|
||||
|
||||
0.6.4
|
||||
-----
|
||||
- Event cleanup bug (issue 145)
|
||||
- Raise exception for duplicate PWM objects (issue 54 - Thijs Schreijer <thijs@thijsschreijer.nl>)
|
||||
- Fix build warnings (Issue 146 - Dominik George)
|
||||
- test.py runs unchanged for both python 2+3
|
||||
- Soft PWM stops running fix (Issues 94, 111, 154)
|
||||
- Soft PWM segfault fix (Luke Allen pull request)
|
||||
|
||||
0.6.3
|
||||
-----
|
||||
- Fix code so it builds under PyPy (Gasper Zejn)
|
||||
- os.system breaks event detection - Matt Kimball (issue 127)
|
||||
|
||||
0.6.2
|
||||
-----
|
||||
- Rewrote Debian packaging mechanism
|
||||
- RPI_INFO reports Pi 3
|
||||
- Changed module layout - moved C components to RPi._GPIO
|
||||
|
||||
0.6.1
|
||||
-----
|
||||
- Update RPI_INFO to detect more board types
|
||||
- Issue 118 - add_event_detect sometimes gives runtime error with unpriv user
|
||||
- Issue 120 - setmode() remembers invalid mode
|
||||
|
||||
0.6.0a3
|
||||
-------
|
||||
- Now uses /dev/gpiomem if available to avoid being run as root
|
||||
- Fix warnings with pull up/down on pins 3/5
|
||||
- Correct base address on Pi 2 when devicetree is disabled
|
||||
- caddr_t error on compile (Issue 109)
|
||||
- Error on invalid parameters to setup() (issue 93)
|
||||
- Add timeout parameter to wait_for_edge() (issue 91)
|
||||
|
||||
0.5.11
|
||||
------
|
||||
- Fix - pins > 26 missing when using BOARD mode
|
||||
- Add getmode()
|
||||
- Raise exception when a mix of modes is used
|
||||
- GPIO.cleanaup() unsets the current pin mode
|
||||
|
||||
0.5.10
|
||||
------
|
||||
- Issue 95 - support RPi 2 boards
|
||||
- Introduce RPI_INFO
|
||||
- Deprecate RPI_REVISION
|
||||
- Issue 97 - fixed docstring for setup()
|
||||
|
||||
0.5.9
|
||||
-----
|
||||
- Issue 87 - warn about pull up/down on i2c pins
|
||||
- Issue 86/75 - wait_for_edge() bugfix
|
||||
- Issue 84 - recognise RPi properly when using a custom kernel
|
||||
- Issue 90 - cleanup() on a list/tuple of channels
|
||||
|
||||
0.5.8
|
||||
-----
|
||||
- Allow lists/tuples of channels in GPIO.setup()
|
||||
- GPIO.output() now allows lists/tuples of values
|
||||
- GPIO.wait_for_edge() bug fixes (issue 78)
|
||||
|
||||
0.5.7
|
||||
-----
|
||||
- Issue 67 - speed up repeated calls to GPIO.wait_for_event()
|
||||
- Added bouncetime keyword to GPIO.wait_for_event()
|
||||
- Added extra edge/interrupt unit tests
|
||||
- GPIO.wait_for_event() can now be mixed with GPIO.add_event_detect()
|
||||
- Improved cleanups of events
|
||||
- Issue 69 resolved
|
||||
|
||||
0.5.6
|
||||
-----
|
||||
- Issue 68 - support for RPi Model B+
|
||||
- Fix gpio_function()
|
||||
|
||||
0.5.5
|
||||
-----
|
||||
- Issue 52 - 'unallocate' a channel
|
||||
- Issue 35 - use switchbounce with GPIO.event_detected()
|
||||
- Refactored events code
|
||||
- Rewrote tests to use unittest mechanism and new test board with loopbacks
|
||||
- Fixed adding events after a GPIO.cleanup()
|
||||
- Issue 64 - misleading /dev/mem permissions error
|
||||
- Issue 59 - name collision with PWM constant and class
|
||||
|
||||
0.5.4
|
||||
-----
|
||||
- Changed release status (from alpha to full release)
|
||||
- Warn when GPIO.cleanup() used with nothing to clean up (issue 44)
|
||||
- Avoid collisions in constants (e.g. HIGH / RISING / PUD_DOWN)
|
||||
- Accept BOARD numbers in gpio_function (issue 34)
|
||||
- More return values for gpio_function (INPUT, OUTPUT, SPI, I2C, PWM, SERIAL, UNKNOWN)
|
||||
- Tidy up docstrings
|
||||
- Fix /dev/mem access error with gpio_function
|
||||
|
||||
0.5.3a
|
||||
------
|
||||
- Allow pydoc for non-root users (issue 27)
|
||||
- Fix add_event_detect error when run as daemon (issue 32)
|
||||
- Simplified exception types
|
||||
- Changed from distribute to pip
|
||||
|
||||
0.5.2a
|
||||
------
|
||||
- Added software PWM (experimental)
|
||||
- Added switch bounce handling to event callbacks
|
||||
- Added channel number parameter to event callbacks (issue 31)
|
||||
- Internal refactoring and code tidy up
|
||||
|
||||
0.5.1a
|
||||
------
|
||||
- Fixed callbacks for multiple GPIOs (issue 28)
|
||||
|
||||
0.5.0a
|
||||
------
|
||||
- Added new edge detection events (interrupt handling)
|
||||
- Added add_event_detect()
|
||||
- Added remove_event_detect()
|
||||
- Added add_event_callback()
|
||||
- Added wait_for_edge()
|
||||
- Removed old experimental event functions
|
||||
- Removed set_rising_event()
|
||||
- Removed set_falling_event()
|
||||
- Removed set_high_event()
|
||||
- Removed set_low_event()
|
||||
- Changed event_detected() for new edge detection functionality
|
||||
- input() now returns 0/LOW == False or 1/HIGH == True (integers) instead of False or True (booleans).
|
||||
- Fix error on repeated import (issue 3)
|
||||
- Change SetupException to a RuntimeError so it can be caught on import (issue 25, Chris Hager <chris@linuxuser.at>)
|
||||
- Improved docstrings of functions
|
||||
|
||||
0.4.2a
|
||||
------
|
||||
- Fix for installing on Arch Linux (Python 3.3) (issue 20)
|
||||
- Initial value when setting a channel as an output (issue 19)
|
||||
|
||||
0.4.1a
|
||||
------
|
||||
- Added VERSION
|
||||
- Permit input() of channels set as outputs (Eric Ptak <trouch@trouch.com>)
|
||||
|
||||
0.4.0a
|
||||
------
|
||||
- Added support for Revision 2 boards
|
||||
- Added RPI_REVISION
|
||||
- Added cleanup() function and removed automatic reset functionality on program exit
|
||||
- Added get_function() to read existing GPIO channel functionality (suggestion from Eric Ptak <trouch@trouch.com>)
|
||||
- Added set_rising_event()
|
||||
- Added set_falling_event()
|
||||
- Added set_high_event()
|
||||
- Added set_low_event()
|
||||
- Added event_detected()
|
||||
- Added test/test.py
|
||||
- Converted debian to armhf
|
||||
- Fixed C function short_wait() (thanks to Thibault Porteboeuf <thibaultporteboeuf@gmail.com>)
|
||||
|
||||
0.3.1a
|
||||
------
|
||||
- Fixed critical bug with swapped high/low state on outputs
|
||||
- Added pull-up / pull-down setup functionality for inputs
|
||||
|
||||
0.3.0a
|
||||
------
|
||||
- Rewritten as a C extension
|
||||
- Now uses /dev/mem and SoC registers instead of /sys/class/gpio
|
||||
- Faster!
|
||||
- Make call to GPIO.setmode() mandatory
|
||||
- Added GPIO.HIGH and GPIO.LOW constants
|
||||
|
||||
0.2.0
|
||||
-----
|
||||
- Changed status from alpha to beta
|
||||
- Added setmode() to be able to use BCM GPIO 00.nn channel numbers
|
||||
- Renamed InvalidPinException to InvalidChannelException
|
||||
|
||||
0.1.0
|
||||
------
|
||||
- Fixed direction bug
|
||||
- Added MANIFEST.in (to include missing file)
|
||||
- Changed GPIO channel number to pin number
|
||||
- Tested and working!
|
||||
|
||||
0.0.3a
|
||||
------
|
||||
- Added GPIO table
|
||||
- Refactored
|
||||
- Fixed a few critical bugs
|
||||
- Still completely untested!
|
||||
|
||||
0.0.2a
|
||||
------
|
||||
- Internal refactoring. Still completely untested!
|
||||
|
||||
0.0.1a
|
||||
------
|
||||
- First version. Completely untested until I can get hold of a Raspberry Pi!
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
CHANGELOG.txt
|
||||
INSTALL.txt
|
||||
LICENCE.txt
|
||||
MANIFEST.in
|
||||
README.txt
|
||||
create_gpio_user_permissions.py
|
||||
setup.cfg
|
||||
setup.py
|
||||
RPi/__init__.py
|
||||
RPi.GPIO.egg-info/PKG-INFO
|
||||
RPi.GPIO.egg-info/SOURCES.txt
|
||||
RPi.GPIO.egg-info/dependency_links.txt
|
||||
RPi.GPIO.egg-info/top_level.txt
|
||||
RPi/GPIO/__init__.py
|
||||
source/c_gpio.c
|
||||
source/c_gpio.h
|
||||
source/common.c
|
||||
source/common.h
|
||||
source/constants.c
|
||||
source/constants.h
|
||||
source/cpuinfo.c
|
||||
source/cpuinfo.h
|
||||
source/event_gpio.c
|
||||
source/event_gpio.h
|
||||
source/py_gpio.c
|
||||
source/py_pwm.c
|
||||
source/py_pwm.h
|
||||
source/soft_pwm.c
|
||||
source/soft_pwm.h
|
||||
test/issue_94_111_154.py
|
||||
test/test.py
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
../RPi/GPIO/__init__.py
|
||||
../RPi/GPIO/__pycache__/__init__.cpython-311.pyc
|
||||
../RPi/_GPIO.cpython-311-x86_64-linux-gnu.so
|
||||
../RPi/__init__.py
|
||||
../RPi/__pycache__/__init__.cpython-311.pyc
|
||||
PKG-INFO
|
||||
SOURCES.txt
|
||||
dependency_links.txt
|
||||
top_level.txt
|
||||
@@ -0,0 +1 @@
|
||||
RPi
|
||||
25
venv/lib/python3.11/site-packages/RPi/GPIO/__init__.py
Normal file
25
venv/lib/python3.11/site-packages/RPi/GPIO/__init__.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Copyright (c) 2012-2021 Ben Croston
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
# this software and associated documentation files (the "Software"), to deal in
|
||||
# the Software without restriction, including without limitation the rights to
|
||||
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
# of the Software, and to permit persons to whom the Software is furnished to do
|
||||
# so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in all
|
||||
# copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
"""This package provides a Python module to control the GPIO on a Raspberry Pi"""
|
||||
|
||||
from RPi._GPIO import *
|
||||
|
||||
VERSION = '0.7.1'
|
||||
Binary file not shown.
BIN
venv/lib/python3.11/site-packages/RPi/_GPIO.cpython-311-x86_64-linux-gnu.so
Executable file
BIN
venv/lib/python3.11/site-packages/RPi/_GPIO.cpython-311-x86_64-linux-gnu.so
Executable file
Binary file not shown.
0
venv/lib/python3.11/site-packages/RPi/__init__.py
Normal file
0
venv/lib/python3.11/site-packages/RPi/__init__.py
Normal file
Binary file not shown.
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,490 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: flask-talisman
|
||||
Version: 1.1.0
|
||||
Summary: HTTP security headers for Flask.
|
||||
Home-page: https://github.com/wntrblm/flask-talisman
|
||||
Author: Alethea Katherine Flowers
|
||||
Author-email: me@thea.codes
|
||||
License: Apache Software License
|
||||
Keywords: flask security https xss
|
||||
Platform: UNKNOWN
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: License :: OSI Approved :: Apache Software License
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: Operating System :: MacOS
|
||||
Classifier: Operating System :: Unix
|
||||
License-File: LICENSE
|
||||
|
||||
Talisman: HTTP security headers for Flask
|
||||
=========================================
|
||||
|
||||
|PyPI Version|
|
||||
|
||||
Talisman is a small Flask extension that handles setting HTTP headers
|
||||
that can help protect against a few common web application security
|
||||
issues.
|
||||
|
||||
The default configuration:
|
||||
|
||||
- Forces all connects to ``https``, unless running with debug enabled.
|
||||
- Enables `HTTP Strict Transport
|
||||
Security <https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security>`_.
|
||||
- Sets Flask's session cookie to ``secure``, so it will never be set if
|
||||
your application is somehow accessed via a non-secure connection.
|
||||
- Sets Flask's session cookie to ``httponly``, preventing JavaScript
|
||||
from being able to access its content. CSRF via Ajax uses a separate
|
||||
cookie and should be unaffected.
|
||||
- Sets Flask's session cookie to ``Lax``, preventing the cookie to be leaked
|
||||
in CSRF-prone request methods.
|
||||
- Sets
|
||||
`X-Frame-Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options>`_
|
||||
to ``SAMEORIGIN`` to avoid
|
||||
`clickjacking <https://en.wikipedia.org/wiki/Clickjacking>`_.
|
||||
- Sets `X-Content-Type-Options
|
||||
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>`_
|
||||
to prevent content type sniffing.
|
||||
- Sets a strict `Content Security
|
||||
Policy <https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy>`__
|
||||
of ``default-src: 'self', 'object-src': 'none'``. This is intended to almost completely
|
||||
prevent Cross Site Scripting (XSS) attacks. This is probably the only
|
||||
setting that you should reasonably change. See the
|
||||
`Content Security Policy`_ section.
|
||||
- Sets a strict `Referrer-Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>`_
|
||||
of ``strict-origin-when-cross-origin`` that governs which referrer information should be included with
|
||||
requests made.
|
||||
- Disables ``browsing-topics`` by default in the `Permissions-Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy>`_
|
||||
like `Drupal <https://www.drupal.org/project/drupal/issues/3209628>`_ to enhance privacy protection.
|
||||
|
||||
|
||||
In addition to Talisman, you **should always use a cross-site request
|
||||
forgery (CSRF) library**. It's highly recommended to use
|
||||
`Flask-SeaSurf <https://flask-seasurf.readthedocs.org/en/latest/>`_,
|
||||
which is based on Django's excellent library.
|
||||
|
||||
Installation & Basic Usage
|
||||
--------------------------
|
||||
|
||||
Install via `pip <https://pypi.python.org/pypi/pip>`_:
|
||||
|
||||
::
|
||||
|
||||
pip install flask-talisman
|
||||
|
||||
After installing, wrap your Flask app with a ``Talisman``:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from flask import Flask
|
||||
from flask_talisman import Talisman
|
||||
|
||||
app = Flask(__name__)
|
||||
Talisman(app)
|
||||
|
||||
|
||||
There is also a full `Example App <https://github.com/wntrblm/flask-talisman/blob/master/example_app>`_.
|
||||
|
||||
Options
|
||||
-------
|
||||
|
||||
- ``force_https``, default ``True``, forces all non-debug connects to
|
||||
``https`` (`about HTTPS <https://developer.mozilla.org/en-US/docs/Glossary/https>`_).
|
||||
- ``force_https_permanent``, default ``False``, uses ``301`` instead of
|
||||
``302`` for ``https`` redirects.
|
||||
|
||||
- ``frame_options``, default ``SAMEORIGIN``, can be ``SAMEORIGIN``,
|
||||
``DENY``, or ``ALLOWFROM`` (`about Frame Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options>`_).
|
||||
- ``frame_options_allow_from``, default ``None``, a string indicating
|
||||
the domains that are allowed to embed the site via iframe.
|
||||
|
||||
- ``strict_transport_security``, default ``True``, whether to send HSTS
|
||||
headers (`about HSTS <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security>`_).
|
||||
- ``strict_transport_security_preload``, default ``False``, enables HSTS
|
||||
preloading. If you register your application with
|
||||
`Google's HSTS preload list <https://hstspreload.appspot.com/>`_,
|
||||
Firefox and Chrome will never load your site over a non-secure
|
||||
connection.
|
||||
- ``strict_transport_security_max_age``, default ``ONE_YEAR_IN_SECS``,
|
||||
length of time the browser will respect the HSTS header.
|
||||
- ``strict_transport_security_include_subdomains``, default ``True``,
|
||||
whether subdomains should also use HSTS.
|
||||
|
||||
- ``content_security_policy``, default ``default-src: 'self'`, 'object-src': 'none'``, see the
|
||||
`Content Security Policy`_ section (`about Content Security Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy>`_).
|
||||
- ``content_security_policy_nonce_in``, default ``[]``. Adds a per-request nonce
|
||||
value to the flask request object and also to the specified CSP header section.
|
||||
I.e. ``['script-src', 'style-src']``
|
||||
- ``content_security_policy_report_only``, default ``False``, whether to set
|
||||
the CSP header as "report-only" (as `Content-Security-Policy-Report-Only`)
|
||||
to ease deployment by disabling the policy enforcement by the browser,
|
||||
requires passing a value with the ``content_security_policy_report_uri``
|
||||
parameter
|
||||
- ``content_security_policy_report_uri``, default ``None``, a string
|
||||
indicating the report URI used for `CSP violation reports
|
||||
<https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_CSP_violation_reports>`_
|
||||
|
||||
- ``referrer_policy``, default ``strict-origin-when-cross-origin``, a string
|
||||
that sets the Referrer Policy header to send a full URL when performing a same-origin
|
||||
request, only send the origin of the document to an equally secure destination
|
||||
(HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP) (`about Referrer Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>`_).
|
||||
|
||||
- ``feature_policy``, default ``{}``, see the `Feature Policy`_ section (`about Feature Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy>`_).
|
||||
|
||||
- ``permissions_policy``, default ``{'browsing-topics': '()'}``, see the `Permissions Policy`_ section (`about Permissions Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy>`_).
|
||||
- ``document_policy``, default ``{}``, see the `Document Policy`_ section (`about Document Policy <https://wicg.github.io/document-policy/>`_).
|
||||
|
||||
- ``session_cookie_secure``, default ``True``, set the session cookie
|
||||
to ``secure``, preventing it from being sent over plain ``http`` (`about cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)_`).
|
||||
- ``session_cookie_http_only``, default ``True``, set the session
|
||||
cookie to ``httponly``, preventing it from being read by JavaScript.
|
||||
- ``session_cookie_samesite``, default ``Lax``, set this to ``Strict`` to prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link.
|
||||
|
||||
|
||||
- ``force_file_save``, default ``False``, whether to set the
|
||||
`X-Download-Options <https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/jj542450(v=vs.85)?redirectedfrom=MSDN>`_
|
||||
header to ``noopen`` to prevent IE >= 8 to from opening file downloads
|
||||
directly and only save them instead.
|
||||
|
||||
- ``x_content_type_options``, default ``True``, Protects against MIME sniffing vulnerabilities (`about Content Type Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>`_).
|
||||
- ``x_xss_protection``, default ``False``, Protects against cross-site scripting (XSS) attacks (`about XSS Protection <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection>`_). This option is disabled by default because no modern browser (`supports this header <https://caniuse.com/mdn-http_headers_x-xss-protection>`_) anymore.
|
||||
|
||||
For a full list of (security) headers, check out: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers.
|
||||
|
||||
Per-view options
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Sometimes you want to change the policy for a specific view. The
|
||||
``force_https``, ``frame_options``, ``frame_options_allow_from``,
|
||||
`content_security_policy``, ``feature_policy``, ``permissions_policy``
|
||||
and ``document_policy`` options can be changed on a per-view basis.
|
||||
|
||||
.. code:: python
|
||||
|
||||
from flask import Flask
|
||||
from flask_talisman import Talisman, ALLOW_FROM
|
||||
|
||||
app = Flask(__name__)
|
||||
talisman = Talisman(app)
|
||||
|
||||
@app.route('/normal')
|
||||
def normal():
|
||||
return 'Normal'
|
||||
|
||||
@app.route('/embeddable')
|
||||
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
|
||||
def embeddable():
|
||||
return 'Embeddable'
|
||||
|
||||
Content Security Policy
|
||||
-----------------------
|
||||
|
||||
The default content security policy is extremely strict and will
|
||||
prevent loading any resources that are not in the same domain as the
|
||||
application. Most web applications will need to change this policy.
|
||||
If you're not ready to deploy Content Security Policy, you can set
|
||||
`content_security_policy` to `False` to disable sending this header
|
||||
entirely.
|
||||
|
||||
A slightly more permissive policy is available at
|
||||
``flask_talisman.GOOGLE_CSP_POLICY``, which allows loading Google-hosted JS
|
||||
libraries, fonts, and embeding media from YouTube and Maps.
|
||||
|
||||
You can and should create your own policy to suit your site's needs.
|
||||
Here's a few examples adapted from
|
||||
`MDN <https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy>`_:
|
||||
|
||||
Example 1
|
||||
~~~~~~~~~
|
||||
|
||||
This is the default policy. A web site administrator wants all content
|
||||
to come from the site's own origin (this excludes subdomains) and disallow
|
||||
legacy HTML elements.
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': '\'self\'',
|
||||
'object-src': '\'none\'',
|
||||
}
|
||||
talisman = Talisman(app, content_security_policy=csp)
|
||||
|
||||
Example 2
|
||||
~~~~~~~~~
|
||||
|
||||
A web site administrator wants to allow content from a trusted domain
|
||||
and all its subdomains (it doesn't have to be the same domain that the
|
||||
CSP is set on.)
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': [
|
||||
'\'self\'',
|
||||
'*.trusted.com'
|
||||
]
|
||||
}
|
||||
|
||||
Example 3
|
||||
~~~~~~~~~
|
||||
|
||||
A web site administrator wants to allow users of a web application to
|
||||
include images from any origin in their own content, but to restrict
|
||||
audio or video media to trusted providers, and all scripts only to a
|
||||
specific server that hosts trusted code.
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': '\'self\'',
|
||||
'img-src': '*',
|
||||
'media-src': [
|
||||
'media1.com',
|
||||
'media2.com',
|
||||
],
|
||||
'script-src': 'userscripts.example.com'
|
||||
}
|
||||
|
||||
In this example content is only permitted from the document's origin
|
||||
with the following exceptions:
|
||||
|
||||
- Images may loaded from anywhere (note the ``*`` wildcard).
|
||||
- Media is only allowed from media1.com and media2.com (and not from
|
||||
subdomains of those sites).
|
||||
- Executable script is only allowed from userscripts.example.com.
|
||||
|
||||
Example 4
|
||||
~~~~~~~~~
|
||||
|
||||
A web site administrator for an online banking site wants to ensure that
|
||||
all its content is loaded using SSL, in order to prevent attackers from
|
||||
eavesdropping on requests.
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': 'https://onlinebanking.jumbobank.com'
|
||||
}
|
||||
|
||||
The server only permits access to documents being loaded specifically
|
||||
over HTTPS through the single origin onlinebanking.jumbobank.com.
|
||||
|
||||
Example 5
|
||||
~~~~~~~~~
|
||||
|
||||
A web site administrator of a web mail site wants to allow HTML in
|
||||
email, as well as images loaded from anywhere, but not JavaScript or
|
||||
other potentially dangerous content.
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': [
|
||||
'\'self\'',
|
||||
'*.mailsite.com',
|
||||
],
|
||||
'img-src': '*'
|
||||
}
|
||||
|
||||
Note that this example doesn't specify a ``script-src``; with the
|
||||
example CSP, this site uses the setting specified by the ``default-src``
|
||||
directive, which means that scripts can be loaded only from the
|
||||
originating server.
|
||||
|
||||
Example 6
|
||||
~~~~~~~~~
|
||||
|
||||
A web site administrator wants to allow embedded scripts (which might
|
||||
be generated dynamicially).
|
||||
|
||||
.. code:: python
|
||||
|
||||
csp = {
|
||||
'default-src': '\'self\'',
|
||||
'script-src': '\'self\'',
|
||||
}
|
||||
talisman = Talisman(
|
||||
app,
|
||||
content_security_policy=csp,
|
||||
content_security_policy_nonce_in=['script-src']
|
||||
)
|
||||
|
||||
The nonce needs to be added to the script tag in the template:
|
||||
|
||||
.. code:: html
|
||||
|
||||
<script nonce="{{ csp_nonce() }}">
|
||||
//...
|
||||
</script>
|
||||
|
||||
Note that the CSP directive (`script-src` in the example) to which the `nonce-...`
|
||||
source should be added needs to be defined explicitly.
|
||||
|
||||
Example 7
|
||||
~~~~~~~~~
|
||||
|
||||
A web site adminstrator wants to override the CSP directives via an
|
||||
environment variable which doesn't support specifying the policy as
|
||||
a Python dictionary, e.g.:
|
||||
|
||||
.. code:: bash
|
||||
|
||||
export CSP_DIRECTIVES="default-src 'self'; image-src *"
|
||||
python app.py
|
||||
|
||||
Then in the app code you can read the CSP directives from the environment:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import os
|
||||
from flask_talisman import Talisman, DEFAULT_CSP_POLICY
|
||||
|
||||
talisman = Talisman(
|
||||
app,
|
||||
content_security_policy=os.environ.get("CSP_DIRECTIVES", DEFAULT_CSP_POLICY),
|
||||
)
|
||||
|
||||
As you can see above the policy can be defined simply just like the official
|
||||
specification requires the HTTP header to be set: As a semicolon separated
|
||||
list of individual CSP directives.
|
||||
|
||||
Feature Policy
|
||||
--------------
|
||||
|
||||
**Note:** Feature Policy has largely been `renamed Permissions Policy <https://github.com/w3c/webappsec-feature-policy/issues/359>`_
|
||||
in the latest draft and some features are likely to move to Document Policy.
|
||||
At this writing, most browsers support the ``Feature-Policy`` HTTP Header name.
|
||||
See the `Permissions Policy`_ and `Document Policy`_ sections below should you wish
|
||||
to set these.
|
||||
|
||||
Also note that the Feature Policy specification did not progress beyond the `draft https://wicg.github.io/feature-policy/`
|
||||
stage before being renamed, but is `supported in some form in most browsers
|
||||
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy#Browser_compatibility>`_.
|
||||
|
||||
The default feature policy is empty, as this is the default expected behaviour.
|
||||
|
||||
Geolocation Example
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Disable access to Geolocation interface.
|
||||
|
||||
.. code:: python
|
||||
|
||||
feature_policy = {
|
||||
'geolocation': '\'none\''
|
||||
}
|
||||
talisman = Talisman(app, feature_policy=feature_policy)
|
||||
|
||||
Permissions Policy
|
||||
------------------
|
||||
|
||||
Feature Policy has been split into Permissions Policy and Document Policy but
|
||||
at this writing `browser support of Permissions Policy is very limited <https://caniuse.com/permissions-policy>`_,
|
||||
and it is recommended to still set the ``Feature-Policy`` HTTP Header.
|
||||
Permission Policy support is included in Talisman for when this becomes more
|
||||
widely supported.
|
||||
|
||||
Note that the `Permission Policy is still an Working Draft <https://www.w3.org/TR/permissions-policy/>`_.
|
||||
|
||||
When the same feature or permission is set in both Feature Policy and Permission Policy,
|
||||
the Permission Policy setting will take precedence in browsers that support both.
|
||||
|
||||
It should be noted that the syntax differs between Feature Policy and Permission Policy
|
||||
as can be seen from the ``geolocation`` examples provided.
|
||||
|
||||
The default Permissions Policy is ``browsing-topics=()``, which opts sites out of
|
||||
`Federated Learning of Cohorts <https://wicg.github.io/floc/>`_ an interest-based advertising initiative
|
||||
called Topics API.
|
||||
|
||||
Permission Policy can be set either using a dictionary, or using a string.
|
||||
|
||||
Geolocation and Microphone Example
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Disable access to Geolocation interface and Microphone using dictionary syntax
|
||||
|
||||
.. code:: python
|
||||
|
||||
permissions_policy = {
|
||||
'geolocation': '()',
|
||||
'microphone': '()'
|
||||
}
|
||||
talisman = Talisman(app, permissions_policy=permissions_policy)
|
||||
|
||||
Disable access to Geolocation interface and Microphone using string syntax
|
||||
|
||||
.. code:: python
|
||||
|
||||
permissions_policy = 'geolocation=(), microphone=()'
|
||||
talisman = Talisman(app, permissions_policy=permissions_policy)
|
||||
|
||||
Document Policy
|
||||
---------------
|
||||
|
||||
Feature Policy has been split into Permissions Policy and Document Policy but
|
||||
at this writing `browser support of Document Policy is very limited <https://caniuse.com/document-policy>`_,
|
||||
and it is recommended to still set the ``Feature-Policy`` HTTP Header.
|
||||
Document Policy support is included in Talisman for when this becomes more
|
||||
widely supported.
|
||||
|
||||
Note that the `Document Policy is still an Unofficial Draft <https://wicg.github.io/document-policy/>`_.
|
||||
|
||||
The default Document Policy is empty, as this is the default expected behaviour.
|
||||
|
||||
Document Policy can be set either using a dictionary, or using a string.
|
||||
|
||||
Oversized-Images Example
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Forbid oversized-images using dictionary syntax:
|
||||
|
||||
.. code:: python
|
||||
|
||||
document_policy = {
|
||||
'oversized-images': '?0'
|
||||
}
|
||||
talisman = Talisman(app, document_policy=document_policy)
|
||||
|
||||
Forbid oversized-images using string syntax:
|
||||
|
||||
.. code:: python
|
||||
|
||||
document_policy = 'oversized-images=?0'
|
||||
talisman = Talisman(app, document_policy=document_policy)
|
||||
|
||||
Disclaimer
|
||||
----------
|
||||
|
||||
This code originated at Google, but is not an official Google product,
|
||||
experimental or otherwise. It was forked on June 6th, 2021 from the
|
||||
unmaintained GoogleCloudPlatform/flask-talisman.
|
||||
|
||||
There is no silver bullet for web application security. Talisman can
|
||||
help, but security is more than just setting a few headers. Any
|
||||
public-facing web application should have a comprehensive approach to
|
||||
security.
|
||||
|
||||
|
||||
Contributing changes
|
||||
--------------------
|
||||
|
||||
- See `CONTRIBUTING.md`_
|
||||
|
||||
Licensing
|
||||
---------
|
||||
|
||||
- Apache 2.0 - See `LICENSE`_
|
||||
|
||||
.. _LICENSE: https://github.com/wntrblm/flask-talisman/blob/master/LICENSE
|
||||
.. _CONTRIBUTING.md: https://github.com/wntrblm/flask-talisman/blob/master/CONTRIBUTING.md
|
||||
.. |PyPI Version| image:: https://img.shields.io/pypi/v/flask-talisman.svg
|
||||
:target: https://pypi.python.org/pypi/flask-talisman
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
flask_talisman-1.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
flask_talisman-1.1.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
||||
flask_talisman-1.1.0.dist-info/METADATA,sha256=AwnGEfgydNEYCwtRCtDWiQB6hSaTi1QBQrdWhw997_0,18722
|
||||
flask_talisman-1.1.0.dist-info/RECORD,,
|
||||
flask_talisman-1.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
flask_talisman-1.1.0.dist-info/WHEEL,sha256=z9j0xAa_JmUKMpmz72K0ZGALSM_n-wQVmGbleXx2VHg,110
|
||||
flask_talisman-1.1.0.dist-info/top_level.txt,sha256=mXVUQo_kTE7G1KmO-Pl2mbgm8braqn1FfwVzSh2rh68,15
|
||||
flask_talisman/__init__.py,sha256=cTbxfRkVoP9JwIwHJFEymT3-ZuOr4uspReRunGwSNns,1027
|
||||
flask_talisman/__pycache__/__init__.cpython-311.pyc,,
|
||||
flask_talisman/__pycache__/talisman.cpython-311.pyc,,
|
||||
flask_talisman/__pycache__/talisman_test.cpython-311.pyc,,
|
||||
flask_talisman/talisman.py,sha256=Y2q-X4ug-91wpS54wArEP0LWpA0bErDNW86ZL-hPhEY,17033
|
||||
flask_talisman/talisman_test.py,sha256=Ht7OTCm2VXWJJlxXNxGmMARGn3dYQg51E4lrpT772dY,14153
|
||||
@@ -0,0 +1,6 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.37.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py2-none-any
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
flask_talisman
|
||||
31
venv/lib/python3.11/site-packages/flask_talisman/__init__.py
Normal file
31
venv/lib/python3.11/site-packages/flask_talisman/__init__.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# Copyright 2015 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from .talisman import (
|
||||
ALLOW_FROM, DEFAULT_CSP_POLICY, DEFAULT_DOCUMENT_POLICY,
|
||||
DEFAULT_FEATURE_POLICY, DEFAULT_PERMISSIONS_POLICY, DENY,
|
||||
GOOGLE_CSP_POLICY, NONCE_LENGTH, SAMEORIGIN, Talisman)
|
||||
|
||||
__all__ = (
|
||||
'ALLOW_FROM',
|
||||
'DEFAULT_CSP_POLICY',
|
||||
'DEFAULT_DOCUMENT_POLICY',
|
||||
'DEFAULT_FEATURE_POLICY',
|
||||
'DEFAULT_PERMISSIONS_POLICY',
|
||||
'DENY',
|
||||
'GOOGLE_CSP_POLICY',
|
||||
'NONCE_LENGTH',
|
||||
'SAMEORIGIN',
|
||||
'Talisman',
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
465
venv/lib/python3.11/site-packages/flask_talisman/talisman.py
Normal file
465
venv/lib/python3.11/site-packages/flask_talisman/talisman.py
Normal file
@@ -0,0 +1,465 @@
|
||||
# Copyright 2015 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from collections import OrderedDict
|
||||
|
||||
import flask
|
||||
|
||||
|
||||
DENY = 'DENY'
|
||||
SAMEORIGIN = 'SAMEORIGIN'
|
||||
ALLOW_FROM = 'ALLOW-FROM'
|
||||
ONE_YEAR_IN_SECS = 31556926
|
||||
|
||||
DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'
|
||||
|
||||
DEFAULT_CSP_POLICY = {
|
||||
'default-src': '\'self\'',
|
||||
'object-src': '\'none\'',
|
||||
}
|
||||
|
||||
DEFAULT_SESSION_COOKIE_SAMESITE = "Lax"
|
||||
|
||||
GOOGLE_CSP_POLICY = {
|
||||
# Fonts from fonts.google.com
|
||||
'font-src': '\'self\' themes.googleusercontent.com *.gstatic.com',
|
||||
# <iframe> based embedding for Maps and Youtube.
|
||||
'frame-src': '\'self\' www.google.com www.youtube.com',
|
||||
# Assorted Google-hosted Libraries/APIs.
|
||||
'script-src': '\'self\' ajax.googleapis.com *.googleanalytics.com '
|
||||
'*.google-analytics.com',
|
||||
# Used by generated code from http://www.google.com/fonts
|
||||
'style-src': '\'self\' ajax.googleapis.com fonts.googleapis.com '
|
||||
'*.gstatic.com',
|
||||
'object-src': '\'none\'',
|
||||
'default-src': '\'self\' *.gstatic.com',
|
||||
}
|
||||
|
||||
DEFAULT_PERMISSIONS_POLICY = {
|
||||
# Disable Topics API
|
||||
'browsing-topics': '()'
|
||||
}
|
||||
|
||||
DEFAULT_DOCUMENT_POLICY = {
|
||||
}
|
||||
|
||||
DEFAULT_FEATURE_POLICY = {
|
||||
}
|
||||
|
||||
NONCE_LENGTH = 32
|
||||
|
||||
|
||||
class Talisman(object):
|
||||
"""
|
||||
Talisman is a Flask extension for HTTP security headers.
|
||||
"""
|
||||
|
||||
def __init__(self, app=None, **kwargs):
|
||||
if app is not None:
|
||||
self.init_app(app, **kwargs)
|
||||
|
||||
def init_app(
|
||||
self,
|
||||
app,
|
||||
feature_policy=DEFAULT_FEATURE_POLICY,
|
||||
permissions_policy=DEFAULT_PERMISSIONS_POLICY,
|
||||
document_policy=DEFAULT_DOCUMENT_POLICY,
|
||||
force_https=True,
|
||||
force_https_permanent=False,
|
||||
force_file_save=False,
|
||||
frame_options=SAMEORIGIN,
|
||||
frame_options_allow_from=None,
|
||||
strict_transport_security=True,
|
||||
strict_transport_security_preload=False,
|
||||
strict_transport_security_max_age=ONE_YEAR_IN_SECS,
|
||||
strict_transport_security_include_subdomains=True,
|
||||
content_security_policy=DEFAULT_CSP_POLICY,
|
||||
content_security_policy_report_uri=None,
|
||||
content_security_policy_report_only=False,
|
||||
content_security_policy_nonce_in=None,
|
||||
referrer_policy=DEFAULT_REFERRER_POLICY,
|
||||
session_cookie_secure=True,
|
||||
session_cookie_http_only=True,
|
||||
session_cookie_samesite=DEFAULT_SESSION_COOKIE_SAMESITE,
|
||||
x_content_type_options=True,
|
||||
x_xss_protection=False):
|
||||
"""
|
||||
Initialization.
|
||||
|
||||
Args:
|
||||
app: A Flask application.
|
||||
feature_policy: A string or dictionary describing the
|
||||
feature policy for the response.
|
||||
permissions_policy: A string or dictionary describing the
|
||||
permissions policy for the response.
|
||||
document_policy: A string or dictionary describing the
|
||||
document policy for the response.
|
||||
force_https: Redirects non-http requests to https, disabled in
|
||||
debug mode.
|
||||
force_https_permanent: Uses 301 instead of 302 redirects.
|
||||
frame_options: Sets the X-Frame-Options header, defaults to
|
||||
SAMEORIGIN.
|
||||
frame_options_allow_from: Used when frame_options is set to
|
||||
ALLOW_FROM and is a string of domains to allow frame embedding.
|
||||
strict_transport_security: Sets HSTS headers.
|
||||
strict_transport_security_preload: Enables HSTS preload. See
|
||||
https://hstspreload.org.
|
||||
strict_transport_security_max_age: How long HSTS headers are
|
||||
honored by the browser.
|
||||
strict_transport_security_include_subdomains: Whether to include
|
||||
all subdomains when setting HSTS.
|
||||
content_security_policy: A string or dictionary describing the
|
||||
content security policy for the response.
|
||||
content_security_policy_report_uri: A string indicating the report
|
||||
URI used for CSP violation reports
|
||||
content_security_policy_report_only: Whether to set the CSP header
|
||||
as "report-only", which disables the enforcement by the browser
|
||||
and requires a "report-uri" parameter with a backend to receive
|
||||
the POST data
|
||||
content_security_policy_nonce_in: A list of csp sections to include
|
||||
a per-request nonce value in
|
||||
referrer_policy: A string describing the referrer policy for the
|
||||
response.
|
||||
session_cookie_secure: Forces the session cookie to only be sent
|
||||
over https. Disabled in debug mode.
|
||||
session_cookie_http_only: Prevents JavaScript from reading the
|
||||
session cookie.
|
||||
session_cookie_samesite: Sets samesite parameter on session cookie
|
||||
force_file_save: Prevents the user from opening a file download
|
||||
directly on >= IE 8
|
||||
x_content_type_options: Prevents MIME type sniffing
|
||||
x_xss_protection: Prevents the page from loading when the browser
|
||||
detects reflected cross-site scripting attacks
|
||||
|
||||
See README.rst for a detailed description of each option.
|
||||
"""
|
||||
if isinstance(feature_policy, dict):
|
||||
self.feature_policy = OrderedDict(feature_policy)
|
||||
else:
|
||||
self.feature_policy = feature_policy
|
||||
|
||||
if isinstance(permissions_policy, dict):
|
||||
self.permissions_policy = OrderedDict(permissions_policy)
|
||||
else:
|
||||
self.permissions_policy = permissions_policy
|
||||
|
||||
if isinstance(document_policy, dict):
|
||||
self.document_policy = OrderedDict(document_policy)
|
||||
else:
|
||||
self.document_policy = document_policy
|
||||
|
||||
self.force_https = force_https
|
||||
self.force_https_permanent = force_https_permanent
|
||||
|
||||
self.frame_options = frame_options
|
||||
self.frame_options_allow_from = frame_options_allow_from
|
||||
|
||||
self.strict_transport_security = strict_transport_security
|
||||
self.strict_transport_security_preload = \
|
||||
strict_transport_security_preload
|
||||
self.strict_transport_security_max_age = \
|
||||
strict_transport_security_max_age
|
||||
self.strict_transport_security_include_subdomains = \
|
||||
strict_transport_security_include_subdomains
|
||||
|
||||
if isinstance(content_security_policy, dict):
|
||||
self.content_security_policy = OrderedDict(content_security_policy)
|
||||
else:
|
||||
self.content_security_policy = content_security_policy
|
||||
self.content_security_policy_report_uri = \
|
||||
content_security_policy_report_uri
|
||||
self.content_security_policy_report_only = \
|
||||
content_security_policy_report_only
|
||||
if self.content_security_policy_report_only and \
|
||||
self.content_security_policy_report_uri is None:
|
||||
raise ValueError(
|
||||
'Setting content_security_policy_report_only to True also '
|
||||
'requires a URI to be specified in '
|
||||
'content_security_policy_report_uri')
|
||||
self.content_security_policy_nonce_in = (
|
||||
content_security_policy_nonce_in or []
|
||||
)
|
||||
|
||||
app.jinja_env.globals['csp_nonce'] = self._get_nonce
|
||||
|
||||
self.referrer_policy = referrer_policy
|
||||
|
||||
self.session_cookie_secure = session_cookie_secure
|
||||
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = session_cookie_samesite
|
||||
|
||||
if session_cookie_http_only:
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
|
||||
self.force_file_save = force_file_save
|
||||
|
||||
self.x_content_type_options = x_content_type_options
|
||||
|
||||
self.x_xss_protection = x_xss_protection
|
||||
|
||||
self.app = app
|
||||
|
||||
app.before_request(self._force_https)
|
||||
app.before_request(self._make_nonce)
|
||||
app.after_request(self._set_response_headers)
|
||||
|
||||
def _get_local_options(self):
|
||||
view_function = flask.current_app.view_functions.get(
|
||||
flask.request.endpoint)
|
||||
view_options = getattr(
|
||||
view_function, 'talisman_view_options', {})
|
||||
|
||||
view_options.setdefault('force_https', self.force_https)
|
||||
view_options.setdefault('frame_options', self.frame_options)
|
||||
view_options.setdefault(
|
||||
'frame_options_allow_from', self.frame_options_allow_from)
|
||||
view_options.setdefault(
|
||||
'content_security_policy', self.content_security_policy)
|
||||
view_options.setdefault(
|
||||
'content_security_policy_nonce_in',
|
||||
self.content_security_policy_nonce_in)
|
||||
view_options.setdefault(
|
||||
'permissions_policy', self.permissions_policy)
|
||||
view_options.setdefault(
|
||||
'document_policy', self.document_policy)
|
||||
view_options.setdefault(
|
||||
'feature_policy', self.feature_policy
|
||||
)
|
||||
|
||||
return view_options
|
||||
|
||||
def _force_https(self):
|
||||
"""Redirect any non-https requests to https.
|
||||
|
||||
Based largely on flask-sslify.
|
||||
"""
|
||||
|
||||
if self.session_cookie_secure:
|
||||
if not self.app.debug:
|
||||
self.app.config['SESSION_COOKIE_SECURE'] = True
|
||||
|
||||
criteria = [
|
||||
self.app.debug,
|
||||
flask.request.is_secure,
|
||||
flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https',
|
||||
]
|
||||
|
||||
local_options = self._get_local_options()
|
||||
|
||||
if local_options['force_https'] and not any(criteria):
|
||||
if flask.request.url.startswith('http://'):
|
||||
url = flask.request.url.replace('http://', 'https://', 1)
|
||||
code = 302
|
||||
if self.force_https_permanent:
|
||||
code = 301
|
||||
r = flask.redirect(url, code=code)
|
||||
return r
|
||||
|
||||
def _set_response_headers(self, response):
|
||||
"""Applies all configured headers to the given response."""
|
||||
options = self._get_local_options()
|
||||
self._set_feature_policy_headers(response.headers, options)
|
||||
self._set_permissions_policy_headers(response.headers, options)
|
||||
self._set_document_policy_headers(response.headers, options)
|
||||
self._set_frame_options_headers(response.headers, options)
|
||||
self._set_content_security_policy_headers(response.headers, options)
|
||||
self._set_hsts_headers(response.headers)
|
||||
self._set_referrer_policy_headers(response.headers)
|
||||
return response
|
||||
|
||||
def _make_nonce(self):
|
||||
local_options = self._get_local_options()
|
||||
if (
|
||||
local_options['content_security_policy'] and
|
||||
local_options['content_security_policy_nonce_in'] and
|
||||
not getattr(flask.request, 'csp_nonce', None)):
|
||||
flask.request.csp_nonce = get_random_string(NONCE_LENGTH)
|
||||
|
||||
def _get_nonce(self):
|
||||
return getattr(flask.request, 'csp_nonce', '')
|
||||
|
||||
def _parse_structured_header_policy(self, policy):
|
||||
if isinstance(policy, str):
|
||||
return policy
|
||||
|
||||
policies = []
|
||||
for section, content in policy.items():
|
||||
policy_part = '{}={}'.format(section, content)
|
||||
|
||||
policies.append(policy_part)
|
||||
|
||||
policy = ', '.join(policies)
|
||||
|
||||
return policy
|
||||
|
||||
def _parse_policy(self, policy):
|
||||
local_options = self._get_local_options()
|
||||
if isinstance(policy, str):
|
||||
# parse the string into a policy dict
|
||||
policy_string = policy
|
||||
policy = OrderedDict()
|
||||
|
||||
for policy_part in policy_string.split(';'):
|
||||
policy_parts = policy_part.strip().split(' ')
|
||||
policy[policy_parts[0]] = " ".join(policy_parts[1:])
|
||||
|
||||
policies = []
|
||||
for section, content in policy.items():
|
||||
if not isinstance(content, str):
|
||||
content = ' '.join(content)
|
||||
policy_part = '{} {}'.format(section, content)
|
||||
|
||||
if (
|
||||
hasattr(flask.request, 'csp_nonce') and
|
||||
section in local_options['content_security_policy_nonce_in']):
|
||||
policy_part += " 'nonce-{}'".format(flask.request.csp_nonce)
|
||||
|
||||
policies.append(policy_part)
|
||||
|
||||
policy = '; '.join(policies)
|
||||
|
||||
return policy
|
||||
|
||||
def _set_feature_policy_headers(self, headers, options):
|
||||
if not options['feature_policy']:
|
||||
return
|
||||
|
||||
policy = options['feature_policy']
|
||||
policy = self._parse_policy(policy)
|
||||
|
||||
headers['Feature-Policy'] = policy
|
||||
|
||||
def _set_permissions_policy_headers(self, headers, options):
|
||||
if not options['permissions_policy']:
|
||||
return
|
||||
|
||||
policy = options['permissions_policy']
|
||||
policy = self._parse_structured_header_policy(policy)
|
||||
|
||||
headers['Permissions-Policy'] = policy
|
||||
|
||||
def _set_document_policy_headers(self, headers, options):
|
||||
if not options['document_policy']:
|
||||
return
|
||||
|
||||
policy = options['document_policy']
|
||||
policy = self._parse_structured_header_policy(policy)
|
||||
|
||||
headers['Document-Policy'] = policy
|
||||
|
||||
def _set_frame_options_headers(self, headers, options):
|
||||
if not options['frame_options']:
|
||||
return
|
||||
headers['X-Frame-Options'] = options['frame_options']
|
||||
|
||||
if options['frame_options'] == ALLOW_FROM:
|
||||
headers['X-Frame-Options'] += " {}".format(
|
||||
options['frame_options_allow_from'])
|
||||
|
||||
def _set_content_security_policy_headers(self, headers, options):
|
||||
if self.x_xss_protection:
|
||||
headers['X-XSS-Protection'] = '1; mode=block'
|
||||
|
||||
if self.x_content_type_options:
|
||||
headers['X-Content-Type-Options'] = 'nosniff'
|
||||
|
||||
if self.force_file_save:
|
||||
headers['X-Download-Options'] = 'noopen'
|
||||
|
||||
if not options['content_security_policy']:
|
||||
return
|
||||
|
||||
policy = options['content_security_policy']
|
||||
policy = self._parse_policy(policy)
|
||||
|
||||
if self.content_security_policy_report_uri and \
|
||||
'report-uri' not in policy:
|
||||
policy += '; report-uri ' + self.content_security_policy_report_uri
|
||||
|
||||
csp_header = 'Content-Security-Policy'
|
||||
if self.content_security_policy_report_only:
|
||||
csp_header += '-Report-Only'
|
||||
|
||||
headers[csp_header] = policy
|
||||
|
||||
def _set_hsts_headers(self, headers):
|
||||
criteria = [
|
||||
flask.request.is_secure,
|
||||
flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https',
|
||||
]
|
||||
if not self.strict_transport_security or not any(criteria):
|
||||
return
|
||||
|
||||
value = 'max-age={}'.format(self.strict_transport_security_max_age)
|
||||
|
||||
if self.strict_transport_security_include_subdomains:
|
||||
value += '; includeSubDomains'
|
||||
|
||||
if self.strict_transport_security_preload:
|
||||
value += '; preload'
|
||||
|
||||
headers['Strict-Transport-Security'] = value
|
||||
|
||||
def _set_referrer_policy_headers(self, headers):
|
||||
headers['Referrer-Policy'] = self.referrer_policy
|
||||
|
||||
def __call__(self, **kwargs):
|
||||
"""Use talisman as a decorator to configure options for a particular
|
||||
view.
|
||||
|
||||
Only force_https, frame_options, frame_options_allow_from,
|
||||
content_security_policy, content_security_policy_nonce_in
|
||||
and feature_policy can be set on a per-view basis.
|
||||
|
||||
Example:
|
||||
|
||||
app = Flask(__name__)
|
||||
talisman = Talisman(app)
|
||||
|
||||
@app.route('/normal')
|
||||
def normal():
|
||||
return 'Normal'
|
||||
|
||||
@app.route('/embeddable')
|
||||
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
|
||||
def embeddable():
|
||||
return 'Embeddable'
|
||||
"""
|
||||
def decorator(f):
|
||||
setattr(f, 'talisman_view_options', kwargs)
|
||||
return f
|
||||
return decorator
|
||||
|
||||
|
||||
try:
|
||||
import secrets
|
||||
|
||||
def get_random_string(length): # pragma: no cover
|
||||
# Note token_urlsafe returns a 'length'-byte string which is then
|
||||
# base64 encoded so is longer than length, so only return last
|
||||
# 'length' characters.
|
||||
return secrets.token_urlsafe(length)[:length]
|
||||
|
||||
except ImportError: # pragma: no cover
|
||||
import random
|
||||
import string
|
||||
rnd = random.SystemRandom()
|
||||
|
||||
def get_random_string(length):
|
||||
allowed_chars = (
|
||||
string.ascii_lowercase +
|
||||
string.ascii_uppercase +
|
||||
string.digits)
|
||||
return ''.join(
|
||||
rnd.choice(allowed_chars)
|
||||
for _ in range(length))
|
||||
@@ -0,0 +1,344 @@
|
||||
# Copyright 2015 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import unittest
|
||||
|
||||
import flask
|
||||
from flask_talisman import ALLOW_FROM, DENY, NONCE_LENGTH, Talisman
|
||||
|
||||
|
||||
HTTPS_ENVIRON = {'wsgi.url_scheme': 'https'}
|
||||
|
||||
|
||||
def hello_world():
|
||||
return 'Hello, world'
|
||||
|
||||
|
||||
def with_nonce():
|
||||
return flask.render_template_string(
|
||||
'<script nonce="{{csp_nonce()}}"></script>'
|
||||
)
|
||||
|
||||
|
||||
class TestTalismanExtension(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.app = flask.Flask(__name__)
|
||||
self.talisman = Talisman(self.app)
|
||||
self.client = self.app.test_client()
|
||||
|
||||
self.app.route('/')(hello_world)
|
||||
self.app.route('/with_nonce')(with_nonce)
|
||||
|
||||
def testDefaults(self):
|
||||
# HTTPS request.
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
|
||||
headers = {
|
||||
'X-Frame-Options': 'SAMEORIGIN',
|
||||
'Strict-Transport-Security':
|
||||
'max-age=31556926; includeSubDomains',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'strict-origin-when-cross-origin'
|
||||
}
|
||||
|
||||
for key, value in headers.items():
|
||||
self.assertEqual(response.headers.get(key), value)
|
||||
|
||||
csp = response.headers.get('Content-Security-Policy')
|
||||
self.assertIn('default-src \'self\'', csp)
|
||||
self.assertIn('object-src \'none\'', csp)
|
||||
|
||||
def testForceSslOptionOptions(self):
|
||||
# HTTP request from Proxy
|
||||
response = self.client.get('/', headers={
|
||||
'X-Forwarded-Proto': 'https'
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# HTTP Request, should be upgraded to https
|
||||
response = self.client.get('/')
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertTrue(response.headers['Location'].startswith('https://'))
|
||||
|
||||
# Permanent redirects
|
||||
self.talisman.force_https_permanent = True
|
||||
response = self.client.get('/')
|
||||
self.assertEqual(response.status_code, 301)
|
||||
|
||||
# Disable forced ssl, should allow the request.
|
||||
self.talisman.force_https = False
|
||||
response = self.client.get('/')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def testForceXSSProtectionOptions(self):
|
||||
self.talisman.x_xss_protection = True
|
||||
|
||||
# HTTP request from Proxy
|
||||
response = self.client.get('/')
|
||||
self.assertIn('X-XSS-Protection', response.headers)
|
||||
self.assertEqual(response.headers['X-XSS-Protection'], '1; mode=block')
|
||||
|
||||
def testHstsOptions(self):
|
||||
self.talisman.force_ssl = False
|
||||
|
||||
# No HSTS headers for non-ssl requests
|
||||
response = self.client.get('/')
|
||||
self.assertNotIn('Strict-Transport-Security', response.headers)
|
||||
|
||||
# Secure request with HSTS off
|
||||
self.talisman.strict_transport_security = False
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('Strict-Transport-Security', response.headers)
|
||||
|
||||
# HSTS back on
|
||||
self.talisman.strict_transport_security = True
|
||||
|
||||
# HTTPS request through proxy
|
||||
response = self.client.get('/', headers={
|
||||
'X-Forwarded-Proto': 'https'
|
||||
})
|
||||
self.assertIn('Strict-Transport-Security', response.headers)
|
||||
|
||||
# No subdomains
|
||||
self.talisman.strict_transport_security_include_subdomains = False
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn(
|
||||
'includeSubDomains', response.headers['Strict-Transport-Security'])
|
||||
|
||||
# Preload
|
||||
self.talisman.strict_transport_security_preload = True
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('preload', response.headers['Strict-Transport-Security'])
|
||||
|
||||
def testFrameOptions(self):
|
||||
self.talisman.frame_options = DENY
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertEqual(response.headers['X-Frame-Options'], 'DENY')
|
||||
|
||||
self.talisman.frame_options = ALLOW_FROM
|
||||
self.talisman.frame_options_allow_from = 'example.com'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertEqual(
|
||||
response.headers['X-Frame-Options'], 'ALLOW-FROM example.com')
|
||||
|
||||
self.talisman.frame_options = None
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('X-Frame-Options', response.headers)
|
||||
|
||||
def testContentSecurityPolicyOptions(self):
|
||||
self.talisman.content_security_policy['image-src'] = '*'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
csp = response.headers['Content-Security-Policy']
|
||||
self.assertIn("default-src 'self';", csp)
|
||||
self.assertIn("object-src \'none\';", csp)
|
||||
self.assertIn("image-src *", csp)
|
||||
|
||||
self.talisman.content_security_policy['image-src'] = [
|
||||
'\'self\'',
|
||||
'example.com'
|
||||
]
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
csp = response.headers['Content-Security-Policy']
|
||||
self.assertIn('default-src \'self\'', csp)
|
||||
self.assertIn('image-src \'self\' example.com', csp)
|
||||
|
||||
# string policy
|
||||
self.talisman.content_security_policy = 'default-src \'foo\' spam.eggs'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertEqual(response.headers['Content-Security-Policy'],
|
||||
'default-src \'foo\' spam.eggs')
|
||||
|
||||
# no policy
|
||||
self.talisman.content_security_policy = False
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('Content-Security-Policy', response.headers)
|
||||
|
||||
# string policy at initialization
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, content_security_policy='default-src \'foo\' spam.eggs')
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn(
|
||||
'default-src \'foo\' spam.eggs',
|
||||
response.headers['Content-Security-Policy']
|
||||
)
|
||||
|
||||
# x-content-type-options disabled
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, x_content_type_options=False)
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('X-Content-Type-Options', response.headers)
|
||||
|
||||
# x-xss-protection disabled
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, x_xss_protection=False)
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('X-XSS-Protection', response.headers)
|
||||
|
||||
def testContentSecurityPolicyOptionsReport(self):
|
||||
# report-only policy
|
||||
self.talisman.content_security_policy_report_only = True
|
||||
self.talisman.content_security_policy_report_uri = \
|
||||
'https://example.com'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('Content-Security-Policy-Report-Only', response.headers)
|
||||
self.assertIn(
|
||||
'report-uri',
|
||||
response.headers['Content-Security-Policy-Report-Only']
|
||||
)
|
||||
self.assertNotIn('Content-Security-Policy', response.headers)
|
||||
|
||||
override_report_uri = 'https://report-uri.io/'
|
||||
self.talisman.content_security_policy = {
|
||||
'report-uri': override_report_uri,
|
||||
}
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn(
|
||||
'Content-Security-Policy-Report-Only', response.headers)
|
||||
self.assertIn(
|
||||
override_report_uri,
|
||||
response.headers['Content-Security-Policy-Report-Only']
|
||||
)
|
||||
|
||||
# exception on missing report-uri when report-only
|
||||
self.assertRaises(ValueError, Talisman, self.app,
|
||||
content_security_policy_report_only=True)
|
||||
|
||||
def testContentSecurityPolicyNonce(self):
|
||||
self.talisman.content_security_policy['script-src'] = "'self'"
|
||||
self.talisman.content_security_policy['style-src'] = "example.com"
|
||||
self.talisman.content_security_policy_nonce_in = ['script-src']
|
||||
|
||||
with self.app.test_client() as client:
|
||||
response = client.get('/with_nonce',
|
||||
environ_overrides=HTTPS_ENVIRON)
|
||||
|
||||
csp = response.headers['Content-Security-Policy']
|
||||
|
||||
self.assertIn(
|
||||
"script-src 'self' 'nonce-{}'".format(flask.request.csp_nonce),
|
||||
csp
|
||||
)
|
||||
self.assertNotIn(
|
||||
"style-src 'self'",
|
||||
csp
|
||||
)
|
||||
self.assertNotIn(
|
||||
"style-src example.com 'nonce-{}'".format(flask.request.csp_nonce),
|
||||
csp
|
||||
)
|
||||
self.assertIn(
|
||||
"style-src example.com",
|
||||
csp
|
||||
)
|
||||
self.assertIn(
|
||||
flask.request.csp_nonce,
|
||||
response.data.decode("utf-8")
|
||||
)
|
||||
self.assertEqual(len(flask.request.csp_nonce), NONCE_LENGTH)
|
||||
|
||||
def testDecorator(self):
|
||||
@self.app.route('/nocsp')
|
||||
@self.talisman(content_security_policy=None)
|
||||
def nocsp():
|
||||
return 'Hello, world'
|
||||
|
||||
response = self.client.get('/nocsp', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertNotIn('Content-Security-Policy', response.headers)
|
||||
self.assertEqual(response.headers['X-Frame-Options'], 'SAMEORIGIN')
|
||||
|
||||
def testDecoratorForceHttps(self):
|
||||
@self.app.route('/noforcehttps')
|
||||
@self.talisman(force_https=False)
|
||||
def noforcehttps():
|
||||
return 'Hello, world'
|
||||
|
||||
response = self.client.get('/noforcehttps')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def testForceFileSave(self):
|
||||
self.talisman.force_file_save = True
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('X-Download-Options', response.headers)
|
||||
self.assertEqual(response.headers['X-Download-Options'], 'noopen')
|
||||
|
||||
def testBadEndpoint(self):
|
||||
response = self.client.get('/bad_endpoint')
|
||||
self.assertEqual(response.status_code, 302)
|
||||
response = self.client.get('/bad_endpoint',
|
||||
headers={'X-Forwarded-Proto': 'https'})
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
def testFeaturePolicy(self):
|
||||
self.talisman.feature_policy['geolocation'] = '\'none\''
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
feature_policy = response.headers['Feature-Policy']
|
||||
self.assertIn('geolocation \'none\'', feature_policy)
|
||||
|
||||
self.talisman.feature_policy['fullscreen'] = '\'self\' example.com'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
feature_policy = response.headers['Feature-Policy']
|
||||
self.assertIn('fullscreen \'self\' example.com', feature_policy)
|
||||
|
||||
# string policy at initialization
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, feature_policy='vibrate \'none\'')
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('vibrate \'none\'', response.headers['Feature-Policy'])
|
||||
|
||||
def testPermissionsPolicy(self):
|
||||
self.talisman.permissions_policy['geolocation'] = '()'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
permissions_policy = response.headers['Permissions-Policy']
|
||||
self.assertIn('browsing-topics=()', permissions_policy)
|
||||
self.assertIn('geolocation=()', permissions_policy)
|
||||
|
||||
self.talisman.permissions_policy['geolocation'] = '()'
|
||||
self.talisman.permissions_policy['fullscreen'] = '(self, "https://example.com")'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
permissions_policy = response.headers['Permissions-Policy']
|
||||
self.assertIn('browsing-topics=()', permissions_policy)
|
||||
self.assertIn('geolocation=(), fullscreen=(self, "https://example.com")', permissions_policy)
|
||||
|
||||
# no policy
|
||||
self.talisman.permissions_policy = {}
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
permissions_policy = response.headers.get('Permissions-Policy')
|
||||
self.assertEqual(None, permissions_policy)
|
||||
|
||||
# string policy at initialization
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, permissions_policy='vibrate=(), geolocation=()')
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('vibrate=(), geolocation=()', response.headers['Permissions-Policy'])
|
||||
|
||||
def testDocumentPolicy(self):
|
||||
self.talisman.document_policy['oversized-images'] = '?0'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
document_policy = response.headers['Document-Policy']
|
||||
self.assertIn('oversized-images=?0', document_policy)
|
||||
|
||||
self.talisman.document_policy['oversized-images'] = '?0'
|
||||
self.talisman.document_policy['document-write'] = '?0'
|
||||
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
document_policy = response.headers['Document-Policy']
|
||||
self.assertIn('oversized-images=?0, document-write=?0', document_policy)
|
||||
|
||||
# string policy at initialization
|
||||
app = flask.Flask(__name__)
|
||||
Talisman(app, document_policy='oversized-images=?0, document-write=?0')
|
||||
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
|
||||
self.assertIn('oversized-images=?0, document-write=?0', response.headers['Document-Policy'])
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,50 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: mfrc522
|
||||
Version: 0.0.7
|
||||
Summary: A library to integrate the MFRC522 RFID readers with the Raspberry Pi
|
||||
Home-page: https://github.com/pimylifeup/MFRC522-python
|
||||
Author: Pi My Life Up
|
||||
Author-email: support@pimylifeup.com
|
||||
License: UNKNOWN
|
||||
Platform: UNKNOWN
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: Topic :: System :: Hardware
|
||||
Description-Content-Type: text/markdown
|
||||
Requires-Dist: RPi.GPIO
|
||||
Requires-Dist: spidev
|
||||
|
||||
# mfrc522
|
||||
|
||||
A python library to read/write RFID tags via the budget MFRC522 RFID module.
|
||||
|
||||
This code was published in relation to a [blog post](https://pimylifeup.com/raspberry-pi-rfid-rc522/) and you can find out more about how to hook up your MFRC reader to a Raspberry Pi there.
|
||||
|
||||
## Installation
|
||||
|
||||
Until the package is on PyPi, clone this repository and run `python setup.py install` in the top level directory.
|
||||
|
||||
## Example Code
|
||||
|
||||
The following code will read a tag from the MFRC522
|
||||
|
||||
```python
|
||||
from time import sleep
|
||||
import sys
|
||||
from mfrc522 import SimpleMFRC522
|
||||
reader = SimpleMFRC522()
|
||||
|
||||
try:
|
||||
while True:
|
||||
print("Hold a tag near the reader")
|
||||
id, text = reader.read()
|
||||
print("ID: %s\nText: %s" % (id,text))
|
||||
sleep(5)
|
||||
except KeyboardInterrupt:
|
||||
GPIO.cleanup()
|
||||
raise
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
mfrc522-0.0.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
mfrc522-0.0.7.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
||||
mfrc522-0.0.7.dist-info/METADATA,sha256=DuR2cXr2dvuE-x9cZPmmVLUNe97m_kaxsMVDvSbfRns,1438
|
||||
mfrc522-0.0.7.dist-info/RECORD,,
|
||||
mfrc522-0.0.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
mfrc522-0.0.7.dist-info/WHEEL,sha256=U88EhGIw8Sj2_phqajeu_EAi3RAo8-C6zV3REsWbWbs,92
|
||||
mfrc522-0.0.7.dist-info/top_level.txt,sha256=nifp5B2xtRnqBNpnzPn0QYkfXdzBkdnE0XYoBNOHT0M,8
|
||||
mfrc522/MFRC522.py,sha256=BAQ0z1mfv3FOm1d0mSXl6dL-a6GC40hkBR4MvAHQcmU,12560
|
||||
mfrc522/SimpleMFRC522.py,sha256=-Ebpgq4Gpb_r6eOwokU5Xpj8zLdYSmGpHKs4su1LIQc,2823
|
||||
mfrc522/__init__.py,sha256=uLENBHNbvgZJUf8Spyno2Ru55zHVhzMWR-TuXuj8n4U,88
|
||||
mfrc522/__pycache__/MFRC522.cpython-311.pyc,,
|
||||
mfrc522/__pycache__/SimpleMFRC522.cpython-311.pyc,,
|
||||
mfrc522/__pycache__/__init__.cpython-311.pyc,,
|
||||
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.33.1)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
mfrc522
|
||||
425
venv/lib/python3.11/site-packages/mfrc522/MFRC522.py
Normal file
425
venv/lib/python3.11/site-packages/mfrc522/MFRC522.py
Normal file
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf8 -*-
|
||||
#
|
||||
# Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
|
||||
#
|
||||
# This file is part of MFRC522-Python
|
||||
# MFRC522-Python is a simple Python implementation for
|
||||
# the MFRC522 NFC Card Reader for the Raspberry Pi.
|
||||
#
|
||||
# MFRC522-Python is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# MFRC522-Python is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with MFRC522-Python. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import RPi.GPIO as GPIO
|
||||
import spidev
|
||||
import signal
|
||||
import time
|
||||
import logging
|
||||
|
||||
class MFRC522:
|
||||
MAX_LEN = 16
|
||||
|
||||
PCD_IDLE = 0x00
|
||||
PCD_AUTHENT = 0x0E
|
||||
PCD_RECEIVE = 0x08
|
||||
PCD_TRANSMIT = 0x04
|
||||
PCD_TRANSCEIVE = 0x0C
|
||||
PCD_RESETPHASE = 0x0F
|
||||
PCD_CALCCRC = 0x03
|
||||
|
||||
PICC_REQIDL = 0x26
|
||||
PICC_REQALL = 0x52
|
||||
PICC_ANTICOLL = 0x93
|
||||
PICC_SElECTTAG = 0x93
|
||||
PICC_AUTHENT1A = 0x60
|
||||
PICC_AUTHENT1B = 0x61
|
||||
PICC_READ = 0x30
|
||||
PICC_WRITE = 0xA0
|
||||
PICC_DECREMENT = 0xC0
|
||||
PICC_INCREMENT = 0xC1
|
||||
PICC_RESTORE = 0xC2
|
||||
PICC_TRANSFER = 0xB0
|
||||
PICC_HALT = 0x50
|
||||
|
||||
MI_OK = 0
|
||||
MI_NOTAGERR = 1
|
||||
MI_ERR = 2
|
||||
|
||||
Reserved00 = 0x00
|
||||
CommandReg = 0x01
|
||||
CommIEnReg = 0x02
|
||||
DivlEnReg = 0x03
|
||||
CommIrqReg = 0x04
|
||||
DivIrqReg = 0x05
|
||||
ErrorReg = 0x06
|
||||
Status1Reg = 0x07
|
||||
Status2Reg = 0x08
|
||||
FIFODataReg = 0x09
|
||||
FIFOLevelReg = 0x0A
|
||||
WaterLevelReg = 0x0B
|
||||
ControlReg = 0x0C
|
||||
BitFramingReg = 0x0D
|
||||
CollReg = 0x0E
|
||||
Reserved01 = 0x0F
|
||||
|
||||
Reserved10 = 0x10
|
||||
ModeReg = 0x11
|
||||
TxModeReg = 0x12
|
||||
RxModeReg = 0x13
|
||||
TxControlReg = 0x14
|
||||
TxAutoReg = 0x15
|
||||
TxSelReg = 0x16
|
||||
RxSelReg = 0x17
|
||||
RxThresholdReg = 0x18
|
||||
DemodReg = 0x19
|
||||
Reserved11 = 0x1A
|
||||
Reserved12 = 0x1B
|
||||
MifareReg = 0x1C
|
||||
Reserved13 = 0x1D
|
||||
Reserved14 = 0x1E
|
||||
SerialSpeedReg = 0x1F
|
||||
|
||||
Reserved20 = 0x20
|
||||
CRCResultRegM = 0x21
|
||||
CRCResultRegL = 0x22
|
||||
Reserved21 = 0x23
|
||||
ModWidthReg = 0x24
|
||||
Reserved22 = 0x25
|
||||
RFCfgReg = 0x26
|
||||
GsNReg = 0x27
|
||||
CWGsPReg = 0x28
|
||||
ModGsPReg = 0x29
|
||||
TModeReg = 0x2A
|
||||
TPrescalerReg = 0x2B
|
||||
TReloadRegH = 0x2C
|
||||
TReloadRegL = 0x2D
|
||||
TCounterValueRegH = 0x2E
|
||||
TCounterValueRegL = 0x2F
|
||||
|
||||
Reserved30 = 0x30
|
||||
TestSel1Reg = 0x31
|
||||
TestSel2Reg = 0x32
|
||||
TestPinEnReg = 0x33
|
||||
TestPinValueReg = 0x34
|
||||
TestBusReg = 0x35
|
||||
AutoTestReg = 0x36
|
||||
VersionReg = 0x37
|
||||
AnalogTestReg = 0x38
|
||||
TestDAC1Reg = 0x39
|
||||
TestDAC2Reg = 0x3A
|
||||
TestADCReg = 0x3B
|
||||
Reserved31 = 0x3C
|
||||
Reserved32 = 0x3D
|
||||
Reserved33 = 0x3E
|
||||
Reserved34 = 0x3F
|
||||
|
||||
serNum = []
|
||||
|
||||
def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, debugLevel='WARNING'):
|
||||
self.spi = spidev.SpiDev()
|
||||
self.spi.open(bus, device)
|
||||
self.spi.max_speed_hz = spd
|
||||
|
||||
self.logger = logging.getLogger('mfrc522Logger')
|
||||
self.logger.addHandler(logging.StreamHandler())
|
||||
level = logging.getLevelName(debugLevel)
|
||||
self.logger.setLevel(level)
|
||||
|
||||
gpioMode = GPIO.getmode()
|
||||
|
||||
if gpioMode is None:
|
||||
GPIO.setmode(pin_mode)
|
||||
else:
|
||||
pin_mode = gpioMode
|
||||
|
||||
if pin_rst == -1:
|
||||
if pin_mode == 11:
|
||||
pin_rst = 15
|
||||
else:
|
||||
pin_rst = 22
|
||||
|
||||
GPIO.setup(pin_rst, GPIO.OUT)
|
||||
GPIO.output(pin_rst, 1)
|
||||
self.MFRC522_Init()
|
||||
|
||||
def MFRC522_Reset(self):
|
||||
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
|
||||
|
||||
def Write_MFRC522(self, addr, val):
|
||||
val = self.spi.xfer2([(addr << 1) & 0x7E, val])
|
||||
|
||||
def Read_MFRC522(self, addr):
|
||||
val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])
|
||||
return val[1]
|
||||
|
||||
def Close_MFRC522(self):
|
||||
self.spi.close()
|
||||
GPIO.cleanup()
|
||||
|
||||
def SetBitMask(self, reg, mask):
|
||||
tmp = self.Read_MFRC522(reg)
|
||||
self.Write_MFRC522(reg, tmp | mask)
|
||||
|
||||
def ClearBitMask(self, reg, mask):
|
||||
tmp = self.Read_MFRC522(reg)
|
||||
self.Write_MFRC522(reg, tmp & (~mask))
|
||||
|
||||
def AntennaOn(self):
|
||||
temp = self.Read_MFRC522(self.TxControlReg)
|
||||
if (~(temp & 0x03)):
|
||||
self.SetBitMask(self.TxControlReg, 0x03)
|
||||
|
||||
def AntennaOff(self):
|
||||
self.ClearBitMask(self.TxControlReg, 0x03)
|
||||
|
||||
def MFRC522_ToCard(self, command, sendData):
|
||||
backData = []
|
||||
backLen = 0
|
||||
status = self.MI_ERR
|
||||
irqEn = 0x00
|
||||
waitIRq = 0x00
|
||||
lastBits = None
|
||||
n = 0
|
||||
|
||||
if command == self.PCD_AUTHENT:
|
||||
irqEn = 0x12
|
||||
waitIRq = 0x10
|
||||
if command == self.PCD_TRANSCEIVE:
|
||||
irqEn = 0x77
|
||||
waitIRq = 0x30
|
||||
|
||||
self.Write_MFRC522(self.CommIEnReg, irqEn | 0x80)
|
||||
self.ClearBitMask(self.CommIrqReg, 0x80)
|
||||
self.SetBitMask(self.FIFOLevelReg, 0x80)
|
||||
|
||||
self.Write_MFRC522(self.CommandReg, self.PCD_IDLE)
|
||||
|
||||
for i in range(len(sendData)):
|
||||
self.Write_MFRC522(self.FIFODataReg, sendData[i])
|
||||
|
||||
self.Write_MFRC522(self.CommandReg, command)
|
||||
|
||||
if command == self.PCD_TRANSCEIVE:
|
||||
self.SetBitMask(self.BitFramingReg, 0x80)
|
||||
|
||||
i = 2000
|
||||
while True:
|
||||
n = self.Read_MFRC522(self.CommIrqReg)
|
||||
i -= 1
|
||||
if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):
|
||||
break
|
||||
|
||||
self.ClearBitMask(self.BitFramingReg, 0x80)
|
||||
|
||||
if i != 0:
|
||||
if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00:
|
||||
status = self.MI_OK
|
||||
|
||||
if n & irqEn & 0x01:
|
||||
status = self.MI_NOTAGERR
|
||||
|
||||
if command == self.PCD_TRANSCEIVE:
|
||||
n = self.Read_MFRC522(self.FIFOLevelReg)
|
||||
lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
|
||||
if lastBits != 0:
|
||||
backLen = (n - 1) * 8 + lastBits
|
||||
else:
|
||||
backLen = n * 8
|
||||
|
||||
if n == 0:
|
||||
n = 1
|
||||
if n > self.MAX_LEN:
|
||||
n = self.MAX_LEN
|
||||
|
||||
for i in range(n):
|
||||
backData.append(self.Read_MFRC522(self.FIFODataReg))
|
||||
else:
|
||||
status = self.MI_ERR
|
||||
|
||||
return (status, backData, backLen)
|
||||
|
||||
def MFRC522_Request(self, reqMode):
|
||||
status = None
|
||||
backBits = None
|
||||
TagType = []
|
||||
|
||||
self.Write_MFRC522(self.BitFramingReg, 0x07)
|
||||
|
||||
TagType.append(reqMode)
|
||||
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
|
||||
|
||||
if ((status != self.MI_OK) | (backBits != 0x10)):
|
||||
status = self.MI_ERR
|
||||
|
||||
return (status, backBits)
|
||||
|
||||
def MFRC522_Anticoll(self):
|
||||
backData = []
|
||||
serNumCheck = 0
|
||||
|
||||
serNum = []
|
||||
|
||||
self.Write_MFRC522(self.BitFramingReg, 0x00)
|
||||
|
||||
serNum.append(self.PICC_ANTICOLL)
|
||||
serNum.append(0x20)
|
||||
|
||||
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum)
|
||||
|
||||
if (status == self.MI_OK):
|
||||
i = 0
|
||||
if len(backData) == 5:
|
||||
for i in range(4):
|
||||
serNumCheck = serNumCheck ^ backData[i]
|
||||
if serNumCheck != backData[4]:
|
||||
status = self.MI_ERR
|
||||
else:
|
||||
status = self.MI_ERR
|
||||
|
||||
return (status, backData)
|
||||
|
||||
def CalulateCRC(self, pIndata):
|
||||
self.ClearBitMask(self.DivIrqReg, 0x04)
|
||||
self.SetBitMask(self.FIFOLevelReg, 0x80)
|
||||
|
||||
for i in range(len(pIndata)):
|
||||
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
|
||||
|
||||
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
|
||||
i = 0xFF
|
||||
while True:
|
||||
n = self.Read_MFRC522(self.DivIrqReg)
|
||||
i -= 1
|
||||
if not ((i != 0) and not (n & 0x04)):
|
||||
break
|
||||
pOutData = []
|
||||
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
|
||||
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
|
||||
return pOutData
|
||||
|
||||
def MFRC522_SelectTag(self, serNum):
|
||||
backData = []
|
||||
buf = []
|
||||
buf.append(self.PICC_SElECTTAG)
|
||||
buf.append(0x70)
|
||||
|
||||
for i in range(5):
|
||||
buf.append(serNum[i])
|
||||
|
||||
pOut = self.CalulateCRC(buf)
|
||||
buf.append(pOut[0])
|
||||
buf.append(pOut[1])
|
||||
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
|
||||
|
||||
if (status == self.MI_OK) and (backLen == 0x18):
|
||||
self.logger.debug("Size: " + str(backData[0]))
|
||||
return backData[0]
|
||||
else:
|
||||
return 0
|
||||
|
||||
def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
|
||||
buff = []
|
||||
|
||||
# First byte should be the authMode (A or B)
|
||||
buff.append(authMode)
|
||||
|
||||
# Second byte is the trailerBlock (usually 7)
|
||||
buff.append(BlockAddr)
|
||||
|
||||
# Now we need to append the authKey which usually is 6 bytes of 0xFF
|
||||
for i in range(len(Sectorkey)):
|
||||
buff.append(Sectorkey[i])
|
||||
|
||||
# Next we append the first 4 bytes of the UID
|
||||
for i in range(4):
|
||||
buff.append(serNum[i])
|
||||
|
||||
# Now we start the authentication itself
|
||||
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff)
|
||||
|
||||
# Check if an error occurred
|
||||
if not (status == self.MI_OK):
|
||||
self.logger.error("AUTH ERROR!!")
|
||||
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
|
||||
self.logger.error("AUTH ERROR(status2reg & 0x08) != 0")
|
||||
|
||||
# Return the status
|
||||
return status
|
||||
|
||||
def MFRC522_StopCrypto1(self):
|
||||
self.ClearBitMask(self.Status2Reg, 0x08)
|
||||
|
||||
def MFRC522_Read(self, blockAddr):
|
||||
recvData = []
|
||||
recvData.append(self.PICC_READ)
|
||||
recvData.append(blockAddr)
|
||||
pOut = self.CalulateCRC(recvData)
|
||||
recvData.append(pOut[0])
|
||||
recvData.append(pOut[1])
|
||||
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
|
||||
if not (status == self.MI_OK):
|
||||
self.logger.error("Error while reading!")
|
||||
|
||||
if len(backData) == 16:
|
||||
self.logger.debug("Sector " + str(blockAddr) + " " + str(backData))
|
||||
return backData
|
||||
else:
|
||||
return None
|
||||
|
||||
def MFRC522_Write(self, blockAddr, writeData):
|
||||
buff = []
|
||||
buff.append(self.PICC_WRITE)
|
||||
buff.append(blockAddr)
|
||||
crc = self.CalulateCRC(buff)
|
||||
buff.append(crc[0])
|
||||
buff.append(crc[1])
|
||||
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
|
||||
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
|
||||
status = self.MI_ERR
|
||||
|
||||
self.logger.debug("%s backdata &0x0F == 0x0A %s" % (backLen, backData[0] & 0x0F))
|
||||
if status == self.MI_OK:
|
||||
buf = []
|
||||
for i in range(16):
|
||||
buf.append(writeData[i])
|
||||
|
||||
crc = self.CalulateCRC(buf)
|
||||
buf.append(crc[0])
|
||||
buf.append(crc[1])
|
||||
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
|
||||
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
|
||||
self.logger.error("Error while writing")
|
||||
if status == self.MI_OK:
|
||||
self.logger.debug("Data written")
|
||||
|
||||
|
||||
def MFRC522_DumpClassic1K(self, key, uid):
|
||||
for i in range(64):
|
||||
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
|
||||
# Check if authenticated
|
||||
if status == self.MI_OK:
|
||||
self.MFRC522_Read(i)
|
||||
else:
|
||||
self.logger.error("Authentication error")
|
||||
|
||||
def MFRC522_Init(self):
|
||||
self.MFRC522_Reset()
|
||||
|
||||
self.Write_MFRC522(self.TModeReg, 0x8D)
|
||||
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
|
||||
self.Write_MFRC522(self.TReloadRegL, 30)
|
||||
self.Write_MFRC522(self.TReloadRegH, 0)
|
||||
|
||||
self.Write_MFRC522(self.TxAutoReg, 0x40)
|
||||
self.Write_MFRC522(self.ModeReg, 0x3D)
|
||||
self.AntennaOn()
|
||||
90
venv/lib/python3.11/site-packages/mfrc522/SimpleMFRC522.py
Normal file
90
venv/lib/python3.11/site-packages/mfrc522/SimpleMFRC522.py
Normal file
@@ -0,0 +1,90 @@
|
||||
# Code by Simon Monk https://github.com/simonmonk/
|
||||
|
||||
from . import MFRC522
|
||||
import RPi.GPIO as GPIO
|
||||
|
||||
class SimpleMFRC522:
|
||||
|
||||
READER = None
|
||||
|
||||
KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
|
||||
BLOCK_ADDRS = [8, 9, 10]
|
||||
|
||||
def __init__(self):
|
||||
self.READER = MFRC522()
|
||||
|
||||
def read(self):
|
||||
id, text = self.read_no_block()
|
||||
while not id:
|
||||
id, text = self.read_no_block()
|
||||
return id, text
|
||||
|
||||
def read_id(self):
|
||||
id = self.read_id_no_block()
|
||||
while not id:
|
||||
id = self.read_id_no_block()
|
||||
return id
|
||||
|
||||
def read_id_no_block(self):
|
||||
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
|
||||
if status != self.READER.MI_OK:
|
||||
return None
|
||||
(status, uid) = self.READER.MFRC522_Anticoll()
|
||||
if status != self.READER.MI_OK:
|
||||
return None
|
||||
return self.uid_to_num(uid)
|
||||
|
||||
def read_no_block(self):
|
||||
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
|
||||
if status != self.READER.MI_OK:
|
||||
return None, None
|
||||
(status, uid) = self.READER.MFRC522_Anticoll()
|
||||
if status != self.READER.MI_OK:
|
||||
return None, None
|
||||
id = self.uid_to_num(uid)
|
||||
self.READER.MFRC522_SelectTag(uid)
|
||||
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
|
||||
data = []
|
||||
text_read = ''
|
||||
if status == self.READER.MI_OK:
|
||||
for block_num in self.BLOCK_ADDRS:
|
||||
block = self.READER.MFRC522_Read(block_num)
|
||||
if block:
|
||||
data += block
|
||||
if data:
|
||||
text_read = ''.join(chr(i) for i in data)
|
||||
self.READER.MFRC522_StopCrypto1()
|
||||
return id, text_read
|
||||
|
||||
def write(self, text):
|
||||
id, text_in = self.write_no_block(text)
|
||||
while not id:
|
||||
id, text_in = self.write_no_block(text)
|
||||
return id, text_in
|
||||
|
||||
def write_no_block(self, text):
|
||||
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
|
||||
if status != self.READER.MI_OK:
|
||||
return None, None
|
||||
(status, uid) = self.READER.MFRC522_Anticoll()
|
||||
if status != self.READER.MI_OK:
|
||||
return None, None
|
||||
id = self.uid_to_num(uid)
|
||||
self.READER.MFRC522_SelectTag(uid)
|
||||
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
|
||||
self.READER.MFRC522_Read(11)
|
||||
if status == self.READER.MI_OK:
|
||||
data = bytearray()
|
||||
data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii')))
|
||||
i = 0
|
||||
for block_num in self.BLOCK_ADDRS:
|
||||
self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16])
|
||||
i += 1
|
||||
self.READER.MFRC522_StopCrypto1()
|
||||
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]
|
||||
|
||||
def uid_to_num(self, uid):
|
||||
n = 0
|
||||
for i in range(0, 5):
|
||||
n = n * 256 + uid[i]
|
||||
return n
|
||||
4
venv/lib/python3.11/site-packages/mfrc522/__init__.py
Normal file
4
venv/lib/python3.11/site-packages/mfrc522/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from .MFRC522 import MFRC522
|
||||
from .SimpleMFRC522 import SimpleMFRC522
|
||||
|
||||
name = "mfrc522"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
pip
|
||||
276
venv/lib/python3.11/site-packages/spidev-3.8.dist-info/METADATA
Normal file
276
venv/lib/python3.11/site-packages/spidev-3.8.dist-info/METADATA
Normal file
@@ -0,0 +1,276 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: spidev
|
||||
Version: 3.8
|
||||
Summary: Python bindings for Linux SPI access through spidev
|
||||
Home-page: http://github.com/doceme/py-spidev
|
||||
Author: Volker Thoms
|
||||
Author-email: unconnected@gmx.de
|
||||
Maintainer: Stephen Caudle
|
||||
Maintainer-email: scaudle@doceme.com
|
||||
License: MIT
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Programming Language :: Python :: 2.6
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Topic :: Software Development
|
||||
Classifier: Topic :: System :: Hardware
|
||||
Classifier: Topic :: System :: Hardware :: Hardware Drivers
|
||||
Description-Content-Type: text/markdown
|
||||
License-File: LICENSE
|
||||
Dynamic: author
|
||||
Dynamic: author-email
|
||||
Dynamic: classifier
|
||||
Dynamic: description
|
||||
Dynamic: description-content-type
|
||||
Dynamic: home-page
|
||||
Dynamic: license
|
||||
Dynamic: license-file
|
||||
Dynamic: maintainer
|
||||
Dynamic: maintainer-email
|
||||
Dynamic: summary
|
||||
|
||||
Python Spidev
|
||||
=============
|
||||
|
||||
This project contains a python module for interfacing with SPI devices from user space via the spidev linux kernel driver.
|
||||
|
||||
All code is MIT licensed unless explicitly stated otherwise.
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
```python
|
||||
import spidev
|
||||
spi = spidev.SpiDev()
|
||||
spi.open_path(spidev_devicefile_path)
|
||||
to_send = [0x01, 0x02, 0x03]
|
||||
spi.xfer(to_send)
|
||||
```
|
||||
Settings
|
||||
--------
|
||||
|
||||
```python
|
||||
import spidev
|
||||
spi = spidev.SpiDev()
|
||||
spi.open_path("/dev/spidev0.0")
|
||||
|
||||
# Settings (for example)
|
||||
spi.max_speed_hz = 5000
|
||||
spi.mode = 0b01
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
* `bits_per_word`
|
||||
* `cshigh`
|
||||
* `loop` - Set the "SPI_LOOP" flag to enable loopback mode
|
||||
* `no_cs` - Set the "SPI_NO_CS" flag to disable use of the chip select (although the driver may still own the CS pin)
|
||||
* `lsbfirst`
|
||||
* `max_speed_hz`
|
||||
* `mode` - SPI mode as two bit pattern of clock polarity and phase [CPOL|CPHA], min: 0b00 = 0, max: 0b11 = 3
|
||||
* `threewire` - SI/SO signals shared
|
||||
* `read0` - Read 0 bytes after transfer to lower CS if cshigh == True
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
open_path(filesystem_path)
|
||||
|
||||
Connects to the specified SPI device special file, following symbolic links if
|
||||
appropriate (see note on deterministic SPI bus numbering in the Linux kernel
|
||||
below for why this can be advantageous in some configurations).
|
||||
|
||||
open(bus, device)
|
||||
|
||||
Equivalent to calling `open_path("/dev/spidev<bus>.<device>")`. n.b. **Either**
|
||||
`open_path` or `open` should be used.
|
||||
|
||||
readbytes(n)
|
||||
|
||||
Read n bytes from SPI device.
|
||||
|
||||
writebytes(list of values)
|
||||
|
||||
Writes a list of values to SPI device.
|
||||
|
||||
writebytes2(list of values)
|
||||
|
||||
Similar to `writebytes` but accepts arbitrary large lists.
|
||||
If list size exceeds buffer size (which is read from `/sys/module/spidev/parameters/bufsiz`),
|
||||
data will be split into smaller chunks and sent in multiple operations.
|
||||
|
||||
Also, `writebytes2` understands [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
|
||||
so it can accept numpy byte arrays for example without need to convert them with `tolist()` first.
|
||||
This offers much better performance where you need to transfer frames to SPI-connected displays for instance.
|
||||
|
||||
xfer(list of values[, speed_hz, delay_usec, bits_per_word])
|
||||
|
||||
Performs an SPI transaction. Chip-select should be released and reactivated between blocks.
|
||||
Delay specifies the delay in usec between blocks.
|
||||
|
||||
xfer2(list of values[, speed_hz, delay_usec, bits_per_word])
|
||||
|
||||
Performs an SPI transaction. Chip-select should be held active between blocks.
|
||||
|
||||
xfer3(list of values[, speed_hz, delay_usec, bits_per_word])
|
||||
|
||||
Similar to `xfer2` but accepts arbitrary large lists.
|
||||
If list size exceeds buffer size (which is read from `/sys/module/spidev/parameters/bufsiz`),
|
||||
data will be split into smaller chunks and sent in multiple operations.
|
||||
|
||||
close()
|
||||
|
||||
Disconnects from the SPI device.
|
||||
|
||||
The Linux kernel and SPI bus numbering and the role of udev
|
||||
-----------------------------------------------------------
|
||||
|
||||
### Summary
|
||||
|
||||
If your code may interact with an SPI controller which is attached to the
|
||||
system via the USB or PCI buses, **or** if you are maintaining a product which
|
||||
is likely to change SoCs **or upgrade kernels** during its lifetime, then you
|
||||
should consider using one or more udev rules to create symlinks to the SPI
|
||||
controller spidev, and then use `open_path`, to open the device file via the
|
||||
symlink in your code.
|
||||
|
||||
Consider allowing the end-user to configure their choice of full spidev path -
|
||||
for example with the use of a command line argument to your Python script, or
|
||||
an entry in a configuration file which your code reads and parses.
|
||||
|
||||
Additional udev actions can also set the ownership and file access permissions
|
||||
on the spidev device node file (to increase the security of the system). In
|
||||
some instances, udev rules may also be needed to ensure that spidev device
|
||||
nodes are created in the first place (by triggering the Linux `spidev` driver
|
||||
to "bind" to an underlying SPI controller).
|
||||
|
||||
### Detailed Information
|
||||
|
||||
This section provides an overview of the Linux APIs which this extension uses.
|
||||
|
||||
**If your software might be used on systems with non-deterministic SPI bus
|
||||
numbering**, then using the `open_path` method can allow those maintaining the
|
||||
system to use mechanisms such as `udev` to create stable symbolic links to the
|
||||
SPI device for the correct physical SPI bus.
|
||||
|
||||
See the example udev rule file `99-local-spi-example-udev.rules`.
|
||||
|
||||
This Python extension communicates with SPI devices by using the 'spidev'
|
||||
[Linux kernel SPI userspace
|
||||
API](https://www.kernel.org/doc/html/next/spi/spidev.html).
|
||||
|
||||
'spidev' in turn communicates with SPI bus controller hardware using the
|
||||
kernel's internal SPI APIs and hardware device drivers.
|
||||
|
||||
If the system is configured to expose a particular SPI device to user space
|
||||
(i.e. when an SPI device is "bound" to the spidev driver), then the spidev
|
||||
driver registers this device with the kernel, and exposes its Linux kernel SPI
|
||||
bus number and SPI chip select number to user space in the form of a POSIX
|
||||
"character device" special file.
|
||||
|
||||
A user space program (usually 'udev') listens for kernel device creation
|
||||
events, and creates a file system "device node" for user space software to
|
||||
interact with. By convention, for spidev, the device nodes are named
|
||||
/dev/spidev<bus>.<device> is (where the *bus* is the Linux kernel's internal
|
||||
SPI bus number (see below) and the *device* number corresponds to the SPI
|
||||
controller "chip select" output pin that is connected to the SPI *device* 'chip
|
||||
select' input pin.
|
||||
|
||||
The Linux kernel **may assign SPI bus numbers to a system's SPI controllers in
|
||||
a non-deterministic way.** In some hardware configurations, the SPI bus number
|
||||
of a particular hardware peripheral is:
|
||||
|
||||
- Not guaranteed to remain constant between different Linux kernel versions.
|
||||
- Not guaranteed to remain constant between successive boots of the same kernel
|
||||
(due to race conditions during boot-time hardware enumeration, or dynamic
|
||||
kernel module loading).
|
||||
- Not guaranteed to match the hardware manufacturer's SPI bus numbering scheme.
|
||||
|
||||
In the case of SPI controllers which are themselves connected to the system via
|
||||
buses that are subject to hot-plug (such as USB, Thunderbolt, or PCI), the
|
||||
SPI bus number should usually be expected to be non-deterministic.
|
||||
|
||||
The supported Linux mechanism which allows user space software to identify the
|
||||
correct hardware, it to compose "udev rules" which create stable symbolic links
|
||||
to device files. For example, most Linux distributions automatically create
|
||||
symbolic links to allow identification of block storage devices e.g. see the
|
||||
output of `ls -alR /dev/disk`.
|
||||
|
||||
`99-local-spi-example-udev.rules` included with py-spidev includes example udev
|
||||
rules for creating stable symlink device paths (for use with `open_path`).
|
||||
|
||||
e.g. the following Python code could be used to communicate with an SPI device
|
||||
attached to chip-select line 0 of an individual FTDI FT232H USB to SPI adapter
|
||||
which has the USB serial number "1A8FG636":
|
||||
|
||||
|
||||
```
|
||||
#!/usr/bin/env python3
|
||||
import spidev
|
||||
|
||||
spi = spidev.SpiDev()
|
||||
spi.open_path("/dev/spi/by-path/usb-sernum-1A8FG636-cs-0")
|
||||
# TODO: Useful stuff here
|
||||
spi.close()
|
||||
|
||||
```
|
||||
|
||||
In the more general case, the example udev file should be modified as
|
||||
appropriate to your needs, renamed to something descriptive of the purpose
|
||||
and/or project, and placed in `/etc/udev/rules.d/` (or `/lib/udev/rules.d/` in
|
||||
the case of rules files included with operating system packages).
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
3.8
|
||||
====
|
||||
|
||||
* Added open_path method to accommodate dynamic SPI bus number allocation
|
||||
|
||||
3.7
|
||||
===
|
||||
|
||||
* Fixed installation deprecation warning
|
||||
|
||||
3.6
|
||||
====
|
||||
|
||||
* Added read0 flag to enable reading 0 bytes after transfer to lower CS when cshigh == True
|
||||
|
||||
3.5
|
||||
====
|
||||
|
||||
* Fixed memory leaks
|
||||
|
||||
3.4
|
||||
=====
|
||||
|
||||
* Changed license to MIT
|
||||
|
||||
3.0.1
|
||||
=====
|
||||
|
||||
* Fixed README.md and CHANGELOG.md formatting, hopefully
|
||||
|
||||
3.0
|
||||
===
|
||||
|
||||
* Memset fix recommended by Dougie Lawson
|
||||
* Fixes for Kernel 3.15+ from https://github.com/chrillomat/py-spidev
|
||||
* Fixes for Python 3/2 compatibility.
|
||||
* Added subclassing support - https://github.com/doceme/py-spidev/issues/10
|
||||
|
||||
2.0
|
||||
===
|
||||
|
||||
Code sourced from http://elk.informatik.fh-augsburg.de/da/da-49/trees/pyap7k/lang/py-spi
|
||||
and modified.
|
||||
|
||||
Pre 2.0
|
||||
=======
|
||||
|
||||
spimodule.c originally uathored by Volker Thoms, 2009.
|
||||
@@ -0,0 +1,7 @@
|
||||
spidev-3.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
spidev-3.8.dist-info/METADATA,sha256=B98zilX1SKoe_rOFghsGyaV852GHoQyWpmF52GGiaIc,9262
|
||||
spidev-3.8.dist-info/RECORD,,
|
||||
spidev-3.8.dist-info/WHEEL,sha256=kOE5YCW3k8HyUKo2VIIfZUnbnbVy91mH1mbQOEtImFE,104
|
||||
spidev-3.8.dist-info/licenses/LICENSE,sha256=UQEpvIF0wPqB-m1lNpHRvV01VffziXnsRbX8W7_1N3s,1092
|
||||
spidev-3.8.dist-info/top_level.txt,sha256=44pvfbj3ltXTNIZtsGBpy8p3g-DJtpS2CZDMFrXY-es,7
|
||||
spidev.cpython-311-x86_64-linux-gnu.so,sha256=56ng5Hz1d3c9RGEsz1N1QNEWZKD_cFaVv4blWfd-dn4,92528
|
||||
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: setuptools (82.0.1)
|
||||
Root-Is-Purelib: false
|
||||
Tag: cp311-cp311-linux_x86_64
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Stephen Caudle <stephen@caudle.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
spidev
|
||||
BIN
venv/lib/python3.11/site-packages/spidev.cpython-311-x86_64-linux-gnu.so
Executable file
BIN
venv/lib/python3.11/site-packages/spidev.cpython-311-x86_64-linux-gnu.so
Executable file
Binary file not shown.
Reference in New Issue
Block a user