├── .gitignore ├── AUTHORS ├── CNAME ├── LICENSE ├── README.md ├── Tariq ├── Steganography.py ├── TariqClient.py ├── TariqServer.py ├── TariqUtils.py ├── __init__.py └── gnupg.py ├── TariqCleint ├── TariqServer ├── _config.yml ├── client-gpg ├── pubring.gpg ├── random_seed ├── secring.gpg └── trustdb.gpg ├── client.conf ├── img └── delme.png ├── index.md ├── installation.md ├── server-gpg ├── pubring.gpg ├── random_seed ├── secring.gpg └── trustdb.gpg └── server.conf /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Tariq � Copyright 2010, Arabnix - Linux Professional Solutions 4 | * http://arabnix.com 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, version 3 of the License. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | * 18 | */ 19 | 20 | Please see: http://code.google.com/p/tariq/people/list/ for a list of all the people currently involved in Tariq. 21 | 22 | Tariq Lead Developer : Ali Al-Shemery (aka: B!n@ry) 23 | 24 | 25 | -- Copyrights -- 26 | 27 | Tariq contains code from the following applications: 28 | 29 | GNU General Public License v3 licenced: 30 | steganogra-py (c) 2010 by Zach.Varberg, http://code.google.com/p/steganogra-py/ 31 | 32 | 33 | EoF 34 | 35 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | tariq.ashemery.com -------------------------------------------------------------------------------- /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.md: -------------------------------------------------------------------------------- 1 | # A Hybrid Port Knocking System 2 | - This project was done to fulfill the requirements of my Ph.D. Thesis... 3 | - Please check the details of the project [here](http://ashemery.github.io/tariq/) 4 | -------------------------------------------------------------------------------- /Tariq/Steganography.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2010 Zachary Varberg 3 | @author: Zachary Varberg 4 | 5 | This file is part of Steganogra-py. 6 | 7 | Steganogra-py is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Steganogra-py is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Steganogra-py. If not, see . 19 | ''' 20 | import Image 21 | 22 | class FileTooLargeException(Exception): 23 | ''' 24 | Custom Exception to throw if the file is too large to fit in 25 | the Image file specified 26 | ''' 27 | pass 28 | 29 | 30 | def Dec2Bin(n): 31 | ''' 32 | Function to convert an integer to a string of 1s and 0s that is the 33 | binary equivalent. Code inspired from 34 | http://www.daniweb.com/code/snippet216539.html 35 | ''' 36 | return "".join([str((n>>y)&1) for y in xrange(7,-1,-1)]) 37 | 38 | def Bin2Dec(n): 39 | ''' 40 | Function that takes a string of 1s and 0s and converts it back to an 41 | integer 42 | ''' 43 | tmp = 0 44 | for i in xrange(1,len(n)+1): 45 | tmp+= (pow(2,i-1))*int(n[-i]) 46 | return tmp 47 | 48 | def encode(im_file, data_file, red_bits=1, green_bits=1, blue_bits=1): 49 | ''' 50 | im_file is a string that is the file name of the image to 51 | encode the data into. The data comes from data_file (which is a file object or a StringIO). Currently 52 | only character data is supported. The red, green, and blue bits 53 | variables determine how many bits of each color to encode the data 54 | into. 55 | ''' 56 | in_image = Image.open(im_file,'r') 57 | data = "" 58 | for line in data_file: 59 | for char in line: 60 | data += Dec2Bin(ord(char)) 61 | # Termination characters 62 | data+= Dec2Bin(255) + Dec2Bin(255) 63 | 64 | new_image_data = [] 65 | colors = ["red", "green", "blue"] 66 | i = 0; 67 | curCol = 0; 68 | for pixel in in_image.getdata(): 69 | # This will hold the new array of R,G,B colors with the 70 | # embedded data 71 | new_col_arr = [] 72 | for color in pixel: 73 | new_col = 0 74 | # if we still have data to encode 75 | if(i < len(data)): 76 | 77 | # Number of bits to encode for this color 78 | bits = 1 79 | if (colors[curCol%3]=="red"): 80 | bits = red_bits 81 | elif (colors[curCol%3]=="green"): 82 | bits = green_bits 83 | elif (colors[curCol%3]=="blue"): 84 | bits = blue_bits 85 | 86 | # Encode the number of bits requested 87 | tmp = list(Dec2Bin(color)) 88 | for j in xrange(1,bits+1): 89 | # if we still have data to encode 90 | if(i < len(data)): 91 | tmp[-j]=data[i] 92 | i+=1 93 | 94 | #Pull out a new int value for the encoded color 95 | new_col = Bin2Dec("".join(tmp)) 96 | else: 97 | new_col = color 98 | 99 | # Append the new color to our new pixel array 100 | new_col_arr.append(new_col) 101 | curCol +=1 102 | 103 | # Append the new 3 color array to our new image data 104 | new_image_data.append(new_col_arr) 105 | 106 | # If there wasn't enough pixels to encode all the data. 107 | if i != len(data): 108 | raise FileTooLargeException("Image to small for current settings.") 109 | 110 | # Write our new image data to a new image 111 | out_image = in_image.copy() 112 | for x in xrange(out_image.size[0]): 113 | for y in xrange(out_image.size[1]): 114 | pos = x + out_image.size[0] * y 115 | out_image.putpixel((x,y),tuple(new_image_data[pos])) 116 | return out_image 117 | 118 | def decode(im_dec, red_bits=1, green_bits=1, blue_bits=1): 119 | in_image = Image.open(im_dec) 120 | 121 | # Number of consecutive ones to track if we've found the termination 122 | # characters 123 | num_ones = 0 124 | 125 | # The data pulled out 126 | data = [] 127 | 128 | tmp_list = [] 129 | colors = ["red", "green", "blue"] 130 | try: 131 | for pixel in in_image.getdata(): 132 | i = 0 133 | for color in pixel: 134 | tmp = list(Dec2Bin(color)) 135 | 136 | bits = 1 137 | if(colors[i%3]=="red"): 138 | bits = red_bits 139 | if(colors[i%3]=="green"): 140 | bits = green_bits 141 | if(colors[i%3]=="blue"): 142 | bits = blue_bits 143 | 144 | # Pull out the specified number of bits based on the color 145 | for j in xrange(1,bits+1): 146 | tmp_list.append(tmp[-j]) 147 | if tmp[-j] == '1': 148 | num_ones += 1 149 | else: 150 | num_ones = 0 151 | # If we have pulled out 1 byte of data 152 | if len(tmp_list) == 8: 153 | data.append(tmp_list) 154 | tmp_list = [] 155 | # Two 255 characters is a termination sequence 156 | if num_ones == 16: 157 | raise StopIteration 158 | i += 1 159 | 160 | except StopIteration: 161 | pass 162 | 163 | 164 | chars = "" 165 | for char in data[:-1]: 166 | tmp = chr(Bin2Dec("".join(char))) 167 | if(ord(tmp)!=255): 168 | chars+=tmp 169 | 170 | return chars 171 | 172 | def save_file(data, file_name): 173 | ''' 174 | This will write all of the information in data (currently only 175 | character data is tested) and save it to the file file_name 176 | ''' 177 | out_file = open(file_name,'wb+') 178 | out_file.write(data) 179 | out_file.close() 180 | 181 | if __name__ == '__main__': 182 | pass 183 | # encode('flower.png','Macbeth.txt',0,1,6).save('newOut.png') 184 | # save_file(decode('newOut.png',0,1,6),'newOut1.txt') 185 | 186 | -------------------------------------------------------------------------------- /Tariq/TariqClient.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python3 2 | 3 | import sys, os, os.path, re, random, glob 4 | import StringIO 5 | import Steganography 6 | 7 | import gnupg 8 | from time import time, sleep 9 | from TariqUtils import readconf, get_fingerprint, dec 10 | 11 | 12 | import sys 13 | sys.path.append('/usr/lib/python2.6') 14 | sys.path.append('/usr/lib/pymodules/python2.6') 15 | sys.path.append('/usr/local/lib/python2.6/dist-packages') 16 | import scapy 17 | 18 | #from scapy.all import * 19 | 20 | bigS=re.compile(r'^\S+$') 21 | cmd_re=re.compile(r'^([CEO]) ') # close port, execute command, open port 22 | 23 | def gen_payload(img_fn, s): 24 | """ 25 | put text s into image file img_fn x 26 | and return the modified image file content 27 | """ 28 | in_file=StringIO.StringIO(s) 29 | out_file=StringIO.StringIO() 30 | # for example in 16-bit they use 565 for rgb see http://en.wikipedia.org/wiki/Color_depth 31 | # because human eye is more sensitive to the color green 32 | Steganography.encode(img_fn, in_file, red_bits=1, green_bits=1, blue_bits=1).save(out_file,format='png') 33 | return out_file.getvalue() 34 | 35 | def split_msg(n, msg): 36 | l=len(msg) 37 | r=l//n 38 | msgs=[] 39 | j=0 40 | for i in range(n-1): msgs.append(msg[j:j+r]); j+=r 41 | msgs.append(msg[j:]) 42 | return msgs 43 | 44 | def knock(gpg, ports, email, img_fn, ip, cmd): 45 | """ 46 | email need not be a real email, it's just a unique id within the system 47 | """ 48 | if not bigS.match(email): raise KeyError 49 | fingerprint=get_fingerprint(gpg, email=email) # just to make sure it exists 50 | if not cmd_re.match(cmd): return -1 51 | s=email+" "+cmd 52 | msg=gen_payload(img_fn, s) 53 | l=len(msg) 54 | print (l) 55 | # open('delme2.png','wb+').write(msg) 56 | n=len(ports) 57 | msgs=split_msg(n, msg) 58 | t=1.0/n 59 | sp=RandShort() 60 | # knock all but last ports 61 | for i,p in enumerate(ports[:-1]): 62 | pk=IP(dst=ip)/TCP(flags='S', sport=sp, dport=p)/msgs[i] 63 | send(pk) 64 | sleep(t) 65 | # knock last port and wait response 66 | i,p=-1,ports[-1] 67 | pk=IP(dst=ip)/TCP(flags='S', sport=sp, dport=p)/msgs[i] 68 | r,u=sr(pk,timeout=0.5) 69 | if len(r)==0: print ("** Error: no response") 70 | print (r.__repr__()) 71 | for pk in r[0]: 72 | print ("Got answer:",) 73 | if pk.payload.flags!=18: print ("skipped"); continue 74 | print ("OK") 75 | enc_blob=str(pk.payload.payload) 76 | # print "payload: [%s]" % enc_blob 77 | print ("** SENDING REST:",) 78 | dec_blob=dec(gpg, enc_blob) 79 | rpk=IP(dst=pk.src,src=pk.dst)/TCP(flags='R',dport=pk.sport, sport=pk.dport, seq=pk.seq+1)/dec_blob 80 | send(rpk) 81 | return 0 82 | from getopt import getopt, GetoptError 83 | 84 | def usage(): 85 | print ('''\ 86 | Usage: {0} [-c CONF] [-p PORTS] [-i IMG_DIR] [-g GPGDIR] [-u USERID] TARGET COMMAND 87 | \tWhere: 88 | \t\t-c CONF 89 | \t\t\t* specify config file 90 | \t\t-p PORTS 91 | \t\t\t* comma delimited no space ports to knock 92 | \t\t-u USERID 93 | \t\t\t* the email portion of your private GPG key 94 | 95 | 96 | \tCOMMAD: one of the following 97 | \t\tO PORT 98 | \t\t\t* opens specified port for you 99 | \t\tC PORT 100 | \t\t\t* closes specified port 101 | \t\tE CMD 102 | \t\t\t* run specified command on server as root 103 | ''').format(os.path.basename(sys.argv[0])) 104 | 105 | def main(): 106 | random.seed(time()) 107 | args_to_c={ 108 | '-p':'secret_ports', '-i':'img_dir', 109 | '-g': 'client_gpg_dir', '-u':'user' 110 | } 111 | try: 112 | opts, args = getopt(sys.argv[1:], "c:p:i:g:u:", ["help"]) 113 | except (GetoptError, err): 114 | print (str(err)) # will print something like "option -a not recognized" 115 | usage() 116 | sys.exit(1) 117 | opts=dict([(args_to_c.get(i,i),j) for i,j in opts]) 118 | if opts.has_key('help'): 119 | usage() 120 | sys.exit(2) 121 | fn=opts.get('-c',None) 122 | if not fn: 123 | fn='/etc/tariq/client.conf' 124 | elif fn and not os.path.exists(fn): 125 | fn='/etc/tariq/client.conf' 126 | 127 | if not os.path.exists(fn): 128 | fn=os.path.join(os.path.dirname(sys.argv[0]),'client.conf') 129 | if not os.path.exists(fn): 130 | fn=os.path.abspath('client.conf') 131 | if not os.path.exists(fn): 132 | print (" ** Error: config file not found") 133 | usage() 134 | exit(3) 135 | c=readconf(fn) 136 | c.update(opts) 137 | if not all(map(lambda i: i in c,['secret_ports','img_dir', 'client_gpg_dir', 'user'])): 138 | print (" ** Error: missing required parameters") 139 | usage() 140 | exit(4) 141 | 142 | 143 | tariqPorts=map(lambda i: int(i) ,c['secret_ports'].split(',')) 144 | user=c['user'] 145 | img_dir=c['img_dir'] 146 | if not os.path.isdir(img_dir): 147 | print (" ** Error [%s] not found") % img_dir 148 | usage() 149 | exit(5) 150 | 151 | img_ls=glob.glob(os.path.join(img_dir,'*.png')) 152 | if not img_ls: 153 | print (" ** Error: no png images found on [%s]") % img_dir 154 | usage() 155 | exit(5) 156 | img=random.choice(img_ls) 157 | gpg_dir=c['client_gpg_dir'] 158 | if not os.path.isdir(gpg_dir): 159 | print (" ** Error [%s] not found") % gpg_dir 160 | print (" ** trying client_gpg_dir=[%s]") % gpg_dir 161 | gpg_dir=os.path.join(os.path.dirname(sys.argv[0]),'client-gpg') 162 | if not os.path.isdir(gpg_dir): 163 | print (" gpg dir not found") 164 | usage() 165 | exit(5) 166 | gpg = gnupg.GPG(gnupghome=gpg_dir) 167 | if len(args)<3: 168 | print (" ** missing TARGET CMD ARGS") 169 | usage() 170 | exit(6) 171 | target=args[0] 172 | cmd=" ".join(args[1:]) 173 | knock(gpg, tariqPorts, user, img , target, cmd) 174 | 175 | if __name__=='__main__': 176 | main() 177 | 178 | 179 | -------------------------------------------------------------------------------- /Tariq/TariqServer.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python3 2 | import sys, time, hashlib, random 3 | 4 | import StringIO 5 | import Steganography 6 | 7 | import gnupg 8 | 9 | from Queue import Queue 10 | from threading import Thread 11 | from subprocess import Popen, PIPE 12 | 13 | from TariqUtils import readconf, get_fingerprint, enc 14 | 15 | 16 | import sys 17 | sys.path.append('/usr/lib/python2.6') 18 | sys.path.append('/usr/lib/pymodules/python2.6') 19 | sys.path.append('/usr/local/lib/python2.6/dist-packages') 20 | import scapy 21 | 22 | #from scapy.all import * 23 | 24 | 25 | cmd_re=re.compile(r'^([CEO]) ') # close port, execute command, open port 26 | 27 | def randomblob(m,M): 28 | return (''.join(map(lambda i: chr(random.randrange(0,255)), range(random.randrange(m,M))))).encode('base64') 29 | 30 | class TariqServer(AnsweringMachine): 31 | function_name = "TariqServer" 32 | filter = "tcp and dst portrange 1000-65535" 33 | send_function = staticmethod(send) 34 | def __init__(self, fn, *args, **kw): 35 | random.seed(time.time()) 36 | self._ps=[] 37 | self._setsid = getattr(os, 'setsid', None) 38 | if not self._setsid: self._setsid = getattr(os, 'setpgrp', None) 39 | self._q = Queue(0) 40 | self._process_conf(fn) 41 | self._start_threads() 42 | self._portsN=len(self._ports) 43 | self._hist={} 44 | self._challenge={} 45 | self._gpg = gnupg.GPG(gnupghome=self._server_gpg_dir) 46 | AnsweringMachine.__init__(self, *args, **kw) 47 | 48 | def _get_iptables_rule_n(self, ip, dport): 49 | """ 50 | returns rule number or 0 if not found 51 | """ 52 | p=Popen(self._iptables_dump_cmd, 0, '/bin/bash',shell=True, stdout=PIPE) 53 | l=p.communicate()[0].strip().splitlines() 54 | if not l or not l[0].startswith('-N'): return 0 55 | for i,j in enumerate(l): 56 | #print "matching with rule %d which is [%s]" % (i,j) 57 | m=self._open_tcp_port_re.match(j) 58 | if m and m.group('ip')==ip and int(m.group('dport'))==dport: 59 | return i 60 | m=self._open_udp_port_re.match(j) 61 | if m and m.group('ip')==ip and int(m.group('dport'))==dport: 62 | return i 63 | return 0 64 | 65 | def _run_shell_cmd(self, cmd): 66 | self._ps=filter(lambda x: x.poll()!=None,self._ps) # remove terminated processes from _ps list 67 | self._ps.append(Popen(cmd,0,'/bin/bash',shell=True, preexec_fn=self._setsid)) 68 | 69 | def _run_cmd(self, ip, cmd, args): 70 | if cmd=="E": 71 | print (' ** running [%s]') % args 72 | self._run_shell_cmd(args) 73 | elif cmd=='C': 74 | if not args.isdigit(): 75 | print (" ** Error: dport should be an integer") 76 | return 77 | k=1 78 | while(k): 79 | k=self._get_iptables_rule_n(ip, int(args)) 80 | if k: self._run_shell_cmd('/sbin/iptables -D %s %d' % (self._iptables_chain, k)) 81 | elif cmd=='O': 82 | if not args.isdigit(): 83 | print (" ** Error: dport should be an integer") 84 | return 85 | self._run_shell_cmd('/sbin/iptables '+self._open_tcp_port.format(ip=ip, dport=args)) 86 | self._run_shell_cmd('/sbin/iptables '+self._open_udp_port.format(ip=ip, dport=args)) 87 | else: 88 | print (" ** Error: cmd=[%s] not supported") % cmd 89 | 90 | def _worker(self): 91 | while self._keepworking: 92 | self._started=True 93 | # get a job from queue or block sleeping till one is available 94 | item = self._q.get(not self._end_when_done) 95 | if item: 96 | ip,cmd,args=item 97 | self._run_cmd(ip, cmd, args) 98 | self._q.task_done() 99 | elif self._q.empty() and self._end_when_done: 100 | self._keepworking=False 101 | 102 | def _start_threads(self): 103 | self._keepworking=True 104 | self._end_when_done=False 105 | self._started=False 106 | # here we create our thread pool of workers 107 | for i in range(self._threads_n): 108 | t = Thread(target=self._worker) 109 | t.setDaemon(True) 110 | t.start() 111 | # sleep to make sure all threads are waiting for jobs (inside loop) 112 | while not self._started: time.sleep(0.25) 113 | 114 | def _process_conf(self, fn): 115 | c=readconf(fn) 116 | print ("config=", c) 117 | self._server_gpg_dir=c['server_gpg_dir'] 118 | if not os.path.isabs(self._server_gpg_dir): 119 | self._server_gpg_dir=os.path.join(os.path.dirname(sys.argv[0]),self._server_gpg_dir) 120 | self._server_gpg_dir=os.path.expanduser(self._server_gpg_dir) 121 | self._ports=[int(i.strip()) for i in c['secret_ports'].split(',')] 122 | self.filter="tcp and dst portrange %s" % c['sniff_range'].strip() 123 | self._threads_n=int(c['threads_n'].strip()) 124 | self._open_tcp_port=c['open_tcp_port'].strip() 125 | self._open_udp_port=c['open_udp_port'].strip() 126 | self._open_tcp_port_re=re.compile(re.escape(self._open_tcp_port).replace('\\{','{').replace('\\}','}').format(ip=r'(?P[\d.]+)(?:/\S*)?', dport=r'(?P\d+)')) 127 | self._open_udp_port_re=re.compile(re.escape(self._open_udp_port).replace('\\{','{').replace('\\}','}').format(ip=r'(?P[\d.]+)(?:/\S*)?', dport=r'(?P\d+)')) 128 | self._iptables_chain=c['iptables_chain'] 129 | self._iptables_dump_cmd='/sbin/iptables -S '+self._iptables_chain 130 | if c['just_check_sequence'].strip()=='1': 131 | self._filter_more() 132 | self._blobm=int(c['min_random_blob_size'].strip()) 133 | self._blobM=int(c['max_random_blob_size'].strip()) 134 | 135 | def _filter_more(self): 136 | """ 137 | filter only needed ports to sniff 138 | """ 139 | c=" or ".join("dst port %d" % p for p in self._ports) 140 | self.filter = "tcp and ( %s )" % c 141 | 142 | def send_reply(self, reply): 143 | if reply!=None: self.send_function(reply, **self.optsend) 144 | 145 | def print_reply(self, req, reply): 146 | if req and reply: AnsweringMachine.print_reply(self, req, reply) 147 | 148 | def is_request(self, req): 149 | return 1 150 | 151 | def _is_right_knock(self, s, dp): 152 | if s in self._hist: 153 | n=len(self._hist[s]) 154 | # if it's the same as last one, ignore it 155 | if n>1 and n" 23 | keys=filter( 24 | lambda k: any(map(lambda u: u.endswith(e) ,k['uids'])), 25 | gpg.list_keys() 26 | ) 27 | if not keys: raise KeyError 28 | key=keys[0] 29 | fingerprint=key['fingerprint'] 30 | return fingerprint 31 | 32 | def enc(gpg, s, **kw): 33 | """ 34 | enc payload s using email or keyid or fingerprint 35 | """ 36 | fingerprint=get_fingerprint(gpg,**kw) 37 | return gpg.encrypt(s, fingerprint).data 38 | 39 | def dec(gpg, s, **kw): 40 | """ 41 | enc payload s using email or keyid or fingerprint 42 | """ 43 | return gpg.decrypt(s).data 44 | -------------------------------------------------------------------------------- /Tariq/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/Tariq/__init__.py -------------------------------------------------------------------------------- /Tariq/gnupg.py: -------------------------------------------------------------------------------- 1 | """ A wrapper for the 'gpg' command:: 2 | 3 | Portions of this module are derived from A.M. Kuchling's well-designed 4 | GPG.py, using Richard Jones' updated version 1.3, which can be found 5 | in the pycrypto CVS repository on Sourceforge: 6 | 7 | http://pycrypto.cvs.sourceforge.net/viewvc/pycrypto/gpg/GPG.py 8 | 9 | This module is *not* forward-compatible with amk's; some of the 10 | old interface has changed. For instance, since I've added decrypt 11 | functionality, I elected to initialize with a 'gnupghome' argument 12 | instead of 'keyring', so that gpg can find both the public and secret 13 | keyrings. I've also altered some of the returned objects in order for 14 | the caller to not have to know as much about the internals of the 15 | result classes. 16 | 17 | While the rest of ISconf is released under the GPL, I am releasing 18 | this single file under the same terms that A.M. Kuchling used for 19 | pycrypto. 20 | 21 | Steve Traugott, stevegt@terraluna.org 22 | Thu Jun 23 21:27:20 PDT 2005 23 | 24 | This version of the module has been modified from Steve Traugott's version 25 | (see http://trac.t7a.org/isconf/browser/trunk/lib/python/isconf/GPG.py) by 26 | Vinay Sajip to make use of the subprocess module (Steve's version uses os.fork() 27 | and so does not work on Windows). Renamed to gnupg.py to avoid confusion with 28 | the previous versions. 29 | 30 | Modifications Copyright (C) 2008-2010 Vinay Sajip. All rights reserved. 31 | 32 | A unittest harness (test_gnupg.py) has also been added. 33 | """ 34 | import locale 35 | 36 | __author__ = "Vinay Sajip" 37 | __date__ = "$07-Jan-2010 18:19:19$" 38 | 39 | try: 40 | from io import StringIO 41 | from io import TextIOWrapper 42 | from io import BufferedReader 43 | from io import BufferedWriter 44 | except ImportError: 45 | from cStringIO import StringIO 46 | class BufferedReader: pass 47 | class BufferedWriter: pass 48 | 49 | import locale 50 | import logging 51 | import os 52 | import socket 53 | from subprocess import Popen 54 | from subprocess import PIPE 55 | import threading 56 | 57 | try: 58 | import logging.NullHandler as NullHandler 59 | except ImportError: 60 | class NullHandler(logging.Handler): 61 | def emit(self, record): 62 | pass 63 | 64 | logger = logging.getLogger(__name__) 65 | if not logger.handlers: 66 | logger.addHandler(NullHandler()) 67 | 68 | def _copy_data(instream, outstream): 69 | # Copy one stream to another 70 | sent = 0 71 | while True: 72 | data = instream.read(1024) 73 | if data == "": 74 | break 75 | sent += len(data) 76 | logger.debug("sending chunk (%d): %r", sent, data[:256]) 77 | try: 78 | outstream.write(data) 79 | except: 80 | # Can sometimes get 'broken pipe' errors even when the data has all 81 | # been sent 82 | logger.exception('Error sending data') 83 | break 84 | outstream.close() 85 | logger.debug("closed output, %d bytes sent", sent) 86 | 87 | def _threaded_copy_data(instream, outstream): 88 | wr = threading.Thread(target=_copy_data, args=(instream, outstream)) 89 | wr.setDaemon(True) 90 | wr.start() 91 | return wr 92 | 93 | def _write_passphrase(stream, passphrase): 94 | stream.write(passphrase + "\n") 95 | logger.debug("Wrote passphrase") 96 | 97 | def _is_sequence(instance): 98 | return isinstance(instance,list) or isinstance(instance,tuple) 99 | 100 | def _wrap_input(inp): 101 | if isinstance(inp, BufferedWriter): 102 | inp = TextIOWrapper(inp, locale.getpreferredencoding()) 103 | return inp 104 | 105 | def _wrap_output(outp): 106 | if isinstance(outp, BufferedReader): 107 | outp = TextIOWrapper(outp) 108 | return outp 109 | 110 | class GPG(object): 111 | "Encapsulate access to the gpg executable" 112 | def __init__(self, gpgbinary='gpg', gnupghome=None, verbose=False): 113 | """Initialize a GPG process wrapper. Options are: 114 | 115 | gpgbinary -- full pathname for GPG binary. 116 | 117 | gnupghome -- full pathname to where we can find the public and 118 | private keyrings. Default is whatever gpg defaults to. 119 | 120 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 121 | 122 | """ 123 | self.gpgbinary = gpgbinary 124 | self.gnupghome = gnupghome 125 | self.verbose = verbose 126 | if gnupghome and not os.path.isdir(self.gnupghome): 127 | os.makedirs(self.gnupghome,0x1C0) 128 | p = self._open_subprocess(["--version"]) 129 | result = Verify() # any result will do for this 130 | self._collect_output(p, result) 131 | if p.returncode != 0: 132 | raise ValueError("Error invoking gpg: %s: %s" % (p.returncode, 133 | result.stderr)) 134 | 135 | def _open_subprocess(self, args, passphrase=False): 136 | # Internal method: open a pipe to a GPG subprocess and return 137 | # the file objects for communicating with it. 138 | cmd = [self.gpgbinary, '--status-fd 2 --no-tty'] 139 | if self.gnupghome: 140 | cmd.append('--homedir "%s" ' % self.gnupghome) 141 | if passphrase: 142 | cmd.append('--batch --passphrase-fd 0') 143 | 144 | cmd.extend(args) 145 | cmd = ' '.join(cmd) 146 | if self.verbose: 147 | print(cmd) 148 | logger.debug("%s", cmd) 149 | return Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) 150 | 151 | def _read_response(self, stream, result): 152 | # Internal method: reads all the output from GPG, taking notice 153 | # only of lines that begin with the magic [GNUPG:] prefix. 154 | # 155 | # Calls methods on the response object for each valid token found, 156 | # with the arg being the remainder of the status line. 157 | lines = [] 158 | while True: 159 | line = stream.readline() 160 | lines.append(line) 161 | if self.verbose: 162 | print(line) 163 | logger.debug("%s", line.rstrip()) 164 | if line == "": break 165 | line = line.rstrip() 166 | if line[0:9] == '[GNUPG:] ': 167 | # Chop off the prefix 168 | line = line[9:] 169 | L = line.split(None, 1) 170 | keyword = L[0] 171 | if len(L) > 1: 172 | value = L[1] 173 | else: 174 | value = "" 175 | result.handle_status(keyword, value) 176 | result.stderr = ''.join(lines) 177 | 178 | def _read_data(self, stream, result): 179 | # Read the contents of the file from GPG's stdout 180 | chunks = [] 181 | while True: 182 | data = stream.read(1024) 183 | if data == "": 184 | break 185 | logger.debug("chunk: %s" % data) 186 | chunks.append(data) 187 | result.data = ''.join(chunks) 188 | 189 | def _collect_output(self, process, result, writer=None): 190 | """ 191 | Drain the subprocesses output streams, writing the collected output 192 | to the result. If a writer thread (writing to the subprocess) is given, 193 | make sure it's joined before returning. 194 | """ 195 | stderr = _wrap_output(process.stderr) 196 | rr = threading.Thread(target=self._read_response, args=(stderr, result)) 197 | rr.setDaemon(True) 198 | rr.start() 199 | 200 | stdout = _wrap_output(process.stdout) 201 | dr = threading.Thread(target=self._read_data, args=(stdout, result)) 202 | dr.setDaemon(True) 203 | dr.start() 204 | 205 | dr.join() 206 | rr.join() 207 | if writer is not None: 208 | writer.join() 209 | process.wait() 210 | 211 | def _handle_io(self, args, file, result, passphrase=None): 212 | "Handle a call to GPG - pass input data, collect output data" 213 | # Handle a basic data call - pass data to GPG, handle the output 214 | # including status information. Garbage In, Garbage Out :) 215 | p = self._open_subprocess(args, passphrase is not None) 216 | stdin = _wrap_input(p.stdin) 217 | if passphrase: 218 | _write_passphrase(stdin, passphrase) 219 | writer = _threaded_copy_data(file, stdin) 220 | self._collect_output(p, result, writer) 221 | return result 222 | 223 | # 224 | # SIGNATURE METHODS 225 | # 226 | def sign(self, message, **kwargs): 227 | """sign message""" 228 | return self.sign_file(StringIO(message), **kwargs) 229 | 230 | def sign_file(self, file, keyid=None, passphrase=None, clearsign=True): 231 | """sign file""" 232 | args = ["-sa"] 233 | if clearsign: 234 | args.append("--clearsign") 235 | if keyid: 236 | args.append("--default-key %s" % keyid) 237 | 238 | result = Sign() 239 | #We could use _handle_io here except for the fact that if the 240 | #passphrase is bad, gpg bails and you can't write the message. 241 | #self._handle_io(args, StringIO(message), result, passphrase=passphrase) 242 | p = self._open_subprocess(args, passphrase is not None) 243 | try: 244 | stdin = _wrap_input(p.stdin) 245 | if passphrase: 246 | _write_passphrase(stdin, passphrase) 247 | writer = _threaded_copy_data(file, stdin) 248 | except IOError: 249 | logging.exception("error writing message") 250 | writer = None 251 | self._collect_output(p, result, writer) 252 | return result 253 | 254 | def verify(self, data): 255 | """Verify the signature on the contents of the string 'data' 256 | 257 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 258 | >>> input = gpg.gen_key_input(Passphrase='foo') 259 | >>> key = gpg.gen_key(input) 260 | >>> assert key 261 | >>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='bar') 262 | >>> assert not sig 263 | >>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='foo') 264 | >>> assert sig 265 | >>> verify = gpg.verify(str(sig)) 266 | >>> assert verify 267 | 268 | """ 269 | return self.verify_file(StringIO(data)) 270 | 271 | def verify_file(self, file): 272 | "Verify the signature on the contents of the file-like object 'file'" 273 | result = Verify() 274 | self._handle_io(['--verify'], file, result) 275 | return result 276 | 277 | # 278 | # KEY MANAGEMENT 279 | # 280 | 281 | def import_keys(self, key_data): 282 | """ import the key_data into our keyring 283 | 284 | >>> import shutil 285 | >>> shutil.rmtree("/tmp/pygpgtest") 286 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 287 | >>> input = gpg.gen_key_input() 288 | >>> result = gpg.gen_key(input) 289 | >>> print1 = result.fingerprint 290 | >>> result = gpg.gen_key(input) 291 | >>> print2 = result.fingerprint 292 | >>> pubkey1 = gpg.export_keys(print1) 293 | >>> seckey1 = gpg.export_keys(print1,secret=True) 294 | >>> seckeys = gpg.list_keys(secret=True) 295 | >>> pubkeys = gpg.list_keys() 296 | >>> assert print1 in seckeys.fingerprints 297 | >>> assert print1 in pubkeys.fingerprints 298 | >>> str(gpg.delete_keys(print1)) 299 | 'Must delete secret key first' 300 | >>> str(gpg.delete_keys(print1,secret=True)) 301 | 'ok' 302 | >>> str(gpg.delete_keys(print1)) 303 | 'ok' 304 | >>> str(gpg.delete_keys("nosuchkey")) 305 | 'No such key' 306 | >>> seckeys = gpg.list_keys(secret=True) 307 | >>> pubkeys = gpg.list_keys() 308 | >>> assert not print1 in seckeys.fingerprints 309 | >>> assert not print1 in pubkeys.fingerprints 310 | >>> result = gpg.import_keys('foo') 311 | >>> assert not result 312 | >>> result = gpg.import_keys(pubkey1) 313 | >>> pubkeys = gpg.list_keys() 314 | >>> seckeys = gpg.list_keys(secret=True) 315 | >>> assert not print1 in seckeys.fingerprints 316 | >>> assert print1 in pubkeys.fingerprints 317 | >>> result = gpg.import_keys(seckey1) 318 | >>> assert result 319 | >>> seckeys = gpg.list_keys(secret=True) 320 | >>> pubkeys = gpg.list_keys() 321 | >>> assert print1 in seckeys.fingerprints 322 | >>> assert print1 in pubkeys.fingerprints 323 | >>> assert print2 in pubkeys.fingerprints 324 | 325 | """ 326 | result = ImportResult() 327 | self._handle_io(['--import'], StringIO(key_data), result) 328 | return result 329 | 330 | def delete_keys(self, fingerprints, secret=False): 331 | which='key' 332 | if secret: 333 | which='secret-key' 334 | if _is_sequence(fingerprints): 335 | fingerprints = ' '.join(fingerprints) 336 | args = ["--batch --delete-%s %s" % (which, fingerprints)] 337 | result = DeleteResult() 338 | p = self._open_subprocess(args) 339 | self._collect_output(p, result) 340 | return result 341 | 342 | def export_keys(self, keyids, secret=False): 343 | "export the indicated keys. 'keyid' is anything gpg accepts" 344 | which='' 345 | if secret: 346 | which='-secret-key' 347 | if _is_sequence(keyids): 348 | keyids = ' '.join(keyids) 349 | args = ["--armor --export%s %s" % (which, keyids)] 350 | p = self._open_subprocess(args) 351 | # gpg --export produces no status-fd output; stdout will be 352 | # empty in case of failure 353 | #stdout, stderr = p.communicate() 354 | result = DeleteResult() # any result will do 355 | self._collect_output(p, result) 356 | return result.data 357 | 358 | def list_keys(self, secret=False): 359 | """ list the keys currently in the keyring 360 | 361 | >>> import shutil 362 | >>> shutil.rmtree("/tmp/pygpgtest") 363 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 364 | >>> input = gpg.gen_key_input() 365 | >>> result = gpg.gen_key(input) 366 | >>> print1 = result.fingerprint 367 | >>> result = gpg.gen_key(input) 368 | >>> print2 = result.fingerprint 369 | >>> pubkeys = gpg.list_keys() 370 | >>> assert print1 in pubkeys.fingerprints 371 | >>> assert print2 in pubkeys.fingerprints 372 | 373 | """ 374 | 375 | which='keys' 376 | if secret: 377 | which='secret-keys' 378 | args = "--list-%s --fixed-list-mode --fingerprint --with-colons" % (which) 379 | args = [args] 380 | p = self._open_subprocess(args) 381 | 382 | # there might be some status thingumy here I should handle... (amk) 383 | # ...nope, unless you care about expired sigs or keys (stevegt) 384 | 385 | # Get the response information 386 | result = ListKeys() 387 | self._collect_output(p, result) 388 | stdout = StringIO(result.data) 389 | valid_keywords = 'pub uid sec fpr'.split() 390 | while True: 391 | line = stdout.readline() 392 | if self.verbose: 393 | print(line) 394 | logger.debug("%s", line.rstrip()) 395 | if not line: 396 | break 397 | L = line.strip().split(':') 398 | if not L: 399 | continue 400 | keyword = L[0] 401 | if keyword in valid_keywords: 402 | getattr(result, keyword)(L) 403 | return result 404 | 405 | def gen_key(self, input): 406 | """Generate a key; you might use gen_key_input() to create the 407 | control input. 408 | 409 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 410 | >>> input = gpg.gen_key_input() 411 | >>> result = gpg.gen_key(input) 412 | >>> assert result 413 | >>> result = gpg.gen_key('foo') 414 | >>> assert not result 415 | 416 | """ 417 | args = ["--gen-key --batch"] 418 | result = GenKey() 419 | file = StringIO(input) 420 | self._handle_io(args, file, result) 421 | return result 422 | 423 | def gen_key_input(self, **kwargs): 424 | """ 425 | Generate --gen-key input per gpg doc/DETAILS 426 | """ 427 | parms = {} 428 | for key, val in list(kwargs.items()): 429 | key = key.replace('_','-').title() 430 | parms[key] = val 431 | parms.setdefault('Key-Type','RSA') 432 | parms.setdefault('Key-Length',1024) 433 | parms.setdefault('Name-Real', "Autogenerated Key") 434 | parms.setdefault('Name-Comment', "Generated by gnupg.py") 435 | try: 436 | logname = os.environ['LOGNAME'] 437 | except KeyError: 438 | logname = os.environ['USERNAME'] 439 | hostname = socket.gethostname() 440 | parms.setdefault('Name-Email', "%s@%s" % (logname.replace(' ', '_'), 441 | hostname)) 442 | out = "Key-Type: %s\n" % parms.pop('Key-Type') 443 | for key, val in list(parms.items()): 444 | out += "%s: %s\n" % (key, val) 445 | out += "%commit\n" 446 | return out 447 | 448 | # Key-Type: RSA 449 | # Key-Length: 1024 450 | # Name-Real: ISdlink Server on %s 451 | # Name-Comment: Created by %s 452 | # Name-Email: isdlink@%s 453 | # Expire-Date: 0 454 | # %commit 455 | # 456 | # 457 | # Key-Type: DSA 458 | # Key-Length: 1024 459 | # Subkey-Type: ELG-E 460 | # Subkey-Length: 1024 461 | # Name-Real: Joe Tester 462 | # Name-Comment: with stupid passphrase 463 | # Name-Email: joe@foo.bar 464 | # Expire-Date: 0 465 | # Passphrase: abc 466 | # %pubring foo.pub 467 | # %secring foo.sec 468 | # %commit 469 | 470 | # 471 | # ENCRYPTION 472 | # 473 | def encrypt_file(self, file, recipients, sign=None, 474 | always_trust=False, passphrase=None): 475 | "Encrypt the message read from the file-like object 'file'" 476 | args = ['--encrypt --armor'] 477 | if not _is_sequence(recipients): 478 | recipients = (recipients,) 479 | for recipient in recipients: 480 | args.append('--recipient %s' % recipient) 481 | if sign: 482 | args.append("--sign --default-key %s" % sign) 483 | if always_trust: 484 | args.append("--always-trust") 485 | result = Crypt() 486 | self._handle_io(args, file, result, passphrase=passphrase) 487 | return result 488 | 489 | def encrypt(self, data, recipients, **kwargs): 490 | """Encrypt the message contained in the string 'data' 491 | 492 | >>> import shutil 493 | >>> if os.path.exists("/tmp/pygpgtest"): 494 | ... shutil.rmtree("/tmp/pygpgtest") 495 | >>> gpg = GPG(gnupghome="/tmp/pygpgtest") 496 | >>> input = gpg.gen_key_input(passphrase='foo') 497 | >>> result = gpg.gen_key(input) 498 | >>> print1 = result.fingerprint 499 | >>> input = gpg.gen_key_input() 500 | >>> result = gpg.gen_key(input) 501 | >>> print2 = result.fingerprint 502 | >>> result = gpg.encrypt("hello",print2) 503 | >>> message = str(result) 504 | >>> assert message != 'hello' 505 | >>> result = gpg.decrypt(message) 506 | >>> assert result 507 | >>> str(result) 508 | 'hello' 509 | >>> result = gpg.encrypt("hello again",print1) 510 | >>> message = str(result) 511 | >>> result = gpg.decrypt(message) 512 | >>> result.status 513 | 'need passphrase' 514 | >>> result = gpg.decrypt(message,passphrase='bar') 515 | >>> result.status 516 | 'decryption failed' 517 | >>> assert not result 518 | >>> result = gpg.decrypt(message,passphrase='foo') 519 | >>> result.status 520 | 'decryption ok' 521 | >>> str(result) 522 | 'hello again' 523 | >>> result = gpg.encrypt("signed hello",print2,sign=print1) 524 | >>> result.status 525 | 'need passphrase' 526 | >>> result = gpg.encrypt("signed hello",print2,sign=print1,passphrase='foo') 527 | >>> result.status 528 | 'encryption ok' 529 | >>> message = str(result) 530 | >>> result = gpg.decrypt(message) 531 | >>> result.status 532 | 'decryption ok' 533 | >>> assert result.fingerprint == print1 534 | 535 | """ 536 | return self.encrypt_file(StringIO(data), recipients, **kwargs) 537 | 538 | def decrypt(self, message, **kwargs): 539 | return self.decrypt_file(StringIO(message), **kwargs) 540 | 541 | def decrypt_file(self, file, always_trust=False, passphrase=None): 542 | args = ["--decrypt"] 543 | if always_trust: 544 | args.append("--always-trust") 545 | result = Crypt() 546 | self._handle_io(args, file, result, passphrase) 547 | return result 548 | 549 | class Verify(object): 550 | "Handle status messages for --verify" 551 | 552 | def __init__(self): 553 | self.valid = False 554 | self.fingerprint = self.creation_date = self.timestamp = None 555 | self.signature_id = self.key_id = None 556 | self.username = None 557 | 558 | def __nonzero__(self): 559 | return self.valid 560 | 561 | __bool__ = __nonzero__ 562 | 563 | def handle_status(self, key, value): 564 | if key in ("TRUST_UNDEFINED", "TRUST_NEVER", "TRUST_MARGINAL", 565 | "TRUST_FULLY", "TRUST_ULTIMATE"): 566 | pass 567 | elif key in ("PLAINTEXT", "PLAINTEXT_LENGTH"): 568 | pass 569 | elif key == "BADSIG": 570 | self.valid = False 571 | self.key_id, self.username = value.split(None, 1) 572 | elif key == "GOODSIG": 573 | self.valid = True 574 | self.key_id, self.username = value.split(None, 1) 575 | elif key == "VALIDSIG": 576 | (self.fingerprint, 577 | self.creation_date, 578 | self.sig_timestamp, 579 | self.expire_timestamp) = value.split()[:4] 580 | elif key == "SIG_ID": 581 | (self.signature_id, 582 | self.creation_date, self.timestamp) = value.split() 583 | else: 584 | raise ValueError("Unknown status message: %r" % key) 585 | 586 | class ImportResult(object): 587 | "Handle status messages for --import" 588 | 589 | counts = '''count no_user_id imported imported_rsa unchanged 590 | n_uids n_subk n_sigs n_revoc sec_read sec_imported 591 | sec_dups not_imported'''.split() 592 | def __init__(self): 593 | self.imported = [] 594 | self.results = [] 595 | self.fingerprints = [] 596 | for result in self.counts: 597 | setattr(self, result, None) 598 | 599 | def __nonzero__(self): 600 | if self.not_imported: return False 601 | if not self.fingerprints: return False 602 | return True 603 | 604 | __bool__ = __nonzero__ 605 | 606 | ok_reason = { 607 | '0': 'Not actually changed', 608 | '1': 'Entirely new key', 609 | '2': 'New user IDs', 610 | '4': 'New signatures', 611 | '8': 'New subkeys', 612 | '16': 'Contains private key', 613 | } 614 | 615 | problem_reason = { 616 | '0': 'No specific reason given', 617 | '1': 'Invalid Certificate', 618 | '2': 'Issuer Certificate missing', 619 | '3': 'Certificate Chain too long', 620 | '4': 'Error storing certificate', 621 | } 622 | 623 | def handle_status(self, key, value): 624 | if key == "IMPORTED": 625 | # this duplicates info we already see in import_ok & import_problem 626 | pass 627 | elif key == "NODATA": 628 | self.results.append({'fingerprint': None, 629 | 'problem': '0', 'text': 'No valid data found'}) 630 | elif key == "IMPORT_OK": 631 | reason, fingerprint = value.split() 632 | reasons = [] 633 | for code, text in list(self.ok_reason.items()): 634 | if int(reason) | int(code) == int(reason): 635 | reasons.append(text) 636 | reasontext = '\n'.join(reasons) + "\n" 637 | self.results.append({'fingerprint': fingerprint, 638 | 'ok': reason, 'text': reasontext}) 639 | self.fingerprints.append(fingerprint) 640 | elif key == "IMPORT_PROBLEM": 641 | try: 642 | reason, fingerprint = value.split() 643 | except: 644 | reason = value 645 | fingerprint = '' 646 | self.results.append({'fingerprint': fingerprint, 647 | 'problem': reason, 'text': self.problem_reason[reason]}) 648 | elif key == "IMPORT_RES": 649 | import_res = value.split() 650 | for i in range(len(self.counts)): 651 | setattr(self, self.counts[i], int(import_res[i])) 652 | else: 653 | raise ValueError("Unknown status message: %r" % key) 654 | 655 | def summary(self): 656 | l = [] 657 | l.append('%d imported'%self.imported) 658 | if self.not_imported: 659 | l.append('%d not imported'%self.not_imported) 660 | return ', '.join(l) 661 | 662 | class ListKeys(list): 663 | ''' Handle status messages for --list-keys. 664 | 665 | Handle pub and uid (relating the latter to the former). 666 | 667 | Don't care about (info from src/DETAILS): 668 | 669 | crt = X.509 certificate 670 | crs = X.509 certificate and private key available 671 | sub = subkey (secondary key) 672 | ssb = secret subkey (secondary key) 673 | uat = user attribute (same as user id except for field 10). 674 | sig = signature 675 | rev = revocation signature 676 | pkd = public key data (special field format, see below) 677 | grp = reserved for gpgsm 678 | rvk = revocation key 679 | ''' 680 | def __init__(self): 681 | self.curkey = None 682 | self.fingerprints = [] 683 | 684 | def key(self, args): 685 | vars = (""" 686 | type trust length algo keyid date expires dummy ownertrust uid 687 | """).split() 688 | self.curkey = {} 689 | for i in range(len(vars)): 690 | self.curkey[vars[i]] = args[i] 691 | self.curkey['uids'] = [self.curkey['uid']] 692 | del self.curkey['uid'] 693 | self.append(self.curkey) 694 | 695 | pub = sec = key 696 | 697 | def fpr(self, args): 698 | self.curkey['fingerprint'] = args[9] 699 | self.fingerprints.append(args[9]) 700 | 701 | def uid(self, args): 702 | self.curkey['uids'].append(args[9]) 703 | 704 | def handle_status(self, key, value): 705 | pass 706 | 707 | class Crypt(Verify): 708 | "Handle status messages for --encrypt and --decrypt" 709 | def __init__(self): 710 | Verify.__init__(self) 711 | self.data = '' 712 | self.ok = False 713 | self.status = '' 714 | 715 | def __nonzero__(self): 716 | if self.ok: return True 717 | return False 718 | 719 | __bool__ = __nonzero__ 720 | 721 | def __str__(self): 722 | return self.data 723 | 724 | def handle_status(self, key, value): 725 | if key in ("ENC_TO", "USERID_HINT", "GOODMDC", "END_DECRYPTION", 726 | "BEGIN_SIGNING", "NO_SECKEY"): 727 | pass 728 | elif key in ("NEED_PASSPHRASE", "BAD_PASSPHRASE", "GOOD_PASSPHRASE", 729 | "DECRYPTION_FAILED"): 730 | self.status = key.replace("_", " ").lower() 731 | elif key == "BEGIN_DECRYPTION": 732 | self.status = 'decryption incomplete' 733 | elif key == "BEGIN_ENCRYPTION": 734 | self.status = 'encryption incomplete' 735 | elif key == "DECRYPTION_OKAY": 736 | self.status = 'decryption ok' 737 | self.ok = True 738 | elif key == "END_ENCRYPTION": 739 | self.status = 'encryption ok' 740 | self.ok = True 741 | elif key == "INV_RECP": 742 | self.status = 'invalid recipient' 743 | elif key == "KEYEXPIRED": 744 | self.status = 'key expired' 745 | elif key == "SIG_CREATED": 746 | self.status = 'sig created' 747 | elif key == "SIGEXPIRED": 748 | self.status = 'sig expired' 749 | else: 750 | Verify.handle_status(self, key, value) 751 | 752 | class GenKey(object): 753 | "Handle status messages for --gen-key" 754 | def __init__(self): 755 | self.type = None 756 | self.fingerprint = None 757 | 758 | def __nonzero__(self): 759 | if self.fingerprint: return True 760 | return False 761 | 762 | __bool__ = __nonzero__ 763 | 764 | def __str__(self): 765 | return self.fingerprint or '' 766 | 767 | def handle_status(self, key, value): 768 | if key in ("PROGRESS", "GOOD_PASSPHRASE", "NODATA"): 769 | pass 770 | elif key == "KEY_CREATED": 771 | (self.type,self.fingerprint) = value.split() 772 | else: 773 | raise ValueError("Unknown status message: %r" % key) 774 | 775 | class DeleteResult(object): 776 | "Handle status messages for --delete-key and --delete-secret-key" 777 | def __init__(self): 778 | self.status = 'ok' 779 | 780 | def __str__(self): 781 | return self.status 782 | 783 | problem_reason = { 784 | '1': 'No such key', 785 | '2': 'Must delete secret key first', 786 | '3': 'Ambigious specification', 787 | } 788 | 789 | def handle_status(self, key, value): 790 | if key == "DELETE_PROBLEM": 791 | self.status = self.problem_reason.get(value, 792 | "Unknown error: %r" % value) 793 | else: 794 | raise ValueError("Unknown status message: %r" % key) 795 | 796 | class Sign(object): 797 | "Handle status messages for --sign" 798 | def __init__(self): 799 | self.type = None 800 | self.fingerprint = None 801 | 802 | def __nonzero__(self): 803 | if self.fingerprint: return True 804 | return False 805 | 806 | __bool__ = __nonzero__ 807 | 808 | def __str__(self): 809 | return self.data or '' 810 | 811 | def handle_status(self, key, value): 812 | if key in ("USERID_HINT", "NEED_PASSPHRASE", "BAD_PASSPHRASE", 813 | "GOOD_PASSPHRASE", "BEGIN_SIGNING"): 814 | pass 815 | elif key == "SIG_CREATED": 816 | (self.type, 817 | algo, hashalgo, cls, 818 | self.timestamp, self.fingerprint 819 | ) = value.split() 820 | else: 821 | raise ValueError("Unknown status message: %r" % key) 822 | -------------------------------------------------------------------------------- /TariqCleint: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python3 2 | from Tariq.TariqClient import main 3 | main() 4 | 5 | -------------------------------------------------------------------------------- /TariqServer: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python3 2 | from Tariq.TariqServer import main 3 | main() 4 | 5 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker -------------------------------------------------------------------------------- /client-gpg/pubring.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/client-gpg/pubring.gpg -------------------------------------------------------------------------------- /client-gpg/random_seed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/client-gpg/random_seed -------------------------------------------------------------------------------- /client-gpg/secring.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/client-gpg/secring.gpg -------------------------------------------------------------------------------- /client-gpg/trustdb.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/client-gpg/trustdb.gpg -------------------------------------------------------------------------------- /client.conf: -------------------------------------------------------------------------------- 1 | # the default sequence to knock 2 | secret_ports=10000,7456,22022,12121,10001 3 | 4 | # Steganography image dir 5 | #img_dir=/usr/share/TariqClient/img 6 | img_dir=img 7 | 8 | # client GPG dir 9 | #client_gpg_dir=/etc/tariq/.client-gpg 10 | client_gpg_dir=client-gpg 11 | 12 | # default user id the server trusts 13 | # it's the email section in GPG 14 | user=omar@myorg.com 15 | 16 | -------------------------------------------------------------------------------- /img/delme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/img/delme.png -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | # A Hybrid Port Knocking System 2 | The network security has become a primary concern on the Internet in order to provide protected communication between hosts/nodes in a hostile environment. In order to protect network resources, each service provider pose a number of nontrivial challenges to security design and set its own policies for accessing resources on the network. These challenges make a case for building security solutions that achieve both broad protection and desirable network performance in terms of minimum data overhead and delay. It is so crucial to have computationally cheap and simple defense mechanisms that allow early protection against all types of attacks. In particular, it becomes very common and useful to have multiple progressively stronger layers of security, rather than attempting to have a single perfect security layer. 3 | 4 | --- 5 | ### Port-Knocking History 6 | In computer networking, Port Knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of pre-specified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s) [1]. 7 | 8 | The problem today in the world full of security threats, it should be assumed that all traffic is monitored by an unknown third party as it travels across a network. Doggedly adhering to this viewpoint provides us with the fact that our knock sequence can be passively observed by an eavesdropping person in the middle of our connection and just replay the knock sequence to get the same response from the server (open port or perform a task). This problem is called “TCP Replay Attack”. So we had to find a solution were the knock sequence is not re-playable. 9 | 10 | --- 11 | ### Tariq Overview 12 | Tariq is a new hybrid port-knocking technique, that uses Cryptography, Steganography, and Mutual Authentication to develop another security layer in front of any service that needs to be accessed from different locations around the globe. Tariq was developed using python and scapy to fulfil my Ph.D. Research. We had to use a new methodology that can communicate in an unseen manner, making TCP Replay Attacks hard to be issued against Tariq. We also wanted the implementation to listen to no ports, or bind itself to no socket for packets exchange, so that Tariq won't be exposed himself to a remote exploit. Tariq relies completely on Packet Crafting, as all packets sent and received are crafted to suite our needs. 13 | 14 | Tariq is developed using python and scapy to fulfil my Ph.D. Research. I chose python, because its an easy to learn language and the code can be easily audited or studied by others. I had to use a new methodology that can communicate in an unseen manner, making TCP Replay Attacks hard to be issued against Tariq. I also wanted the implementation to listen to no ports, or bind itself to no socket for packets exchange, so that Tariq won't be exposed itself to a remote exploit. Tariq relies completely on Packet Crafting, as all packets sent and received are crafted to suite its needs. Tariq doesn't just open/close ports, it can be used to perform remote tasks without the need to login to the remote box where Tariq is installed. All data sent and recived by Tariq is hidden within a PNG image using steganogra-py [2], and encrypted using GnuPG. The current version of Tariq uses only the TCP protocol, but I am willing to make another version of Tariq were the user has the ability to choose the communication protocol used. 15 | 16 | **Note:** This project was done to fulfill the requirements of my PhD. Thesis... 17 | 18 | --- 19 | ### What does Tariq mean? 20 | It means knocking, hammering or coming at night :) 21 | الطَّرْقُ: الضَّرْبُ، أو بالمِطْرَقَةِ، بالكسر، والصَّكُّ، -- القاموس المحيط 22 | 23 | --- 24 | ### Why Is Tariq Secure? 25 | - Tariq Server's code is very simple, and is written completely using scapy (python) 26 | - The code is concise enough to be easily audited 27 | - Tariq needs root privileges to adjust iptables rules, and perform remote tasks 28 | - Tariq does not listen on any TCP/UDP port, which means no sockets is used. Tariq uses scapy's capabilities to sniff the incoming traffic and uses Packet Crafting techniques to reply back to an legitimate client 29 | - The communication protocol is a simple secure encryption scheme that uses GnuPG keys with Steganography constructions. An observer watching packets is not given any indication that the SYN packet transmitted by 'Tariq' is a port knocking request, but even if they knew, there would be no way for them to determine which port was requested to open, or what task was requested to be done as all of that is inserted into a png picture using Steganography and then encrypted using GnuPG keys 30 | - Replaying the knock request later does them no good, and in fact does not provide any information that might be useful in determining the contents of future request. The mechanism works using a single packet for the mutual authentication 31 | 32 | --- 33 | ### Why Is Tariq Needed? 34 | Any host connected to the Internet needs to be secured against unauthorized intrusion and other attacks. Unfortunately, the only secure system is one that is completely inaccessible, but, to be useful, many hosts need to make services accessible to other hosts. While some services need to be accessible to anyone from any location, others should only be accessed by a limited number of people, or from a limited set of locations. The most obvious way to limit access is to require users to authenticate themselves before granting them access. This is were Tariq comes in place. Tariq can be used to open ports on a firewall to authorized users, and blocking all other traffic users. Tariq can also be used to execute a remotely requested task, and finally for sure Tariq can close the open ports that have been opened by a previous TariqClient? request. Tariq runs as a port authentication service on the iptables firewall, which validates the identity of remote users and modifies firewall rules (plus other tasks) according to a mutual authentication process done between Tariq Server and a Tariq client. Tariq could be used for a number of purposes, including: 35 | - Making services invisible to port scans 36 | - Providing an extra layer of security that attackers must penetrate before accessing or breaking anything important 37 | - Acting as a stop-gap security measure for services with known unpatched vulnerabilities 38 | - Providing a wrapper for a legacy or proprietary services with insufficient integrated security 39 | 40 | --- 41 | ### Howto Install Tariq 42 | - Check the installation page [here](installation) 43 | 44 | --- 45 | ### Useful References: 46 | - [[1](http://en.wikipedia.org/wiki/Port_knocking/)] Port Knocking 47 | - [[2](http://code.google.com/p/steganogra-py/)] Steganography in Python 48 | 49 | --- 50 | ### Contact Me 51 | - Twitter [here](https://twitter.com/binaryz0ne) 52 | - Email: "Ali Hadi" 53 | -------------------------------------------------------------------------------- /installation.md: -------------------------------------------------------------------------------- 1 | # Howto Install Tariq? 2 | 3 | ## Requirements 4 | - Python >= 2.6 5 | - python-imaging - Python Imaging Library (PIL) 6 | - GnuGP 7 | - Scapy 8 | - Linux kernel with iptables (eg. 2.6) 9 | 10 | --- 11 | ## Installation and Configuration 12 | ### Configuring the Client 13 | First we need to preparing GnuPG to be used, so you need to create a directory for gnupg and generate a pair of keys using the following commands: 14 | ``` 15 | mkdir /etc/tariq/.client-gpg 16 | chmod 600 /etc/tariq/.client-gpg 17 | gpg --homedir /etc/tariq/.client-gpg –gen-key 18 | ``` 19 | 20 | You need to export client's public key: 21 | ``` 22 | gpg --homedir /etc/tariq/.client-gpg -a --export tariq@arabnix.com > key.pub.txt 23 | ``` 24 | 25 | Edit the 'client.conf' file to specify the client gpg directory and the default gpg user: 26 | ``` 27 | client_gpg_dir=/etc/tariq/.client-gpg user=tariq@arabnix.com 28 | ``` 29 | 30 | And specify the image directory used for steganography, containing at least 1 reasonable png image file, just like the one included as a sample 'sample.png': 31 | ``` 32 | img_dir=/usr/share/TariqClient?/img 33 | ``` 34 | 35 | Now specify the default secret knock sequence to match the sequence configured on the tariq server: 36 | ``` 37 | secret_ports=10000,7456,22022,12121,10001 38 | ``` 39 | 40 | **Note:** you may pass the gpg user and knock sequence as arguments to TariqClient? (see howto use section). 41 | 42 | ### Configuring the Server 43 | After installing the requirements, the first step is to download, unpack, and install Tariq. Tariq can be downloaded from: http://code.google.com/p/tariq/. Once this is done, we need to configure the server. We also need to prepare GnuPG. So you need to create a directory for gnupg using the following commands: 44 | ``` 45 | mkdir /etc/tariq/.server-gpg 46 | chmod 600 /etc/tariq/.server-gpg 47 | ``` 48 | 49 | You need to import and trust the client(s) public key(s): 50 | ``` 51 | gpg --homedir /etc/tariq/.server-gpg --import < client.pub.txt 52 | gpg --homedir /etc/tariq/.server-gpg --edit-key tariq@arabnix.com 53 | ``` 54 | Then select trust (5) 55 | 56 | **Preparing iptables:** 57 | Create an iptables chain to be used by tariq server: 58 | ``` 59 | iptables -P INPUT DROP iptables -N tariq 60 | iptables -A INPUT -j tariq 61 | iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT 62 | ``` 63 | 64 | **Optional:** 65 | you may specify a range of ports to be filtered (dropped) in case you are running normal services on the same box: 66 | ``` 67 | iptables -A INPUT -p tcp -m tcp --dport 1000,65535 -j DROP 68 | iptables -A INPUT -p udp -m udp --dport 1000,65535 -j DROP 69 | iptables -A INPUT -p tcp -m tcp --dport 80 -m state --state NEW -j ACCEPT 70 | ``` 71 | **IMPORTANT NOTE:** Do not use the REJECT target with tariq. 72 | 73 | Now edit 'server.conf' and specify the correct sequence of ports, by using the secret_ports variable. Example: 74 | ``` 75 | secret_ports=10000,7456,22022,12121,10001 76 | ``` 77 | 78 | Now specify the server's gpg path: 79 | ``` 80 | server_gpg_dir=/etc/tariq/.server-gpg 81 | ``` 82 | 83 | Specify the iptables chain name you have created for tariq: 84 | ``` 85 | iptables_chain=tariq 86 | ``` 87 | 88 | Now please adjust the iptables chain name used to open ports for a successful knock: 89 | ``` 90 | open_tcp_port=-A tariq -s {ip} -p tcp -m state --state NEW -m tcp --dport {dport} -j ACCEPT 91 | open_udp_port=-A tariq -s {ip} -p udp -m state --state NEW -m udp --dport {dport} -j ACCEPT 92 | ``` 93 | 94 | --- 95 | ## Howto use Tariq? 96 | To start running tariq server, just run the following command using user root: 97 | ``` 98 | ./TariqServer 99 | ``` 100 | 101 | Now that you have tariq server running, the firewall rules configured on the server, and your profile installed on the client, you're ready to run some commands remotely or open some ports. Using user root, to open, for instance, ssh (22) on the remote server (example.com), all you simply need to do on the client, is run: 102 | ``` 103 | ./TariqCleint -u tariq@arabnix.com example.com O 22 104 | ``` 105 | 106 | If you don't want to open a port but perform a remote command for instance restarting the httpd service on the box, you don't need to login remotely and do it yourself and still working with the default drop firewall. All you simply need to do on the client is run the following command: 107 | ``` 108 | ./TariqCleint -u tariq@arabnix.com example.com E service httpd restart 109 | ``` 110 | 111 | Another example, here I'm sending an echo message to the box: 112 | ``` 113 | ./TariqCleint -u tariq@arabnix.com example.com E echo “Hello, It's me tariq” 114 | ``` 115 | 116 | Finally to close the port you requested to open, all you need to do is: 117 | ``` 118 | ./TariqCleint -u tariq@arabnix.com example.com C 22 119 | ``` 120 | 121 | --- 122 | ### Future Work (aka TODO): 123 | - Make installer (rpm/deb based package) 124 | - Check if client uses a passphrase gpg key 125 | - Make system work as a daemon (write init scripts) 126 | -------------------------------------------------------------------------------- /server-gpg/pubring.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/server-gpg/pubring.gpg -------------------------------------------------------------------------------- /server-gpg/random_seed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/server-gpg/random_seed -------------------------------------------------------------------------------- /server-gpg/secring.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/server-gpg/secring.gpg -------------------------------------------------------------------------------- /server-gpg/trustdb.gpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashemery/tariq/4aa426992fa49ac80aa7ed33715580eb1544028d/server-gpg/trustdb.gpg -------------------------------------------------------------------------------- /server.conf: -------------------------------------------------------------------------------- 1 | # the right sequence of ports, at least 5 unique ports 2 | secret_ports=10000,7456,22022,12121,10001 3 | 4 | # set it to 1-65535 to sniff all ports, you may skip some leading ports 5 | # so that when someone access to http port while knocking it won't be rejected 6 | sniff_range=1000-65535 7 | 8 | # if this is 1 then knocking wrong ports won't reset request, 9 | # only knocking right ports in wrong sequence will do 10 | just_check_sequence=0 11 | 12 | # size in bytes of random blob 13 | # it will be a little bit bigger because it uses base64 14 | min_random_blob_size=25 15 | max_random_blob_size=50 16 | 17 | # server GPG dir 18 | #server_gpg_dir=/etc/tariq/.server-gpg 19 | server_gpg_dir=server-gpg 20 | 21 | # number of working threads 22 | threads_n=3 23 | 24 | # the name of the iptables chain to use 25 | iptables_chain=tariq 26 | 27 | # iptables open port commads 28 | open_tcp_port=-A tariq -s {ip} -p tcp -m state --state NEW -m tcp --dport {dport} -j ACCEPT 29 | open_udp_port=-A tariq -s {ip} -p udp -m state --state NEW -m udp --dport {dport} -j ACCEPT 30 | 31 | --------------------------------------------------------------------------------