├── .github └── workflows │ ├── build.yml │ ├── lint.yml │ └── publish.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.en.md ├── README.md ├── accesser.py ├── accesser.spec ├── accesser ├── __init__.py ├── __main__.py ├── config.toml ├── custom.toml.sample ├── pac ├── rules.toml └── utils │ ├── __init__.py │ ├── cert_verify.py │ ├── certmanager.py │ ├── importca.py │ ├── log.py │ ├── setting.py │ └── sysproxy.py ├── pyproject.toml └── requirements.txt /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Auto build for windows 2 | 3 | on: 4 | push: 5 | branches: [ '*' ] 6 | tags: [ 'v*.*.*' ] 7 | pull_request: 8 | branches: [ '*' ] 9 | 10 | jobs: 11 | windows: 12 | runs-on: windows-2022 13 | steps: 14 | - name: Setup python 15 | uses: actions/setup-python@v5 16 | with: 17 | python-version: '3.12' 18 | architecture: x64 19 | - uses: actions/checkout@v4 20 | - name: Install dependencies 21 | run: | 22 | pip install pyinstaller dnspython[doh,doq] rich 23 | pip install -r requirements.txt 24 | - name: Package Application 25 | run: | 26 | pyinstaller accesser.spec 27 | env: 28 | PYTHONOPTIMIZE: 1 29 | - uses: actions/upload-artifact@v4 30 | with: 31 | name: windows 32 | path: ./dist/ 33 | 34 | windows-lite: 35 | runs-on: windows-2022 36 | steps: 37 | - name: Setup python 38 | uses: actions/setup-python@v5 39 | with: 40 | python-version: '3.12' 41 | architecture: x64 42 | - uses: actions/checkout@v4 43 | - name: Install dependencies 44 | run: | 45 | pip install pyinstaller 46 | pip install -r requirements.txt 47 | - name: Package Application 48 | run: | 49 | sed -i 's/^ \+\"https/# \"https/' accesser/rules.toml 50 | pyinstaller accesser.spec 51 | env: 52 | PYTHONOPTIMIZE: 1 53 | - uses: actions/upload-artifact@v4 54 | with: 55 | name: windows-lite 56 | path: ./dist/ 57 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: [ '*' ] 6 | pull_request: 7 | branches: [ '*' ] 8 | 9 | jobs: 10 | toml-lint: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-python@v5 15 | with: 16 | python-version: ">=3.11" 17 | - run: | 18 | python3 -c 'import tomllib; tomllib.load(open("accesser/config.toml", "rb"))' 19 | - run: | 20 | python3 -c 'import tomllib; tomllib.load(open("accesser/rules.toml", "rb"))' 21 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distribution 📦 to PyPI and TestPyPI 2 | 3 | on: 4 | push: 5 | tags: [ 'v*.*.*' ] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | name: Build distribution 📦 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Set up Python 16 | uses: actions/setup-python@v5 17 | with: 18 | python-version: "3.x" 19 | - name: Install pypa/build 20 | run: >- 21 | python3 -m 22 | pip install 23 | build 24 | --user 25 | - name: Build a binary wheel and a source tarball 26 | run: python3 -m build 27 | - name: Store the distribution packages 28 | uses: actions/upload-artifact@v4 29 | with: 30 | name: python-package-distributions 31 | path: dist/ 32 | 33 | publish-to-testpypi: 34 | name: Publish Python 🐍 distribution 📦 to TestPyPI 35 | if: startsWith(github.ref, 'refs/tags/') 36 | needs: 37 | - build 38 | runs-on: ubuntu-latest 39 | 40 | environment: 41 | name: testpypi 42 | url: https://test.pypi.org/p/accesser 43 | 44 | permissions: 45 | id-token: write 46 | 47 | steps: 48 | - name: Download all the dists 49 | uses: actions/download-artifact@v4 50 | with: 51 | name: python-package-distributions 52 | path: dist/ 53 | - name: Publish distribution 📦 to TestPyPI 54 | uses: pypa/gh-action-pypi-publish@release/v1 55 | with: 56 | repository-url: https://test.pypi.org/legacy/ 57 | 58 | publish-to-pypi: 59 | name: >- 60 | Publish Python 🐍 distribution 📦 to PyPI 61 | if: startsWith(github.ref, 'refs/tags/') 62 | needs: 63 | - build 64 | runs-on: ubuntu-latest 65 | environment: 66 | name: pypi 67 | url: https://pypi.org/p/accesser 68 | permissions: 69 | id-token: write 70 | 71 | steps: 72 | - name: Download all the dists 73 | uses: actions/download-artifact@v4 74 | with: 75 | name: python-package-distributions 76 | path: dist/ 77 | - name: Publish distribution 📦 to PyPI 78 | uses: pypa/gh-action-pypi-publish@release/v1 79 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *.cover 46 | .hypothesis/ 47 | .pytest_cache/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | db.sqlite3 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # Environments 84 | .env 85 | .venv 86 | env/ 87 | venv/ 88 | ENV/ 89 | env.bak/ 90 | venv.bak/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | .spyproject 95 | 96 | # Rope project settings 97 | .ropeproject 98 | 99 | # mkdocs documentation 100 | /site 101 | 102 | # mypy 103 | .mypy_cache/ 104 | 105 | python/ 106 | CERT/ 107 | hosts 108 | *.exe 109 | .1 110 | config.toml 111 | rules.toml 112 | rules 113 | 114 | # vscode 115 | .vscode -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11 2 | WORKDIR /accesser 3 | 4 | RUN pip install -U "accesser[doh,doq]" 5 | 6 | EXPOSE 7654 7 | VOLUME /accesser 8 | 9 | CMD ["accesser","--notsetproxy","--notimportca"] 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 | # Accesser 2 | [中文版本](README.md) 3 | 4 | A tool that solves SNI RST, which blocks sites like Wikipedia and Pixiv on the main land of China. 5 | 6 | Because the main users of this project are in mainland China, you may encounter a lot of Chinese. Google translate may help you. 7 | 8 | [Supported sites](https://github.com/URenko/Accesser/wiki/目前支持的站点) 9 | 10 | [![](https://img.shields.io/github/release/URenko/Accesser.svg)](https://github.com/URenko/Accesser/releases/latest) 11 | [![](https://img.shields.io/pypi/v/accesser)](https://pypi.org/project/accesser/) 12 | [![](https://img.shields.io/github/downloads/URenko/Accesser/total.svg)](https://github.com/URenko/Accesser/releases/latest) 13 | [![](https://img.shields.io/github/license/URenko/Accesser.svg)](https://github.com/URenko/Accesser/blob/master/LICENSE) 14 | 15 | ## Usage 16 | ### If you don't know what Python is 17 | Download Windows executable program from [here](https://github.com/URenko/Accesser/releases/download/v0.11.0/accesser.exe) and run it. The first time you use it, you will be asked to install a certificate, just select yes. 18 | ### If Python 3.10* or later is already installed 19 | ``` 20 | pip3 install -U "accesser[doh,doq]" 21 | ``` 22 | If you don't need DNS-over-HTTPS and DNS-over-QUIC, you can install without `[doh,doq]`. 23 | 24 | Then launch it with the following command: 25 | ``` 26 | accesser 27 | ``` 28 | For Windows, by default (without specifying `--notsetproxy`) it will set the system PAC proxy to `http://localhost:7654/pac/?t=`, if not you can set it manually. 29 | 30 | In addition, for Windows, by default (without specifying `--notimportca`) the certificate will be imported to the system automatically, if not you can import it manually, please see [here](https://github.com/URenko/Accesser/wiki/FAQ#q-windows%E8%AE%BF%E9%97%AE%E7%9B%B8%E5%85%B3%E7%BD%91%E7%AB%99%E5%87%BA%E7%8E%B0%E8%AF%81%E4%B9%A6%E9%94%99%E8%AF%AF%E6%82%A8%E7%9A%84%E8%BF%9E%E6%8E%A5%E4%B8%8D%E6%98%AF%E7%A7%81%E5%AF%86%E8%BF%9E%E6%8E%A5neterr_cert_invalid%E4%B9%8B%E7%B1%BB%E7%9A%84%E6%80%8E%E4%B9%88%E5%8A%9E%E8%AF%81%E4%B9%A6%E5%AF%BC%E5%85%A5%E9%94%99%E8%AF%AF%E6%80%8E%E4%B9%88%E5%8A%9E%E5%A6%82%E4%BD%95%E5%8D%B8%E8%BD%BD%E8%AF%81%E4%B9%A6) (The root certificate can be obtained via `http://localhost:7654/CERT/root.crt`). 31 | 32 | *You can use, for example, [pyenv](https://github.com/pyenv/pyenv) to install the required version of Python (Python 3.11+ is recommended). 33 | 34 | ## Configuration 35 | After launching Accesser once, the following files and directories will be created in the **working directory**: 36 | 37 | * `config.toml`: Basic settings 38 | * `rules.toml`: Advanced rules. It will be automatically updated if unmodified. (delete it to restore auto-updates) 39 | * `rules/` directory: Place your custom advanced rules here 40 | 41 | See the inline comments for details; after saving your edits, restart the application. You can also refer to the [`custom.toml.sample`](accesser/custom.toml.sample) for examples of how to configure advanced rules. 42 | 43 | You may additionally place PAC files in the **working directory** to define specific routing rules (the default PAC is available here: [https://github.com/URenko/Accesser/blob/master/accesser/pac](https://github.com/URenko/Accesser/blob/master/accesser/pac)). 44 | 45 | 46 | ## Advanced Usage 1: Use with other proxy software such as v2ray 47 | Accesser is a local HTTP proxy with a default proxy address of `http://localhost:7654`, which can be used in combination with other proxy software as long as the network traffic can be exported as HTTP proxy. 48 | 49 | Take [v2ray](https://github.com/v2fly/v2ray-core) as an example, you can add an HTTP outbound pointing to `http://localhost:7654` and set the corresponding routing rules to send traffic from sites like Wikipedia, Pixiv, etc. to this outbound. 50 | And then run Accesser with the argument `--notsetproxy` to prevent Accesser from setting the system proxy. 51 | 52 | In addition, you can set up a DNS outbound and then edit `config.toml` to allow Accesser to use this DNS. 53 | 54 | ## Advanced Usage 2: Add sites 55 | Edit the pac file in the working directory (if it is a Windows executable program, you can download this file from GitHub to the working directory), so that the websites to be supported can pass through the proxy. 56 | 57 | However, not all sites will work straight away and may require some adjustment, see [How to adapt sites](https://github.com/URenko/Accesser/wiki/如何适配站点). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Accesser 2 | [English version](README.en.md) 3 | 4 | 一个解决SNI RST导致维基百科、Pixiv等站点无法访问的工具 5 | [支持的站点](https://github.com/URenko/Accesser/wiki/目前支持的站点) 6 | 7 | [![](https://img.shields.io/github/release/URenko/Accesser.svg)](https://github.com/URenko/Accesser/releases/latest) 8 | [![](https://img.shields.io/pypi/v/accesser)](https://pypi.org/project/accesser/) 9 | [![](https://img.shields.io/github/downloads/URenko/Accesser/total.svg)](https://github.com/URenko/Accesser/releases/latest) 10 | [![](https://img.shields.io/github/license/URenko/Accesser.svg)](https://github.com/URenko/Accesser/blob/master/LICENSE) 11 | 12 | ## 使用 13 | ### 如果不知道什么是Python 14 | 从[这里](https://github.com/URenko/Accesser/releases/download/v0.11.0/accesser.exe)下载Windows一键程序,运行既可(建议关闭其他代理软件),首次使用会要求安装证书,选是即可。 15 | ### 如果已经安装了Python 3.10*或更高版本 16 | ``` 17 | pip3 install -U "accesser[doh,doq]" 18 | ``` 19 | 如果你不需要 DNS-over-HTTPS 和 DNS-over-QUIC,则可以不用带`[doh,doq]`。 20 | 21 | 然后通过如下命令启动: 22 | ``` 23 | accesser 24 | ``` 25 | 对于Windows系统,默认情况下(没有指定`--notsetproxy`)会设置PAC代理为`http://localhost:7654/pac/?t=<随机数>`,如果没有可以手动设置。 26 | 27 | 此外,对于Windows系统,默认情况下(没有指定`--notimportca`)会自动导入证书至系统,如果没有可以手动导入,请看[这里](https://github.com/URenko/Accesser/wiki/FAQ#q-windows%E8%AE%BF%E9%97%AE%E7%9B%B8%E5%85%B3%E7%BD%91%E7%AB%99%E5%87%BA%E7%8E%B0%E8%AF%81%E4%B9%A6%E9%94%99%E8%AF%AF%E6%82%A8%E7%9A%84%E8%BF%9E%E6%8E%A5%E4%B8%8D%E6%98%AF%E7%A7%81%E5%AF%86%E8%BF%9E%E6%8E%A5neterr_cert_invalid%E4%B9%8B%E7%B1%BB%E7%9A%84%E6%80%8E%E4%B9%88%E5%8A%9E%E8%AF%81%E4%B9%A6%E5%AF%BC%E5%85%A5%E9%94%99%E8%AF%AF%E6%80%8E%E4%B9%88%E5%8A%9E%E5%A6%82%E4%BD%95%E5%8D%B8%E8%BD%BD%E8%AF%81%E4%B9%A6)(根证书可从`http://localhost:7654/CERT/root.crt`获取)。 28 | 29 | *可以使用例如[pyenv](https://github.com/pyenv/pyenv)来安装所需的Python版本(推荐Python 3.11+)。 30 | 31 | ## 设置 32 | 启动一次Accesser后,会在 **工作目录** 下生成如下文件和目录: 33 | 34 | - `config.toml`:一些基础设置 35 | - `rules.toml`: 进阶规则,在不曾被修改过的情况下会自动更新(删除它可恢复自动更新) 36 | - `rules`目录: 可存放自定义进阶规则 37 | 38 | 具体含义见其中注释,保存后重新打开程序。 39 | 进阶规则的配置方式也可参见 [`custom.toml.sample`](accesser/custom.toml.sample)。 40 | 41 | **工作目录** 下也可放置 pac 文件制定具体的路由规则(默认 pac 见 https://github.com/URenko/Accesser/blob/master/accesser/pac )。 42 | 43 | ## 进阶1: 与v2ray等其他代理软件一起使用 44 | Accesser是一个本地HTTP代理,默认代理地址为`http://localhost:7654`,只要网络流量能从其他代理软件以HTTP代理导出就能联合使用。 45 | 46 | 以[v2ray](https://github.com/v2fly/v2ray-core)为例,可以添加一个HTTP的outbound指向`http://localhost:7654`,并设置相应的路由规则,将维基百科、Pixiv等站点的流量送到这个outbound。 47 | 并在启动 Accesser 时带上 `--notsetproxy` 参数以避免 Accesser 设置系统代理。 48 | 49 | 此外,你还可以设置一个DNS outbound,然后编辑`config.toml`让Accesser使用这一DNS。 50 | 51 | ## 进阶2: 增加支持的网站 52 | 编辑工作目录下的pac文件(如果是一键程序,可以从GitHub下载这一文件到工作目录),使要支持的网站从代理过。 53 | 54 | 然而,并不是所有站点都可以直接工作,可能需要一些调节,见[如何适配站点](https://github.com/URenko/Accesser/wiki/如何适配站点)。 55 | 56 | --- 57 | 58 |
59 | 60 | 时间线与后记 61 | 62 | 18年夏,通过修改 hosts 以连接被 GFW 屏蔽的维基百科、pixiv 等网站的方法突然失效。很快人们就[反应过来](https://github.com/googlehosts/hosts/issues/87)问题的所在:SNI RST。 63 | 在这之前,修改 hosts 是一个几近于零成本的翻墙方法。突然的变化意味着翻墙成本的急剧上升。 64 | 65 | 为了重置平衡,同时抱着对更早时期红杏计划的敬佩,我翻阅了关于 TLS 的 RFC 文档,并注意到其中关于 SNI RST 涉及的 `server_name` 并非 "must",而是可选扩展。 66 | 经过[简单测试](https://github.com/URenko/Access_demo),确认这一思路确实可行。 67 | 秉着重置平衡的想法,我制作了 Accesser,并配备了 web UI (现已移除),目的就是让一般人访问维基百科、pixiv 等网站的难度降低到 hosts 时代的水平。 68 | 尽管我仅在一个极小众论坛(现已关闭)上自荐过,一段时间后,Accesser 甚至成了中文维基社群推荐的方法。 69 | 70 | 在这之后,利用相同思路的翻墙软件/方法如春笋般涌现。不过稍微遗憾的是,他们中的许多没有做和远程服务器之间的证书校验,使得用户暴露在可能的危险中。 71 | 再往后,一些更加投机取巧,利用非标准协议的方法也有出现。 72 | 73 | 19年后,因日渐繁忙,加之坚信这一如此简单的思路很快就会失效,故停更。 74 | 75 | 22年末,契机是 Python 的协程接口日渐稳定,并出现[需要的功能](https://docs.python.org/zh-cn/3/whatsnew/3.11.html#asyncio),我将 Accesser 的核心重写并在各位贡献者的协助下陆续更新。 76 | 77 | Accesser 的大版本号是留予新的技术,然而出乎我的预料,现有的域前置技术在六年后仍未失效。 78 | 而另一方面,看起来天朝人民有足够的能力以维持平衡,因此 1.x 可能永远不会到来。 79 |
80 | -------------------------------------------------------------------------------- /accesser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # This file is for backward compatibility only. 4 | 5 | from accesser import run 6 | 7 | if __name__ == '__main__': 8 | run() -------------------------------------------------------------------------------- /accesser.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | import os, tld, importlib, importlib.metadata 3 | from packaging.requirements import Requirement 4 | from PyInstaller.utils.hooks import copy_metadata 5 | 6 | block_cipher = None 7 | 8 | datas=[ 9 | ('accesser/config.toml', 'accesser'), 10 | ('accesser/rules.toml', 'accesser'), 11 | ('accesser/pac', 'accesser'), 12 | (os.path.dirname(tld.__file__)+'/res/effective_tld_names.dat.txt', 'tld/res'), 13 | ] 14 | 15 | for req in importlib.metadata.requires('dnspython'): 16 | package_name = Requirement(req).name 17 | if importlib.util.find_spec(package_name) is not None: 18 | datas += copy_metadata(package_name, recursive=True) 19 | 20 | a = Analysis(['accesser/__main__.py'], 21 | pathex=['./'], 22 | binaries=[], 23 | datas=datas, 24 | hiddenimports=[], 25 | hookspath=[], 26 | runtime_hooks=[], 27 | excludes=[], 28 | win_no_prefer_redirects=False, 29 | win_private_assemblies=False, 30 | cipher=block_cipher, 31 | noarchive=False) 32 | pyz = PYZ(a.pure, a.zipped_data, 33 | cipher=block_cipher) 34 | exe = EXE(pyz, 35 | a.scripts, 36 | a.binaries, 37 | a.zipfiles, 38 | a.datas, 39 | [], 40 | name='accesser', 41 | debug=False, 42 | bootloader_ignore_signals=False, 43 | strip=False, 44 | upx=True, 45 | runtime_tmpdir=None, 46 | console=True ) 47 | -------------------------------------------------------------------------------- /accesser/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Accesser 4 | # Copyright (C) 2018 URenko 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | __version__ = '0.11.0' 20 | 21 | import os, sys 22 | import json 23 | import fnmatch 24 | import random 25 | import ssl 26 | import asyncio 27 | import traceback 28 | from contextlib import closing 29 | from urllib import request 30 | from urllib.parse import urlsplit 31 | from packaging.version import Version 32 | from tld import get_tld, is_tld 33 | import dns, dns.asyncresolver, dns.nameserver 34 | 35 | from .utils import certmanager as cm 36 | from .utils import importca 37 | from .utils import setting 38 | from .utils.setting import basepath 39 | from .utils.log import logger 40 | from .utils.cert_verify import match_hostname 41 | from .utils import sysproxy 42 | 43 | 44 | async def update_cert(server_name): 45 | global context, cert_store, cert_lock 46 | if not is_tld(server_name): 47 | res = get_tld(server_name, as_object=True, fix_protocol=True) 48 | if res.subdomain: 49 | server_name = res.subdomain.split('.', 1)[-1] + '.' + res.domain + '.' + res.tld 50 | else: 51 | server_name = res.domain + '.' + res.tld 52 | async with cert_lock: 53 | if not server_name in cert_store: 54 | cm.create_certificate(server_name) 55 | context.load_cert_chain(os.path.join(cm.certpath, "{}.crt".format(server_name))) 56 | cert_store.add(server_name) 57 | 58 | async def send_pac(writer: asyncio.StreamWriter): 59 | with open('pac' if os.path.exists('pac') else os.path.join(basepath, 'pac'), 'rb') as f: 60 | pac = f.read().replace(b'{{port}}', str(setting.config['server']['port']).encode('iso-8859-1')).replace(b'{{host}}', setting.config['server'].get('pac_host', '127.0.0.1').encode('iso-8859-1')) 61 | writer.write(f'HTTP/1.1 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: {len(pac)}\r\n\r\n'.encode('iso-8859-1')) 62 | writer.write(pac) 63 | await writer.drain() 64 | writer.close() 65 | await writer.wait_closed() 66 | 67 | async def send_crt(writer: asyncio.StreamWriter, path: str): 68 | with open(os.path.join(basepath, path.lstrip('/')), 'rb') as f: 69 | crt = f.read() 70 | writer.write(f'HTTP/1.1 200 OK\r\nContent-Type: application/x-x509-ca-cert\r\nContent-Length: {len(crt)}\r\n\r\n'.encode('iso-8859-1')) 71 | writer.write(crt) 72 | await writer.drain() 73 | writer.close() 74 | await writer.wait_closed() 75 | 76 | async def http_redirect(writer: asyncio.StreamWriter, path: str): 77 | path = path.removeprefix('http://') 78 | for key in setting.config['http_redirect']: 79 | if path.startswith(key): 80 | path = setting.config['http_redirect'][key] + path[len(key):] 81 | break 82 | logger.debug('Redirect to '+path) 83 | writer.write(f'HTTP/1.1 301 Moved Permanently\r\nLocation: https://{path}\r\n\r\n'.encode('iso-8859-1')) 84 | await writer.drain() 85 | writer.close() 86 | await writer.wait_closed() 87 | 88 | async def forward_stream(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): 89 | while True: 90 | data = await reader.read(32768) 91 | if data == b'': 92 | return 93 | writer.write(data) 94 | await writer.drain() 95 | 96 | async def handle(reader, writer): 97 | global context 98 | with closing(writer): 99 | raw_request = await reader.readuntil(b'\r\n\r\n') 100 | requestline = raw_request.decode('iso-8859-1').splitlines()[0] 101 | i_addr, i_port, *_ = writer.get_extra_info('peername') 102 | logger.debug(f"{i_addr}:{i_port} say: {requestline}") 103 | words = requestline.split() 104 | command, path = words[:2] 105 | match command: 106 | case 'CONNECT': 107 | host, port = path.split(':') 108 | remote_ip = await DNSquery(host) 109 | logger.debug(f'[{i_port:5}] DNS: {host} -> {remote_ip}') 110 | case 'GET': 111 | if path.startswith('/pac/'): 112 | return await send_pac(writer) 113 | elif path.startswith('/CERT/root.'): 114 | return await send_crt(writer, path) 115 | elif path == '/shutdown': 116 | sys.exit() 117 | else: 118 | return await http_redirect(writer, path) 119 | case _: 120 | return await http_redirect(writer, path) 121 | writer.write(b'HTTP/1.1 200 Connection Established\r\n\r\n') 122 | 123 | await update_cert(host) 124 | if sys.version_info[1] >= 11: 125 | await writer.start_tls(context) 126 | else: 127 | writer._transport = await writer._loop.start_tls(writer.transport, writer._protocol, context, server_side=True) 128 | server_hostname_key = next(filter(lambda h:fnmatch.fnmatchcase(host, h), setting.config['alter_hostname']), None) 129 | server_hostname = '' if server_hostname_key is None else setting.config['alter_hostname'][server_hostname_key] 130 | logger.debug(f'[{i_port:5}] {server_hostname=}') 131 | remote_context = ssl.create_default_context() 132 | remote_context.check_hostname = False 133 | remote_reader, remote_writer = await asyncio.open_connection(remote_ip, port, ssl=remote_context, server_hostname=server_hostname) 134 | cert = remote_writer.get_extra_info('peercert') 135 | cert_message = f"subjectAltName: {cert.get('subjectAltName', ())}, subject: {cert.get('subject', ())}" 136 | logger.debug(f"[{i_port:5}] {cert_message}.") 137 | cert_verify_key = next(filter(lambda h:fnmatch.fnmatchcase(host, h), setting.config.get('cert_verify', ())), None) 138 | if cert_verify_key is not None: 139 | cert_verify_list = setting.config['cert_verify'][cert_verify_key] 140 | cert_policy = False if cert_verify_list is False else True 141 | elif server_hostname_key is not None: 142 | cert_verify_list = [setting.config['alter_hostname'][server_hostname_key]] 143 | cert_policy = setting.config['check_hostname'] 144 | else: 145 | cert_verify_list = [host] 146 | cert_policy = setting.config['check_hostname'] 147 | if cert_policy is not False and not any(match_hostname(cert, h, cert_policy) for h in cert_verify_list): 148 | logger.warning(f"[{i_port:5}] {cert_verify_list} don't match either of {cert_message}.") 149 | return 150 | await asyncio.gather( 151 | forward_stream(reader, remote_writer), 152 | forward_stream(remote_reader, writer) 153 | ) 154 | writer.close() 155 | remote_writer.close() 156 | await remote_writer.wait_closed() 157 | await writer.wait_closed() 158 | 159 | async def proxy(): 160 | server = await asyncio.start_server(handle, setting.config['server']['address'], setting.config['server']['port']) 161 | 162 | print(f"Serving on {', '.join(str(sock.getsockname()) for sock in server.sockets)}") 163 | sysproxy.set_pac('http://localhost:'+str(setting.config['server']['port'])+'/pac/?t='+str(random.randrange(2**16))) 164 | 165 | try: 166 | async with server: 167 | await server.serve_forever() 168 | finally: 169 | sysproxy.set_pac(None) 170 | 171 | async def DNSquery(domain, hosts_only=False): 172 | global DNSresolver 173 | try: 174 | return next(v for k,v in setting.config['hosts'].items() if k==domain or (k.startswith('.') and domain.endswith(k))) 175 | except StopIteration: 176 | if hosts_only: 177 | return 178 | if setting.config['ipv6']: 179 | try: 180 | ret = await DNSresolver.resolve(domain, 'AAAA') 181 | except dns.asyncresolver.NoAnswer: 182 | ret = await DNSresolver.resolve(domain, 'A') 183 | else: 184 | ret = await DNSresolver.resolve(domain, 'A') 185 | return ret[0].to_text() 186 | 187 | def update_checker(): 188 | for pypi_url in ['https://pypi.org/pypi/accesser/json', 'https://mirrors.cloud.tencent.com/pypi/json/accesser']: 189 | try: 190 | with request.urlopen(pypi_url) as f: 191 | v2 = Version(json.load(f)["info"]["version"]) 192 | break 193 | except Exception: 194 | logger.warning(traceback.format_exc()) 195 | else: 196 | with request.urlopen('https://github.com/URenko/Accesser/releases/latest') as f: 197 | v2 = Version(f.geturl().rsplit('/', maxsplit=1)[-1]) 198 | v1 = Version(__version__) 199 | if v2 > v1: 200 | logger.warning("There is a new version, you can update with 'python3 -m pip install -U accesser' or download from GitHub") 201 | 202 | async def main(): 203 | global context, cert_store, cert_lock, DNSresolver 204 | print(f"Accesser v{__version__} Copyright (C) 2018-2024 URenko") 205 | setting.parse_args() 206 | 207 | if setting.rules_update_case in ('old', 'missing'): 208 | logger.warning("Updated rules.toml because it is %s.", setting.rules_update_case) 209 | elif setting.rules_update_case == 'modified': 210 | logger.warning("You've already modified rules.toml, so it won't be updated automatically!") 211 | else: 212 | logger.debug("rules.toml status: %s", setting.rules_update_case) 213 | 214 | if any(_keys in setting._config for _keys in setting._rules): 215 | logger.warning("Some sections of config.toml overlap with rules.toml, config.toml has higher priority, but this may make rule updates ineffective.") 216 | 217 | DNSresolver = dns.asyncresolver.Resolver(configure=False) 218 | DNSresolver.cache = dns.resolver.LRUCache() 219 | for nameserver in setting.config['DNS']['nameserver']: 220 | if (_url := urlsplit(nameserver)).netloc == '': 221 | _url = urlsplit('//' + nameserver) 222 | address = await DNSquery(_url.hostname, hosts_only=True) 223 | if _url.scheme == '': 224 | DNSresolver.nameservers.append(dns.nameserver.Do53Nameserver(_url.hostname if address is None else address, 53 if _url.port is None else _url.port)) 225 | elif _url.scheme == 'https': 226 | DNSresolver.nameservers.append(dns.nameserver.DoHNameserver(nameserver, bootstrap_address=address)) 227 | elif _url.scheme == 'tls': 228 | DNSresolver.nameservers.append(dns.nameserver.DoTNameserver(_url.hostname if address is None else address, 853 if _url.port is None else _url.port, hostname=_url.hostname)) 229 | elif _url.scheme == 'quic': 230 | DNSresolver.nameservers.append(dns.nameserver.DoQNameserver(_url.hostname if address is None else address, 853 if _url.port is None else _url.port, server_hostname=_url.hostname)) 231 | 232 | importca.import_ca() 233 | 234 | context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 235 | cert_store = set() 236 | cert_lock = asyncio.Lock() 237 | 238 | await asyncio.gather( 239 | asyncio.to_thread(update_checker), 240 | proxy() 241 | ) 242 | 243 | def run(): 244 | asyncio.run(main()) 245 | -------------------------------------------------------------------------------- /accesser/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from accesser import run 5 | 6 | if __name__ == '__main__': 7 | run() -------------------------------------------------------------------------------- /accesser/config.toml: -------------------------------------------------------------------------------- 1 | # 这是Accesser的配置文件,保存到程序 ⚠工作目录⚠ 后重启程序生效。 2 | # This is the configuration file of Accesser, save it to the program ⚠ working directory ⚠ and restart the program to take effect. 3 | 4 | # 是否校验证书域名?false 不进行校验,true 进行宽松的校验(如a.example.com能匹配b.example.com),"strict" 进行标准的校验。 5 | # Whether to verify the certificate domains? Set to false for no verification, set to true for loose verification (e.g. a.example.com matches b.example.com), set to "strict" for standard verification. 6 | check_hostname = true 7 | 8 | # 是否自动设置系统的代理(目前只对Windows有效)。这可使用命令行参数 --notsetproxy 来覆盖。 9 | # Whether to set the system proxy automatically (currently only valid for Windows). This can be overridden with the command line argument --notsetproxy. 10 | setproxy = true 11 | 12 | # 是否自动导入并信任根证书(目前只对Windows有效)。这可使用命令行参数 --notimportca 来覆盖。 13 | # Whether to automatically import and trust the root certificate (currently only available for Windows). This can be overridden with the command line argument --notimportca. 14 | importca = true 15 | 16 | # 是否开启IPv6支持 17 | # Whether to enable IPv6 support 18 | ipv6 = false 19 | 20 | 21 | [log] 22 | 23 | # 日志级别: 可为"CRITICAL"、"ERROR"、"WARNING"、"INFO"、"DEBUG"、"NOTSET",越后面的输出信息越多,参考Python的logging模块说明。 24 | # Logging level: can be "CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET", the later the more output information, refer to Python's logging module manual. 25 | loglevel = "DEBUG" 26 | 27 | # 日志文件路径,"" 表示输出至控制台(如果存在)而不是文件。 28 | # Log file path, "" indicates output to the console (if present) instead of a file. 29 | logfile = "" 30 | 31 | 32 | [server] 33 | 34 | # 服务器绑定的地址。设为 "0.0.0.0" 可以允许同一局域网的设备连接该程序,比如用手机连接电脑的WiFi,设置PAC后既可允许手机使用。可能会有防火墙的提示,要允许访问。 35 | # The address to which the server is bound. Set to "0.0.0.0" to allow devices on the same LAN to connect to the program, such as using your phone to connect to your computer's WiFi, after setting the PAC to allow both your phone to use it. There may be a firewall prompt to allow access. 36 | address = "127.0.0.1" 37 | 38 | # 服务器的端口号,如果与其他程序发生端口冲突时可以更改,其值应为1-65535,建议>1024。 39 | # The port number of the server, which can be changed in case of port conflicts with other programs, should have a value of 1-65535, with >1024 recommended. 40 | port = 7654 41 | 42 | # PAC文件中的代理主机。如供局域网使用,应设为安装了Accesser的设备在局域网中的IP。 43 | # The proxy host in the PAC file. If for LAN usage, it should be set to the IP of the device on the LAN where Accesser is installed. 44 | pac_host = "127.0.0.1" 45 | 46 | 47 | -------------------------------------------------------------------------------- /accesser/custom.toml.sample: -------------------------------------------------------------------------------- 1 | # 这是Accesser的规则(除路由规则)文件。 2 | # This is the rule (except routing rules) file of Accesser. 3 | # 将 toml 格式的规则文件放置在工作目录下的 rules 目录可向 Accesser 添加规则。规则优先级为 `config.toml` > `rules/*.toml` > 工作目录下的 `rules.toml` 4 | # You can add rules to the Accesser by placing a toml-formatted rules file in the rules directory under the working directory. Rules with priority of 'config.toml' > 'rules/*.toml' > 'rules.toml' in the working directory 5 | 6 | [DNS] 7 | 8 | # DNS服务器地址。可于下方 hosts 字段指定DNS服务器 host 对应的 IP 地址。 9 | # DNS server address. You can specify bootstrap IP address in the [hosts] field below. 10 | nameserver = [ 11 | #"https://77.88.8.8/dns-query", # https://host|IP[:port]/path # DNS-over-HTTPS (DoH) 12 | #"tls://149.112.112.112", # tls://host|IP[:port] # DNS-overTLS (DoT) 13 | # "quic://dns.adguard-dns.com", # quic://host|IP[:port] # DNS-over-QUIC (DoQ) 14 | # "localhost" # host|IP[:port] # 传统 UDP DNS | traditional UDP DNS 15 | ] 16 | 17 | 18 | [http_redirect] 19 | 20 | # 如果一个HTTP(无TLS)请求的URL以下面某个键开头,则会被重定向到其值对应的URL(通过HTTPS请求)。 21 | # If the URL of an HTTP (no TLS) request starts with one of the following keys, it will be redirected to the URL corresponding to its value (via HTTPS request). 22 | 23 | # "example.com/" = "www.example.com/" 24 | 25 | [alter_hostname] 26 | 27 | # 与键对应的域名的TLS连接会使用其值对应的域名作为server_name字段,并且校验证书时也使用这一域名。键支持Unix shell风格的通配符。 28 | # A TLS connection to the domain corresponding to the key will use the domain name corresponding to its value as the server_name field, and this domain name is also used when verifying the certificate. The key supports Unix shell-style wildcards. 29 | 30 | # "example.com" = "notblocked.com" 31 | 32 | [cert_verify] 33 | 34 | # 为域名分别设置证书校验策略,其值可以是一个包含用于校验的域名的列表(有一个匹配就通过),也可以是 false 表示不校验 35 | # 这比 [alter_hostname] 和全局的 check_hostname 的优先级高,但不会在 Client Hello 中作为 server_name 发送。 36 | # Set the certificate validation policy for domains individually. The values can be a array contain strings which represent the domain name used to verify the certificate (pass if there is a match), or false which means disabling the verification. 37 | # It has as a higher priority than [alter_hostname] and the global check_hostname, but will not be sent as server_name in Client Hello. 38 | 39 | # "example.com" = ["example.org", "example.net", "example.xyz"] 40 | 41 | [hosts] 42 | 43 | # 自定义 域名-IP 映射,即用于与网站建立连接,也用于与DNS服务器建立连接。 44 | # Customize domain-IP mapping, which is used to establish a connection with the website and the DNS server. 45 | 46 | # example for DNS server bootstrap address 47 | # "dot.sb" = "185.222.222.222" 48 | # "dns.adguard-dns.com" = "94.140.14.14" 49 | -------------------------------------------------------------------------------- /accesser/pac: -------------------------------------------------------------------------------- 1 | var domains = { 2 | "apkmirror.com": 1, 3 | "appledaily.com": 1, 4 | "artstation.com": 1, 5 | "bbc.com": 1, 6 | "disqus.com": 1, 7 | "dropbox.com": 1, 8 | "dropboxapi.com": 1, 9 | "dropbox-dns.com": 1, 10 | "dw.com": 1, 11 | "e-hentai.org": 1, 12 | "epochtimes.com": 1, 13 | "euronews.com": 1, 14 | "exhentai.org": 1, 15 | "github.com": 1, 16 | "greasyfork.org": 1, 17 | "imgur.com": 1, 18 | "instagram.com": 1, 19 | "kobo.com": 1, 20 | "mega.io": 1, 21 | "mega.nz": 1, 22 | "nicovideo.jp": 1, 23 | "nyaa.si": 1, 24 | "nytimes.com": 1, 25 | "nyt.com": 1, 26 | "phncdn.com": 1, 27 | "pinterest.com": 1, 28 | "pixiv.net": 1, 29 | "fanbox.cc": 1, 30 | "quora.com": 1, 31 | "redd.it": 1, 32 | "reddit.com": 1, 33 | "redditmedia.com": 1, 34 | "startpage.com": 1, 35 | "steamcommunity.com": 1, 36 | "thetvdb.com": 1, 37 | "uptodown.com": 1, 38 | "vimeo.com": 1, 39 | "wenxuecity.com": 1, 40 | "wikipedia.org": 1, 41 | "wikimedia.org": 1, 42 | "mediawiki.org": 1, 43 | "wikiquote.org": 1, 44 | "wikinews.org": 1, 45 | "wikiversity.org": 1, 46 | "wiktionary.org": 1, 47 | "wikibooks.org": 1, 48 | "wikivoyage.org": 1, 49 | "wikisource.org": 1, 50 | "wikidata.org": 1, 51 | "singlelogin.re": 1, 52 | "1lib.sk": 1, 53 | "archive.org": 1, 54 | "amazon.co.jp": 1, 55 | "discord.com": 1, 56 | "discordapp.com": 1, 57 | "discord.gg": 1, 58 | "duckduckgo.com": 1, 59 | "v2ex.com": 1, 60 | "twitch.tv": 1, 61 | "scratch.mit.edu": 1, 62 | "bandcamp.com": 1, 63 | "mastodon.social": 1, 64 | "onedrive.live.com": 1, 65 | "deviantart.com": 1, 66 | "wixmp.com": 1, 67 | "deviantart.net": 1 68 | }; 69 | 70 | var shexps = { 71 | "*://*.bbc.co.uk/*": 1, 72 | "*://*.bbci.co.uk/*": 1, 73 | "*://*.japantimes.co.jp/*": 1, 74 | "*://search.yahoo.co.jp/*": 1, 75 | "*://*.cna.com.tw/*": 1, 76 | "*://media.discordapp.net/*": 1, 77 | "*://i.pximg.net/*": 1, 78 | "*://*.pixivsketch.net/*": 1, 79 | "*://*.githubassets.com/*": 1, 80 | "*://*.githubusercontent.com/*": 1, 81 | "*://*.redditstatic.com/*": 1 82 | }; 83 | 84 | var proxy = "PROXY {{host}}:{{port}};"; 85 | 86 | var direct = 'DIRECT;'; 87 | 88 | var hasOwnProperty = Object.hasOwnProperty; 89 | 90 | function shExpMatchs(str, shexps) { 91 | for (shexp in shexps) { 92 | if (shExpMatch(str, shexp)) { 93 | return true; 94 | } 95 | } 96 | return false; 97 | } 98 | 99 | function FindProxyForURL(url, host) { 100 | var suffix; 101 | var pos = host.lastIndexOf('.'); 102 | pos = host.lastIndexOf('.', pos - 1); 103 | while(1) { 104 | if (pos <= 0) { 105 | if (hasOwnProperty.call(domains, host)) { 106 | return proxy; 107 | } else if (shExpMatchs(url, shexps)) { 108 | return proxy; 109 | } else { 110 | return direct; 111 | } 112 | } 113 | suffix = host.substring(pos + 1); 114 | if (hasOwnProperty.call(domains, suffix)) { 115 | return proxy; 116 | } 117 | pos = host.lastIndexOf('.', pos - 1); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /accesser/rules.toml: -------------------------------------------------------------------------------- 1 | # 这是Accesser的规则(除路由规则)文件。 2 | # This is the rule (except routing rules) file of Accesser. 3 | # 该文件在不曾被修改过的情况下会自动更新。因而不建议一般用户直接修改。 4 | # This file will be automatically updated if it hasn’t been modified. Therefore, ordinary users are not advised to modify it directly. 5 | # 你也可以通过将配置文件复制到工作目录下的 rules 文件夹中以达到向 Accesser 添加规则的目的。 6 | # You can also copy the rules configuration file to the rules directory under working directory to add rules to Accesser. 7 | 8 | [DNS] 9 | 10 | # DNS服务器地址。可于下方 hosts 字段指定DNS服务器 host 对应的 IP 地址。 11 | # DNS server address. You can specify bootstrap IP address in the [hosts] field below. 12 | nameserver = [ 13 | "https://77.88.8.8/dns-query", # https://host|IP[:port]/path # DNS-over-HTTPS (DoH) 14 | "https://tiarap.org/odoh", 15 | "https://185.222.222.222/dns-query", 16 | "https://45.11.45.11/dns-query", 17 | "https://149.112.112.112/dns-query", 18 | "https://149.112.112.10/dns-query", 19 | "tls://149.112.112.112", # tls://host|IP[:port] # DNS-overTLS (DoT) 20 | "tls://149.112.112.10", 21 | "tls://dot.sb", 22 | # "quic://dns.adguard-dns.com", # quic://host|IP[:port] # DNS-over-QUIC (DoQ) 23 | # "localhost" # host|IP[:port] # 传统 UDP DNS | traditional UDP DNS 24 | ] 25 | 26 | 27 | [http_redirect] 28 | 29 | # 如果一个HTTP(无TLS)请求的URL以下面某个键开头,则会被重定向到其值对应的URL(通过HTTPS请求)。 30 | # If the URL of an HTTP (no TLS) request starts with one of the following keys, it will be redirected to the URL corresponding to its value (via HTTPS request). 31 | 32 | "pixiv.net/" = "www.pixiv.net/" 33 | "www.google.com/recaptcha/" = "www.recaptcha.net/recaptcha/" 34 | "instagram.com/" = "www.instagram.com/" 35 | "nicovideo.jp/" = "www.nicovideo.jp/" 36 | "twitch.tv/" = "www.twitch.tv/" 37 | 38 | 39 | [alter_hostname] 40 | 41 | # 与键对应的域名的TLS连接会使用其值对应的域名作为server_name字段,并且校验证书时也使用这一域名。键支持Unix shell风格的通配符。 42 | # A TLS connection to the domain corresponding to the key will use the domain name corresponding to its value as the server_name field, and this domain name is also used when verifying the certificate. The key supports Unix shell-style wildcards. 43 | 44 | "www.quora.com" = "fs.quoracdn.net" 45 | "nyaa.si" = "ddos-guard.net" 46 | "steamcommunity.com" = "www.valvesoftware.com" 47 | "gn-web-assets.api.bbc.com" = "static-web-assets.gnl-common.bbcverticals.com" 48 | 49 | 50 | [cert_verify] 51 | 52 | # 为域名分别设置证书校验策略,其值可以是一个包含用于校验的域名的列表(有一个匹配就通过),也可以是 false 表示不校验 53 | # 这比 [alter_hostname] 和全局的 check_hostname 的优先级高,但不会在 Client Hello 中作为 server_name 发送。 54 | # Set the certificate validation policy for domains individually. The values can be a array contain strings which represent the domain name used to verify the certificate (pass if there is a match), or false which means disabling the verification. 55 | # It has as a higher priority than [alter_hostname] and the global check_hostname, but will not be sent as server_name in Client Hello. 56 | 57 | "1lib.sk" = ["1lib.pm", "1lib.sk", "singlelogin.re"] 58 | "*.1lib.sk" = ["1lib.pm", "1lib.sk", "singlelogin.re"] 59 | "singlelogin.re" = ["1lib.pm", "1lib.sk", "singlelogin.re"] 60 | "*.singlelogin.re" = ["1lib.pm", "1lib.sk", "singlelogin.re"] 61 | "scratch.mit.edu" = ["d.sni-645-default.ssl.fastly.net"] 62 | "*.scratch.mit.edu" = ["d.sni-645-default.ssl.fastly.net"] 63 | "mega.io" = ["static.mega.co.nz"] 64 | "*.nytimes.com" = ["fastly.com", "cloudfront.net"] 65 | "*.twitch.tv" = ["twitch.tv", "cloudfront.net","twitch.a2z.com", "fastly.com", "visioncritical.com", "imgix.net", "discourse.org", "bit.ly"] 66 | "nicovideo.jp" = ["cloudfront.net"] 67 | "*.nicovideo.jp" = ["cloudfront.net", "nicovideo.jp"] 68 | "onedrive.live.com" = ["azureedge.net"] 69 | "*.github.com" = ["github.com", "githubassets.com", "githubusercontent.com"] 70 | "*.pixiv.net" = ["pixiv.net", "firebaseapp.com", "cloudfront.net", "tumblr.com"] 71 | "deviantart.com" = ["cloudfront.net"] 72 | "*.deviantart.com" = ["cloudfront.net"] 73 | "*.deviantart.net" = ["cloudfront.net"] 74 | "*.wixmp.com" = ["cloudfront.net"] 75 | 76 | 77 | [hosts] 78 | 79 | # 自定义 域名-IP 映射,即用于与网站建立连接,也用于与DNS服务器建立连接。 80 | # Customize domain-IP mapping, which is used to establish a connection with the website and the DNS server. 81 | 82 | # example for DNS server bootstrap address 83 | "dot.sb" = "185.222.222.222" 84 | # "dns.adguard-dns.com" = "94.140.14.14" 85 | 86 | "pixiv.net" = "pixiv.me" 87 | "www.pixiv.net" = "pixiv.me" 88 | "sketch.pixiv.net" = "pixiv.me" 89 | "accounts.pixiv.net" = "pixiv.me" 90 | "imp.pixiv.net" = "pixiv.me" 91 | "oauth.secure.pixiv.net" = "pixiv.me" 92 | "factory.pixiv.net" = "pixiv.me" 93 | "embed.pixiv.net" = "pixiv.me" 94 | "engineering.pixiv.net" = "pixiv.me" 95 | "app-api.pixiv.net" = "pixiv.me" 96 | "sensei.pixiv.net" = "pixiv.me" 97 | "goods.pixiv.net" = "pixiv.me" 98 | "link.pixiv.net" = "pixiv.me" 99 | "dic.pixiv.net" = "pixiv.me" 100 | "en-dic.pixiv.net" = "pixiv.me" 101 | "market.pixiv.net" = "pixiv.me" 102 | "comic.pixiv.net" = "210.140.131.153" 103 | "source.pixiv.net" = "210.140.131.153" 104 | "i.pximg.net" = "pximg.net" 105 | "fanbox.cc" = "pixiv.me" 106 | ".fanbox.cc" = "pixiv.me" 107 | "www.bbc.co.uk" = "212.58.233.252" 108 | "count.wenxuecity.com" = "0.0.0.0" 109 | "adserver.wenxuecity.com" = "0.0.0.0" 110 | "www.dropbox.com" = "162.125.69.1" 111 | ".appledaily.com" = "60.254.170.127" 112 | "e-hentai.org" = "e-hentai.org.cdn.cloudflare.net" 113 | ".e-hentai.org" = "e-hentai.org.cdn.cloudflare.net" 114 | "exhentai.org" = "178.175.128.252" 115 | "v2ex.com" = "v2ex.com.cdn.cloudflare.net" 116 | ".v2ex.com" = "v2ex.com.cdn.cloudflare.net" 117 | "discord.com" = "discord.com.cdn.cloudflare.net" 118 | ".discord.com" = "discord.com.cdn.cloudflare.net" 119 | "discordapp.com" = "discordapp.com.cdn.cloudflare.net" 120 | ".discordapp.com" = "discordapp.com.cdn.cloudflare.net" 121 | "discord.gg" = "discord.gg.cdn.cloudflare.net" 122 | ".discord.gg" = "discord.gg.cdn.cloudflare.net" 123 | "media.discordapp.net" = "media.discordapp.net.cdn.cloudflare.net" 124 | "nicovideo.jp" = "futuregadget-lab.com" 125 | "qa.nicovideo.jp" = "124.146.170.109" 126 | ".nicovideo.jp" = "futuregadget-lab.com" 127 | "cn.nytimes.com" = "futuregadget-lab.com" 128 | "www.bbc.com" = "151.101.128.81" 129 | "disqus.com" = "151.101.64.134" 130 | "i.imgur.com" = "151.101.196.193" 131 | "i.stack.imgur.com" = "151.101.196.193" 132 | ".theepochtimes.com" = "151.139.128.13" 133 | "donate.epochtimes.com" = "151.139.128.13" 134 | "i.epochtimes.com" = "151.139.128.13" 135 | "mediawiki.org" = "text-lb.codfw.wikimedia.org" 136 | ".mediawiki.org" = "text-lb.codfw.wikimedia.org" 137 | "wikipedia.org" = "text-lb.codfw.wikimedia.org" 138 | ".wikipedia.org" = "text-lb.codfw.wikimedia.org" 139 | "wikiquote.org" = "text-lb.codfw.wikimedia.org" 140 | ".wikiquote.org" = "text-lb.codfw.wikimedia.org" 141 | "wikinews.org" = "text-lb.codfw.wikimedia.org" 142 | ".wikinews.org" = "text-lb.codfw.wikimedia.org" 143 | "wikiversity.org" = "text-lb.codfw.wikimedia.org" 144 | ".wikiversity.org" = "text-lb.codfw.wikimedia.org" 145 | "wiktionary.org" = "text-lb.codfw.wikimedia.org" 146 | ".wiktionary.org" = "text-lb.codfw.wikimedia.org" 147 | "wikibooks.org" = "text-lb.codfw.wikimedia.org" 148 | ".wikibooks.org" = "text-lb.codfw.wikimedia.org" 149 | "wikivoyage.org" = "text-lb.codfw.wikimedia.org" 150 | ".wikivoyage.org" = "text-lb.codfw.wikimedia.org" 151 | "wikisource.org" = "text-lb.codfw.wikimedia.org" 152 | ".wikisource.org" = "text-lb.codfw.wikimedia.org" 153 | "wikidata.org" = "text-lb.codfw.wikimedia.org" 154 | ".wikidata.org" = "text-lb.codfw.wikimedia.org" 155 | "wikimedia.org" = "text-lb.codfw.wikimedia.org" 156 | "upload.wikimedia.org" = "upload-lb.codfw.wikimedia.org" 157 | "maps.wikimedia.org" = "upload-lb.codfw.wikimedia.org" 158 | ".wikimedia.org" = "text-lb.codfw.wikimedia.org" 159 | "scratch.mit.edu" = "scratchfoundation.map.fastly.net" 160 | ".scratch.mit.edu" = "scratchfoundation.map.fastly.net" 161 | "archive.org" = "207.241.224.27" 162 | "assets.twitch.tv" = "futuregadget-lab.com" 163 | "vod-secure.twitch.tv" = "futuregadget-lab.com" 164 | "vod-metro.twitch.tv" = "futuregadget-lab.com" 165 | "vod-storyboards.twitch.tv" = "futuregadget-lab.com" 166 | "extension-files.twitch.tv" = "futuregadget-lab.com" 167 | "panels.twitch.tv" = "futuregadget-lab.com" 168 | "clips-media-assets2.twitch.tv" = "futuregadget-lab.com" 169 | "extensions-discovery-images.twitch.tv" = "futuregadget-lab.com" 170 | "passport.twitch.tv" = "futuregadget-lab.com" 171 | "brand.twitch.tv" = "futuregadget-lab.com" 172 | "meetups.twitch.tv" = "futuregadget-lab.com" 173 | "affiliate.twitch.tv" = "futuregadget-lab.com" 174 | "ttv-redirect.m7g.twitch.tv" = "futuregadget-lab.com" 175 | "blog.twitch.tv" = "futuregadget-lab.com" 176 | "streamon.twitch.tv" = "futuregadget-lab.com" 177 | "rivals.twitch.tv" = "futuregadget-lab.com" 178 | "bits.twitch.tv" = "futuregadget-lab.com" 179 | "mew.twitch.tv" = "futuregadget-lab.com" 180 | "mobile.twitch.tv" = "futuregadget-lab.com" 181 | ".event-engineering.twitch.tv" = "futuregadget-lab.com" 182 | "mi.twitch.tv" = "futuregadget-lab.com" 183 | "costream.twitch.tv" = "futuregadget-lab.com" 184 | "id-cdn.twitch.tv" = "futuregadget-lab.com" 185 | "cvp.twitch.tv" = "futuregadget-lab.com" 186 | "sings.twitch.tv" = "futuregadget-lab.com" 187 | "discuss.dev.twitch.tv" = "futuregadget-lab.com" 188 | "singlelogin.re" = "176.123.7.105" 189 | ".singlelogin.re" = "176.123.7.105" 190 | # "singlelogin.re" = "176.123.7.228" 191 | # ".singlelogin.re" = "176.123.7.228" 192 | # "singlelogin.re" = "176.123.7.252" 193 | # ".singlelogin.re" = "176.123.7.252" 194 | "greasyfork.org" = "update.greasyfork.org" 195 | "deviantart.com" = "futuregadget-lab.com" 196 | ".deviantart.com" = "futuregadget-lab.com" 197 | ".deviantart.net" = "futuregadget-lab.com" 198 | ".wixmp.com" = "futuregadget-lab.com" 199 | -------------------------------------------------------------------------------- /accesser/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/URenko/Accesser/e99854953553eda4cda036b6b0bd13c5f7f1efd2/accesser/utils/__init__.py -------------------------------------------------------------------------------- /accesser/utils/cert_verify.py: -------------------------------------------------------------------------------- 1 | from ssl import CertificateError, _inet_paton, _dnsname_match, _ipaddress_match 2 | 3 | def loosely_dnsname_match(dn, hostname): 4 | return dn.rsplit('.', maxsplit=2)[-2:] == hostname.rsplit('.', maxsplit=2)[-2:] 5 | 6 | def match_hostname(cert, hostname, policy): 7 | """based on ssl.py in python3.11 8 | """ 9 | try: 10 | host_ip = _inet_paton(hostname) 11 | except ValueError: 12 | # Not an IP address (common case) 13 | host_ip = None 14 | dnsnames = [] 15 | san = cert.get('subjectAltName', ()) 16 | for key, value in san: 17 | if key == 'DNS': 18 | if host_ip is None and (_dnsname_match(value, hostname) or (policy != 'strict' and loosely_dnsname_match(value, hostname))): 19 | return True 20 | dnsnames.append(value) 21 | elif key == 'IP Address': 22 | if host_ip is not None and _ipaddress_match(value, host_ip): 23 | return True 24 | dnsnames.append(value) 25 | if not dnsnames: 26 | # The subject is only checked when there is no dNSName entry 27 | # in subjectAltName 28 | for sub in cert.get('subject', ()): 29 | for key, value in sub: 30 | # XXX according to RFC 2818, the most specific Common Name 31 | # must be used. 32 | if key == 'commonName': 33 | if _dnsname_match(value, hostname) or (policy != 'strict' and loosely_dnsname_match(value, hostname)): 34 | return False 35 | dnsnames.append(value) 36 | if len(dnsnames) > 1: 37 | return False 38 | elif len(dnsnames) == 1: 39 | return False 40 | else: 41 | raise CertificateError("no appropriate commonName or " 42 | "subjectAltName fields were found") -------------------------------------------------------------------------------- /accesser/utils/certmanager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Accesser 4 | # Copyright (C) 2018 URenko 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | import os 20 | import random 21 | import sys 22 | import datetime 23 | from pathlib import Path 24 | 25 | from cryptography import x509 26 | from cryptography.x509.oid import NameOID 27 | from cryptography.hazmat.primitives import hashes 28 | from cryptography.hazmat.primitives import serialization 29 | from cryptography.hazmat.primitives.asymmetric import rsa 30 | 31 | from . import setting 32 | from .setting import basepath 33 | 34 | if setting.config['importca']: 35 | certpath = os.path.join(basepath, 'CERT') 36 | else: 37 | certpath ='CERT' 38 | if not os.path.exists(certpath): 39 | os.makedirs(certpath, exist_ok=True) 40 | 41 | def create_root_ca(): 42 | key = rsa.generate_private_key( 43 | public_exponent=65537, 44 | key_size=4096, 45 | ) 46 | 47 | subject = issuer = x509.Name([ 48 | x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Accesser"), 49 | x509.NameAttribute(NameOID.COMMON_NAME, "Accesser"), 50 | ]) 51 | cert = x509.CertificateBuilder().subject_name( 52 | subject 53 | ).issuer_name( 54 | issuer 55 | ).public_key( 56 | key.public_key() 57 | ).serial_number( 58 | x509.random_serial_number() 59 | ).not_valid_before( 60 | datetime.datetime.now(datetime.timezone.utc) 61 | ).not_valid_after( 62 | datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10*365) 63 | ).add_extension( 64 | x509.BasicConstraints(ca=True, path_length=None), critical=True, 65 | ).sign(key, hashes.SHA256()) 66 | 67 | (Path(certpath) / "root.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM)) 68 | 69 | (Path(certpath) / "root.key").write_bytes(key.private_bytes( 70 | encoding=serialization.Encoding.PEM, 71 | format=serialization.PrivateFormat.PKCS8, 72 | encryption_algorithm=serialization.NoEncryption(), 73 | )) 74 | 75 | (Path(certpath) / "root.pfx").write_bytes(serialization.pkcs12.serialize_key_and_certificates( 76 | b"Accesser", key, cert, None, serialization.NoEncryption() 77 | )) 78 | 79 | 80 | def create_certificate(server_name): 81 | rootpem = (Path(certpath) / "root.crt").read_bytes() 82 | rootkey = (Path(certpath) / "root.key").read_bytes() 83 | ca_cert = x509.load_pem_x509_certificate(rootpem) 84 | pkey = serialization.load_pem_private_key(rootkey, password=None) 85 | 86 | cert = x509.CertificateBuilder().subject_name(x509.Name([ 87 | x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Accesser"), 88 | x509.NameAttribute(NameOID.COMMON_NAME, "Accesser_Proxy"), 89 | ]) 90 | ).issuer_name( 91 | ca_cert.subject 92 | ).public_key( 93 | pkey.public_key() 94 | ).serial_number( 95 | x509.random_serial_number() 96 | ).not_valid_before( 97 | datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=600) 98 | ).not_valid_after( 99 | datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=365) 100 | ).add_extension( 101 | x509.SubjectAlternativeName([ 102 | x509.DNSName(server_name), 103 | x509.DNSName('*.'+server_name), 104 | ]), 105 | critical=False, 106 | ).sign(pkey, hashes.SHA256()) 107 | 108 | 109 | (Path(certpath) / f"{server_name}.crt").write_bytes( 110 | cert.public_bytes(serialization.Encoding.PEM) + 111 | pkey.private_bytes( 112 | encoding=serialization.Encoding.PEM, 113 | format=serialization.PrivateFormat.PKCS8, 114 | encryption_algorithm=serialization.NoEncryption(), 115 | ) 116 | ) 117 | -------------------------------------------------------------------------------- /accesser/utils/importca.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Accesser 4 | # Copyright (C) 2018 URenko 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | import os, sys 20 | import subprocess 21 | import locale 22 | 23 | from cryptography.hazmat.primitives import serialization 24 | from cryptography.hazmat.primitives.serialization import pkcs12 25 | 26 | from . import setting 27 | from . import certmanager as cm 28 | from .setting import basepath 29 | from .log import logger 30 | logger = logger.getChild('importca') 31 | 32 | if setting.config['importca']: 33 | certpath = os.path.join(basepath, 'CERT') 34 | else: 35 | certpath = 'CERT' 36 | 37 | def logandrun(cmd): 38 | if hasattr(subprocess, 'STARTUPINFO'): 39 | si = subprocess.STARTUPINFO() 40 | si.dwFlags |= subprocess.STARTF_USESHOWWINDOW 41 | else: 42 | si = None 43 | return logger.debug(subprocess.check_output(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE \ 44 | , startupinfo=si, env=os.environ).decode(locale.getpreferredencoding())) 45 | 46 | def import_windows_ca(): 47 | try: 48 | logandrun('certutil -f -user -p "" -exportPFX My Accesser '+os.path.join(certpath, 'root.pfx')) 49 | except subprocess.CalledProcessError: 50 | logger.debug("Export Failed") 51 | if not os.path.exists(os.path.join(certpath ,"root.pfx")): 52 | cm.create_root_ca() 53 | try: 54 | logger.info("Importing new certificate") 55 | logandrun('CertUtil -f -user -p "" -importPFX My '+os.path.join(certpath, 'root.pfx')) 56 | except subprocess.CalledProcessError: 57 | logger.error("Import Failed") 58 | logandrun('CertUtil -user -delstore My Accesser') 59 | # os.remove(os.path.join(certpath ,"root.pfx")) 60 | # os.remove(os.path.join(certpath ,"root.crt")) 61 | # os.remove(os.path.join(certpath ,"root.key")) 62 | # sys.exit(5) 63 | logger.warning('Try to manually import the certificate') 64 | else: 65 | with open(os.path.join(certpath ,"root.pfx"), 'rb') as pfxfile: 66 | private_key, certificate, _ = pkcs12.load_key_and_certificates(pfxfile.read(), password=None) 67 | with open(os.path.join(certpath ,"root.crt"), "wb") as certfile: 68 | certfile.write(certificate.public_bytes(serialization.Encoding.PEM)) 69 | with open(os.path.join(certpath ,"root.key"), "wb") as pkeyfile: 70 | pkeyfile.write(private_key.private_bytes( 71 | encoding=serialization.Encoding.PEM, 72 | format=serialization.PrivateFormat.PKCS8, 73 | encryption_algorithm=serialization.NoEncryption(), 74 | )) 75 | 76 | def import_mac_ca(): 77 | ca_hash = CertUtil.ca_thumbprint.replace(':', '') 78 | 79 | def get_exist_ca_sha1(): 80 | args = ['security', 'find-certificate', '-Z', '-a', '-c', 'Accesser'] 81 | output = subprocess.check_output(args) 82 | for line in output.splitlines(True): 83 | if len(line) == 53 and line.startswith("SHA hash:"): 84 | sha1_hash = line[12:52] 85 | return sha1_hash 86 | 87 | exist_ca_sha1 = get_exist_ca_sha1() 88 | if exist_ca_sha1 == ca_hash: 89 | logger.info("Accesser CA exist") 90 | return 91 | 92 | import_command = 'security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain {}'.format('root.crt') 93 | if exist_ca_sha1: 94 | delete_ca_command = 'security delete-certificate -Z %s' % exist_ca_sha1 95 | exec_command = "%s;%s" % (delete_ca_command, import_command) 96 | else: 97 | exec_command = import_command 98 | 99 | admin_command = """osascript -e 'do shell script "%s" with administrator privileges' """ % exec_command 100 | cmd = admin_command.encode('utf-8') 101 | logger.info("try auto import CA command:%s", cmd) 102 | os.system(cmd) 103 | 104 | def import_ca(): 105 | if not(os.path.exists(os.path.join(certpath ,"root.crt")) and os.path.exists(os.path.join(certpath ,"root.key"))): 106 | if setting.config['importca']: 107 | if sys.platform.startswith('win'): 108 | import_windows_ca() 109 | return 110 | else: 111 | logger.warning('Automatic import of root certificate root.crt is not yet supported on this platform.') 112 | cm.create_root_ca() 113 | logger.warning(f'You can GET root certificate from http://localhost:{setting.config["server"]["port"]}/CERT/root.crt and import it manually.') 114 | -------------------------------------------------------------------------------- /accesser/utils/log.py: -------------------------------------------------------------------------------- 1 | import logging, logging.handlers 2 | try: 3 | from rich.logging import RichHandler 4 | has_rich = True 5 | except ModuleNotFoundError: 6 | has_rich = False 7 | 8 | from . import setting 9 | 10 | is_console = not setting.config['log']['logfile'] 11 | logging.basicConfig( 12 | format="%(message)s" if has_rich and is_console else '%(asctime)s %(levelname)-8s %(name)s: %(message)s', 13 | datefmt='%Y-%m-%d %H:%M:%S', 14 | handlers=[logging.handlers.RotatingFileHandler(setting.config['log']['logfile'], maxBytes=2**20, backupCount=1)] if not is_console else ([RichHandler()] if has_rich else None) 15 | ) 16 | logger = logging.getLogger('Accesser') 17 | logger.setLevel(setting.config['log']['loglevel'].upper()) 18 | -------------------------------------------------------------------------------- /accesser/utils/setting.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import shutil, os, shutil, filecmp 3 | 4 | try: 5 | import tomllib 6 | except ModuleNotFoundError: 7 | import tomli as tomllib 8 | import argparse 9 | 10 | basepath = Path(__file__).parent.parent 11 | 12 | 13 | def deep_merge(config_a: dict, config_b: dict): 14 | res = config_b | config_a 15 | for key in config_a: 16 | if key in config_b and type(config_a[key]) is type(config_b[key]): 17 | if isinstance(config_a[key], dict): 18 | res[key] = deep_merge(config_a[key], config_b[key]) 19 | elif isinstance(config_a[key], list): 20 | for elem in config_b[key]: 21 | if elem not in res[key]: 22 | res[key].append(elem) 23 | return res 24 | 25 | 26 | if Path("rules.toml").exists(): 27 | if Path("rules.toml").stat().st_mtime_ns > 0: 28 | rules_update_case = "modified" 29 | else: 30 | if filecmp.cmp("rules.toml", basepath / "rules.toml"): 31 | rules_update_case = "holding" 32 | else: 33 | rules_update_case = "old" 34 | else: 35 | rules_update_case = "missing" 36 | if rules_update_case in ("old", "missing"): 37 | shutil.copyfile(basepath / "rules.toml", "rules.toml") 38 | os.utime("rules.toml", ns=(0, 0)) 39 | 40 | _rules = {} 41 | 42 | if not Path("rules").exists() or not Path("rules").is_dir(): 43 | Path("rules").mkdir() 44 | 45 | for custom_rules in sorted(Path("rules").glob("*.toml"), key=lambda f: f.name): 46 | with custom_rules.open(mode="rb") as f: 47 | _rules = deep_merge(_rules, tomllib.load(f)) 48 | 49 | with Path("rules.toml").open(mode="rb") as f: 50 | _rules = deep_merge(_rules, tomllib.load(f)) 51 | 52 | if not Path("config.toml").exists(): 53 | shutil.copyfile(basepath / "config.toml", "config.toml") 54 | 55 | with open("config.toml", "rb") as f: 56 | _config = tomllib.load(f) 57 | 58 | config = _rules.copy() 59 | config = deep_merge(_config, _rules) 60 | 61 | 62 | def parse_args(): 63 | parser = argparse.ArgumentParser() 64 | parser.add_argument( 65 | "--notsetproxy", 66 | action="store_true", 67 | help="do not set system's pac proxy automatically", 68 | ) 69 | parser.add_argument( 70 | "--notimportca", 71 | action="store_true", 72 | help="do not import certificate to system automatically", 73 | ) 74 | args = parser.parse_args() 75 | if args.notsetproxy: 76 | config["setproxy"] = False 77 | if args.notimportca: 78 | config["importca"] = False 79 | -------------------------------------------------------------------------------- /accesser/utils/sysproxy.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from . import setting 3 | 4 | if sys.platform.startswith('win'): 5 | from ctypes import windll 6 | import winreg 7 | 8 | #TODO: use Windows API instead of winreg, see https://github.com/Noisyfox/sysproxy for example. 9 | 10 | def set_pac(pac): 11 | if setting.config['setproxy'] and sys.platform.startswith('win'): 12 | with winreg.OpenKey(winreg.HKEY_CURRENT_USER, 13 | r'Software\Microsoft\Windows\CurrentVersion\Internet Settings', 14 | 0, winreg.KEY_ALL_ACCESS) as INTERNET_SETTINGS: 15 | if pac is None: 16 | winreg.DeleteValue(INTERNET_SETTINGS, 'AutoConfigURL') 17 | else: 18 | winreg.SetValueEx(INTERNET_SETTINGS, 'AutoConfigURL', 0, winreg.REG_SZ, pac) 19 | 20 | INTERNET_OPTION_REFRESH = 37 21 | INTERNET_OPTION_SETTINGS_CHANGED = 39 22 | windll.Wininet.InternetSetOptionW(0, INTERNET_OPTION_REFRESH, 0, 0) 23 | windll.Wininet.InternetSetOptionW(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0) -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "accesser" 7 | version = "0.11.0" 8 | authors = [ 9 | { name="URenko" }, 10 | ] 11 | description = "🌏一个解决SNI RST导致维基百科、Pixiv等站点无法访问的工具 | A tool for solving SNI RST" 12 | readme = "README.md" 13 | requires-python = ">=3.10" 14 | classifiers = [ 15 | "Programming Language :: Python :: 3", 16 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 17 | "Operating System :: OS Independent", 18 | ] 19 | dependencies = [ 20 | 'packaging', 21 | 'cryptography', 22 | 'tld', 23 | 'dnspython >= 2.7', 24 | 'tomli >= 1.1.0 ; python_version < "3.11"' 25 | ] 26 | 27 | [project.optional-dependencies] 28 | doh = ["dnspython[doh]"] 29 | doq = ["dnspython[doq]"] 30 | 31 | [project.scripts] 32 | accesser = "accesser:run" 33 | 34 | [project.urls] 35 | "Homepage" = "https://github.com/URenko/Accesser" 36 | "Bug Tracker" = "https://github.com/URenko/Accesser/issues" 37 | 38 | [tool.setuptools.package-data] 39 | accesser = ["*.toml", "pac"] 40 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | packaging 2 | cryptography 3 | tld 4 | dnspython >= 2.5 5 | tomli >= 1.1.0 ; python_version < "3.11" 6 | --------------------------------------------------------------------------------