├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── api ├── config.php └── satellite.php ├── back ├── demo_decrypt.py ├── satellite.py └── update_vendors.sh ├── config ├── satellite.conf └── version.conf ├── docs ├── CONFIG_FILE.md ├── JSON_DEMO.md ├── NOTIFICATION_MAIL.md └── PROXY_MODE.md ├── install ├── pialert_satellite_install.sh ├── pialert_satellite_uninstall.sh ├── pialert_satellite_update.sh └── satellite.cron ├── log └── satellite.scan.log └── tar ├── create.sh └── pialert_satellite_latest.tar /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: leiweibau 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | back/encrypted_scandata 3 | log/pialert.scan.log 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /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 | # Pi.Alert Satellite 2 | A companion script for [Pi.Alert](https://github.com/leiweibau/Pi.Alert), which executes the Pi.Alert scan on an external host and sends the data as encrypted [JSON](docs/JSON_DEMO.md) to a special API. 3 | 4 | ### The satellite can operate in 1 of 2 different modes 5 | 6 | ![Satellite Modes][Satellite_Modes] 7 | 8 | #### Direct API call: 9 | Here the API of the Pi.Alert instance is called. This API compares the transmitted token with the Pi.Alert database to check whether the token is valid. If this is the case, the encrypted payload is decrypted and processed together with the scans of the Pi.Alert instance. 10 | 11 | #### Indirect API call (proxy mode): 12 | The API is installed on a separate web server. The satellite now transmits the data to the "proxy". This uses a configuration file to check whether it is a valid token and, if so, stores the data in encrypted form. Decryption on the proxy is not possible, as only the satellite and the Pi.Alert instance know the password. For Pi.Alert to retrieve the data, it must also be configured for proxy mode. 13 | 14 | [Prepare PROXY_MODE](docs/PROXY_MODE.md) 15 | 16 | ### Scan Methods 17 | 18 | - **arp-scan**. The arp-scan system utility is used to search for devices on the network using arp frames. 19 | - **Fritzbox**. If you use a Fritzbox (a router from the company "AVM"), it is possible to perform a query of the active hosts. This also includes hosts of the guest WLAN and Powerline devices from "AVM". 20 | - **Mikrotik**. If you use Mikrotik Router as DHCP server, it is possible to read DHCP leases. 21 | - **UniFi**. If you use UniFi controller, it is possible to read clients (Client Devices) 22 | - **OpenWRT**. If you are using a router based on OpenWRT, you can import the active devices. 23 | - **Pi-hole DNS**. If the Pi-hole v6 DNS server is active, Pi.Alert examines its activity looking for active devices using DNS that have not been detected by other methods. 24 | - **Pi-hole DHCP**. If the Pi-hole v6 DHCP server is active, Pi.Alert examines the DHCP leases (addresses assigned) to find devices that were not discovered by the other methods. 25 | ### Installation 26 | 27 | Initially designed to run on a Debian based Linux distribution. 28 | 29 | 30 | 31 | 32 | 33 | 34 | 40 | 41 |
One-step Automated Install
35 | 36 | ``` 37 | bash -c "$(wget -qLO - https://github.com/leiweibau/Pi.Alert-Satellite/raw/main/install/pialert_satellite_install.sh)" 38 | ``` 39 |
42 | 43 | As an alternative to this installation, you can also click on the blue "i" icon on the right in the line of the corresponding satellite in the Pi.Alert instance after creating a satellite and create the 44 | installation command, which takes care of the important configuration during the installation. 45 | 46 | [Main Config flie parameter](docs/CONFIG_FILE.md) 47 | 48 | | ![Config MainScreen][Config] | ![PreConfig Modal][PreConfig] | 49 | | ---------------------------- | ----------------------------- | 50 | 51 | ### Update 52 | 53 | Initially designed to run on a Debian based Linux distribution. 54 | 55 | 56 | 57 | 58 | 59 | 60 | 66 | 67 |
One-step Automated Update
61 | 62 | ``` 63 | bash -c "$(wget -qLO - https://github.com/leiweibau/Pi.Alert-Satellite/raw/main/install/pialert_satellite_update.sh)" 64 | ``` 65 |
68 | 69 | An archive of older versions can be found at [https://leiweibau.net/archive/pialert-satellite/](https://leiweibau.net/archive/pialert-satellite/). This archive contains all release notes. 70 | 71 | ### Uninstall 72 | 73 | 74 | In the directory "pialert-satellite/install/" there is a script called "pialert_satellite_uninstall.sh". This can be used to delete the cronjob and the "pialert-satellite" directory. 75 | 76 | ### License 77 | GPL 3.0 78 | [Read more here](LICENSE.txt) 79 | 80 | ### Contact 81 | 82 | leiweibau@gmail.com 83 | 84 | 85 | [Config]: https://raw.githubusercontent.com/leiweibau/Pi.Alert/assets/satellite_config.png "Config MainScreen" 86 | [PreConfig]: https://raw.githubusercontent.com/leiweibau/Pi.Alert/assets/satellite_preconfig.png "PreConfig Modal" 87 | [Satellite_Modes]: https://raw.githubusercontent.com/leiweibau/Pi.Alert/assets/Satellite_Modes.png "Satellite Modes" 88 | -------------------------------------------------------------------------------- /api/config.php: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /api/satellite.php: -------------------------------------------------------------------------------- 1 | query($sql_select); 20 | $i = 0; 21 | // Create a nested array 22 | if ($result) { 23 | if ($result->numColumns() > 0) { 24 | while ($row = $result->fetchArray(SQLITE3_ASSOC)) { 25 | $func_satellite_list[$i]['sat_name'] = $row['sat_name']; 26 | $func_satellite_list[$i]['sat_token'] = $row['sat_token']; 27 | $func_satellite_list[$i]['sat_password'] = $row['sat_password']; 28 | $i++; 29 | } 30 | } 31 | } 32 | $db->close(); 33 | return $func_satellite_list; 34 | } 35 | // JSON Response 36 | function json_response($status_code, $api_message) { 37 | header('Content-Type: application/json'); 38 | $response = array("status" => "$status_code", "message" => "$api_message"); 39 | echo json_encode($response); 40 | } 41 | function purge_old_results() { 42 | $directory = '../satellites'; 43 | $files = scandir($directory); 44 | $currentTime = time(); 45 | $ageLimit = 590; // 9 minutes 50 seconds 46 | 47 | foreach ($files as $file) { 48 | $filePath = $directory . '/' . $file; 49 | 50 | if ($file === 'readme' || $file === 'readme.txt') { 51 | continue; 52 | } 53 | 54 | if (is_file($filePath)) { 55 | $fileModificationTime = filemtime($filePath); 56 | if ($currentTime - $fileModificationTime > $ageLimit) { 57 | unlink($filePath); 58 | } 59 | } 60 | } 61 | } 62 | 63 | $http_response = ' 64 | 65 | 404 Not Found 66 | 67 |

Not Found

68 |

The requested URL was not found on this server.

69 | '; 70 | 71 | // Check whether mode or token is set, otherwise HTTP 404 72 | if ($_REQUEST['mode'] == "" || $_REQUEST['token'] == "") { 73 | header('HTTP/1.0 404 Not Found', true, 404); 74 | echo $http_response; 75 | die(); 76 | } 77 | // Check if payload is set when usingg direct or proxy mode, otherwise HTTP 404 78 | if (($_REQUEST['mode'] == "direct" || $_REQUEST['mode'] == "proxy") && !isset($_FILES['encrypted_data'])) { 79 | header('HTTP/1.0 404 Not Found', true, 404); 80 | echo $http_response; 81 | die(); 82 | } 83 | 84 | $incomming_token = $_REQUEST['token']; 85 | 86 | // Procedure for direct API call (Pi.Alert) 87 | if ($_REQUEST['mode'] == "direct") { 88 | // Query from the database 89 | $satellite_list = get_all_satellites(); 90 | $satellite_tokens = array(); 91 | $satellite_passwords = array(); 92 | 93 | for($x=0;$x 198 | -------------------------------------------------------------------------------- /back/demo_decrypt.py: -------------------------------------------------------------------------------- 1 | import subprocess, json 2 | 3 | password = "password" # Hier das tatsächliche Passwort einfügen 4 | 5 | openssl_command = [ 6 | "openssl", "enc", "-d", "-aes-256-cbc", "-in", "encrypted_scandata", 7 | "-pbkdf2", "-pass", "pass:{}".format(password) 8 | ] 9 | 10 | with subprocess.Popen(openssl_command, stdout=subprocess.PIPE) as proc: 11 | decrypted_data = proc.stdout.read() 12 | 13 | decrypted_dict = json.loads(decrypted_data.decode('utf-8')) 14 | 15 | with open('decrypted.json', 'w') as outfile: 16 | json.dump(decrypted_dict, outfile, indent=4) 17 | 18 | print(decrypted_dict) 19 | -------------------------------------------------------------------------------- /back/satellite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | #------------------------------------------------------------------------------- 4 | # Pi.Alert Satellite 5 | #------------------------------------------------------------------------------- 6 | # Puche 2021 GNU GPLv3 7 | # leiweibau 2024+ GNU GPLv3 8 | #------------------------------------------------------------------------------- 9 | 10 | #=============================================================================== 11 | # IMPORTS 12 | #=============================================================================== 13 | from __future__ import print_function 14 | from email.mime.multipart import MIMEMultipart 15 | from email.mime.text import MIMEText 16 | from email.mime.base import MIMEBase 17 | from email import encoders 18 | from requests.packages.urllib3.exceptions import InsecureRequestWarning 19 | from mac_vendor_lookup import MacLookup 20 | from time import sleep, time, strftime, monotonic 21 | from base64 import b64encode 22 | from urllib.parse import urlparse 23 | from cryptography import x509 24 | from cryptography.hazmat.backends import default_backend 25 | from pathlib import Path 26 | from datetime import datetime 27 | import sys, subprocess, os, re, datetime, socket, io, requests, time, pwd, glob, ipaddress, ssl, json, cpuinfo, platform, smtplib, psutil, tzlocal 28 | 29 | #=============================================================================== 30 | # CONFIG CONSTANTS 31 | #=============================================================================== 32 | SATELLITE_BACK_PATH = os.path.dirname(os.path.abspath(__file__)) 33 | SATELLITE_PATH = SATELLITE_BACK_PATH + "/.." 34 | SATELLITE_LOG_PATH = SATELLITE_PATH + "/log" 35 | STATUS_FILE_SCAN = SATELLITE_BACK_PATH + "/.scanning" 36 | STATUS_FILE_BACKUP = SATELLITE_BACK_PATH + "/.backup" 37 | STATUS_FILE_REPORTED = SATELLITE_BACK_PATH + "/.reported" 38 | 39 | PIHOLE6_SES_VALID = "" 40 | PIHOLE6_SES_SID = "" 41 | PIHOLE6_SES_CSRF = "" 42 | 43 | if (sys.version_info > (3,0)): 44 | exec(open(SATELLITE_PATH + "/config/version.conf").read()) 45 | exec(open(SATELLITE_PATH + "/config/satellite.conf").read()) 46 | else: 47 | execfile(SATELLITE_PATH + "/config/version.conf") 48 | execfile(SATELLITE_PATH + "/config/satellite.conf") 49 | 50 | #=============================================================================== 51 | # MAIN 52 | #=============================================================================== 53 | def main(): 54 | global startTime 55 | global cycle 56 | global log_timestamp 57 | global report_timestamp 58 | 59 | # Header 60 | print('\nPi.Alert Satellite v'+ VERSION_DATE) 61 | print('---------------------------------------------------------') 62 | print(f"Executing user: {get_username()}\n") 63 | 64 | # Initialize global variables 65 | log_timestamp = datetime.datetime.now() 66 | report_timestamp = len(datetime.datetime.now().strftime('%Y%m%d_%H%M%S')) 67 | 68 | # Timestamp 69 | startTime = datetime.datetime.now() 70 | startTime = startTime.replace (second=0, microsecond=0) 71 | 72 | # Check parameters 73 | if len(sys.argv) != 2 : 74 | print('usage satelite scan | internet_IP | update_vendors | email_test' ) 75 | return 76 | cycle = str(sys.argv[1]) 77 | 78 | # internet_IP currently not used 79 | if cycle == 'update_vendors': 80 | res = update_devices_MAC_vendors() 81 | elif cycle == 'update_vendors_silent': 82 | res = update_devices_MAC_vendors('-s') 83 | elif cycle == 'scan': 84 | res = scan_network() 85 | elif cycle == 'email_test': 86 | res = mail_notification('Test') 87 | else: 88 | print('usage satelite scan | internet_IP | update_vendors | email_test' ) 89 | return 90 | 91 | # Remove scan status file created in scan_network() 92 | if cycle not in ['internet_IP' 'update_vendors', 'update_vendors_silent'] and os.path.exists(STATUS_FILE_SCAN): 93 | os.remove(STATUS_FILE_SCAN) 94 | 95 | # Final menssage 96 | print('\nDONE!!!\n\n') 97 | return 0 98 | 99 | #=============================================================================== 100 | # Set Env (Userpermissions DB-file) 101 | #=============================================================================== 102 | def get_username(): 103 | return pwd.getpwuid(os.getuid())[0] 104 | 105 | #=============================================================================== 106 | # Satellite Scan 107 | #=============================================================================== 108 | def check_internet_IP(): 109 | # Header 110 | print(' Retrieving Internet IP...') 111 | internet_IP = get_internet_IP() 112 | 113 | # Check result = IP 114 | if internet_IP == "" : 115 | print(' Error retrieving Internet IP') 116 | print(' Exiting...\n') 117 | return 1 118 | 119 | print(' ', internet_IP) 120 | 121 | internet_detection = [] 122 | internet_scan = { 123 | "mac": "Internet - " + SATELLITE_TOKEN, 124 | "ip": internet_IP 125 | } 126 | 127 | internet_detection.append(internet_scan) 128 | 129 | return internet_detection 130 | 131 | # ------------------------------------------------------------------------------ 132 | def parse_cron_part(cron_part, current_value, cron_min_value, cron_max_value): 133 | if cron_part == '*': 134 | return set(range(cron_min_value, cron_max_value)) 135 | elif '/' in cron_part: 136 | step = int(cron_part.split('/')[1]) 137 | return set(range(cron_min_value, cron_max_value, step)) 138 | elif '-' in cron_part: 139 | start, end = map(int, cron_part.split('-')) 140 | return set(range(start, end + 1)) 141 | elif ',' in cron_part: 142 | values = cron_part.split(',') 143 | return set(int(value) for value in values) 144 | else: 145 | return {int(cron_part)} 146 | 147 | #------------------------------------------------------------------------------- 148 | def get_internet_IP(): 149 | curl_args = ['curl', '-s', QUERY_MYIP_SERVER] 150 | # cmd_output = subprocess.check_output (curl_args, universal_newlines=True) 151 | # return check_IP_format (cmd_output) 152 | try: 153 | cmd_output = subprocess.check_output(curl_args, universal_newlines=True) 154 | return check_IP_format(cmd_output) 155 | except subprocess.CalledProcessError as e: 156 | return None 157 | 158 | #------------------------------------------------------------------------------- 159 | def check_IP_format(pIP): 160 | # Check IP format 161 | IPv4SEG = r'(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])' 162 | IPv4ADDR = r'(?:(?:' + IPv4SEG + r'\.){3,3}' + IPv4SEG + r')' 163 | IP = re.search(IPv4ADDR, pIP) 164 | # Return error if not IP 165 | if IP is None : 166 | return "" 167 | return IP.group(0) 168 | 169 | #------------------------------------------------------------------------------- 170 | def update_devices_MAC_vendors (pArg = ''): 171 | print('Update HW Vendors') 172 | print(' Timestamp:', startTime ) 173 | 174 | # Update vendors DB (oui) 175 | print('\nUpdating vendors DB...') 176 | update_args = ['sh', SATELLITE_BACK_PATH + '/update_vendors.sh', pArg] 177 | update_output = subprocess.check_output (update_args) 178 | 179 | # mac-vendor-lookup update 180 | try: 181 | print('\nTry build in mac-vendor-lookup update') 182 | mac = MacLookup() 183 | mac.update_vendors() 184 | print(' Update successful') 185 | except: 186 | print('\nFallback') 187 | print(' Backup old mac-vendors.txt for mac-vendor-lookup') 188 | p = subprocess.call(["cp $HOME/.cache/mac-vendors.txt $HOME/.cache/mac-vendors.bak"], shell=True) 189 | print(' Create mac-vendors.txt for mac-vendor-lookup') 190 | p = subprocess.call(["/usr/bin/sed -e 's/\t/:/g' -e 's/ü/ü/g' -e 's/ö/ö/g' -e 's/ä/ä/g' -e 's/ó/ó/g' -e 's/é/é/g' -e 's/â/–/g' -e 's/Â//g' -e '/^#/d' /usr/share/arp-scan/ieee-oui.txt > $HOME/.cache/mac-vendors.txt"], shell=True) 191 | 192 | #------------------------------------------------------------------------------- 193 | def query_MAC_vendor(pMAC): 194 | try : 195 | pMACstr = str(pMAC) 196 | 197 | # Check MAC parameter 198 | mac = pMACstr.replace (':','') 199 | if len(pMACstr) != 17 or len(mac) != 12 : 200 | return -2 201 | 202 | # Search vendor in HW Vendors DB 203 | mac = mac[0:6] 204 | grep_args = ['grep', '-i', mac, VENDORS_DB] 205 | grep_output = subprocess.check_output (grep_args) 206 | 207 | # Return Vendor 208 | vendor = grep_output[7:] 209 | return vendor.rstrip() 210 | 211 | # not Found 212 | except subprocess.CalledProcessError : 213 | return -1 214 | 215 | #------------------------------------------------------------------------------- 216 | def scan_network(): 217 | global PIHOLE6_SES_VALID 218 | # Header 219 | print('Scan Devices') 220 | print(' Timestamp:', startTime ) 221 | print('\nCheck Internet Connectivity...') 222 | internet_detection = check_internet_IP() 223 | # arp-scan command 224 | print('\nScanning...') 225 | # arp-scan 226 | print_log ('arp-scan starts...') 227 | arpscan_devices = execute_arpscan() 228 | print_log ('Pi-hole copy starts...') 229 | pihole_network = copy_pihole_network() 230 | print_log ('Pi-hole DHCP copy starts...') 231 | pihole_dhcp = read_DHCP_leases() 232 | if PIHOLE6_SES_VALID==True: 233 | pihole_six_api_deauth() 234 | # Fritzbox 235 | print_log ('Fritzbox copy starts...') 236 | fritzbox_network = read_fritzbox_active_hosts() 237 | # Mikrotik 238 | print_log ('Mikrotik copy starts...') 239 | mikrotik_network = read_mikrotik_leases() 240 | # UniFi 241 | print_log ('UniFi copy starts...') 242 | unifi_network = read_unifi_clients() 243 | # OpenWRT 244 | print_log ('OpenWRT copy starts...') 245 | openwrt_network = read_openwrt_clients() 246 | print('\nProcessing scan results...') 247 | print(' Create json of scanned devices') 248 | jsondata = save_scanned_devices (internet_detection, arpscan_devices, fritzbox_network, mikrotik_network, unifi_network, openwrt_network, pihole_network, pihole_dhcp) 249 | print(' Encrypt data and transmit to Master or Proxy') 250 | encrypt_submit_scandata(jsondata) 251 | mail_notification("scan") 252 | 253 | return 0 254 | 255 | #------------------------------------------------------------------------------- 256 | def copy_pihole_network(): 257 | # check if Pi-hole is active 258 | if not PIHOLE_ACTIVE : 259 | return 260 | 261 | 262 | print(' Pi-hole Method...') 263 | pihole_six_api_auth() 264 | pihole_network = copy_pihole_network_six() 265 | return pihole_network 266 | 267 | #------------------------------------------------------------------------------- 268 | def pihole_six_api_auth(): 269 | global PIHOLE6_URL 270 | global PIHOLE6_PASSWORD 271 | global PIHOLE6_SES_VALID 272 | global PIHOLE6_SES_SID 273 | global PIHOLE6_SES_CSRF 274 | 275 | if not PIHOLE6_URL : 276 | print(' ...Skipped (Config Error)') 277 | return 278 | 279 | if not PIHOLE6_URL.endswith('/'): 280 | PIHOLE6_URL += '/' 281 | 282 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 283 | headers = { 284 | "accept": "application/json", 285 | "content-type": "application/json", 286 | "User-Agent": "Pi.Alert/"+ VERSION_DATE 287 | } 288 | data = { 289 | "password": PIHOLE6_PASSWORD 290 | } 291 | try: 292 | response = requests.post(PIHOLE6_URL+'api/auth', headers=headers, json=data, verify=False, timeout=15) 293 | except requests.exceptions.Timeout: 294 | print(f" Request timed out after 15 seconds") 295 | return 296 | except requests.exceptions.ConnectionError as e: 297 | print(f" Connection error occurred") 298 | return 299 | except Exception as e: 300 | print(f" An unexpected error occurred") 301 | return 302 | 303 | response_json = response.json() 304 | 305 | try: 306 | session_data = response_json.get('session', {}) 307 | if session_data.get('valid', False): # Standardwert False, falls 'valid' fehlt 308 | PIHOLE6_SES_VALID = session_data['valid'] 309 | PIHOLE6_SES_SID = session_data['sid'] 310 | # to prevent key error if pihole has no password 311 | if PIHOLE6_PASSWORD: 312 | PIHOLE6_SES_CSRF = session_data['csrf'] 313 | else: 314 | print(" Auth required") 315 | return 316 | except KeyError as e: 317 | print(f" Invalid response. Check Pi-hole URL") 318 | return 319 | 320 | #------------------------------------------------------------------------------- 321 | def pihole_six_api_deauth(): 322 | global PIHOLE6_URL 323 | global PIHOLE6_SES_VALID 324 | global PIHOLE6_SES_SID 325 | global PIHOLE6_SES_CSRF 326 | 327 | if not PIHOLE6_URL.endswith('/'): 328 | PIHOLE6_URL += '/' 329 | 330 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 331 | headers = { 332 | "X-FTL-SID": PIHOLE6_SES_SID 333 | } 334 | try: 335 | response = requests.delete(PIHOLE6_URL+'api/auth', headers=headers, verify=False, timeout=15) 336 | except requests.exceptions.Timeout: 337 | print(f" Request timed out after 15 seconds") 338 | return 339 | except requests.exceptions.ConnectionError as e: 340 | print(f" Connection error occurred") 341 | return 342 | except Exception as e: 343 | print(f" An unexpected error occurred") 344 | return 345 | 346 | #print(" Pi-hole Logout") 347 | 348 | #------------------------------------------------------------------------------- 349 | def copy_pihole_network_six(): 350 | global PIHOLE6_URL 351 | global PIHOLE6_SES_VALID 352 | global PIHOLE6_SES_SID 353 | global PIHOLE6_SES_CSRF 354 | global PIHOLE6_API_MAXCLIENTS 355 | 356 | if PIHOLE6_SES_VALID == True: 357 | headers = { 358 | "X-FTL-SID": PIHOLE6_SES_SID, 359 | "X-FTL-CSRF": PIHOLE6_SES_CSRF 360 | } 361 | #max_addresses=2 IPs per host 362 | raw_deviceslist = requests.get(PIHOLE6_URL+'api/network/devices?max_devices=' + str(PIHOLE6_API_MAXCLIENTS) + '&max_addresses=2', headers=headers, verify=False) 363 | deviceslist = raw_deviceslist.json() 364 | pihole_network = [] 365 | 366 | # If pi-hole is outside the local Pi.Alert network and cannot be found with arp. 367 | interfaces = get_pihole_interface_data() 368 | 369 | actual_timestamp = int(time.time()) 370 | 371 | for device in deviceslist['devices']: 372 | hwaddr = device['hwaddr'] 373 | lastQuery = device['lastQuery'] 374 | macVendor = device['macVendor'] 375 | 376 | # skip lo interface 377 | if hwaddr == "00:00:00:00:00:00": 378 | continue 379 | 380 | for ip_info in device['ips']: 381 | ip = ip_info['ip'] 382 | name = ip_info['name'] if ip_info['name'] not in [None, ""] else "(unknown)" 383 | 384 | # Check whether the IP could be a IPv4 address 385 | if '.' in ip: 386 | # Change the “lastQuery” variable to mark the Pi-hole host as “active” 387 | for mac, localips in interfaces.items(): 388 | if ip in localips: 389 | lastQuery = str(int(datetime.datetime.now().timestamp())) 390 | 391 | # Compare the last request with the current time to filter the active hosts 392 | if int(lastQuery) > actual_timestamp-300: 393 | pihole_scan = { 394 | "mac": hwaddr, 395 | "ip": ip, 396 | "hostname": name, 397 | "vendor": macVendor 398 | } 399 | pihole_network.append(pihole_scan) 400 | 401 | return pihole_network 402 | else: 403 | print(f" ...Skipped") 404 | return 405 | 406 | #------------------------------------------------------------------------------- 407 | def read_DHCP_leases(): 408 | # check DHCP Leases is active 409 | if not PIHOLE_DHCP_ACTIVE : 410 | return 411 | 412 | print(f" Pi-hole DHCP Leases Method...") 413 | 414 | if not PIHOLE6_SES_VALID == True: 415 | pihole_six_api_auth() 416 | pihole_dhcp = read_DHCP_leases_six() 417 | 418 | return pihole_dhcp 419 | 420 | #------------------------------------------------------------------------------- 421 | def read_DHCP_leases_six(): 422 | global PIHOLE6_URL 423 | global PIHOLE6_PASSWORD 424 | global PIHOLE6_SES_VALID 425 | global PIHOLE6_SES_SID 426 | global PIHOLE6_SES_CSRF 427 | 428 | if PIHOLE6_SES_VALID == True: 429 | 430 | headers = { 431 | "X-FTL-SID": PIHOLE6_SES_SID, 432 | "X-FTL-CSRF": PIHOLE6_SES_CSRF 433 | } 434 | raw_deviceslist = requests.get(PIHOLE6_URL+'api/dhcp/leases', headers=headers, verify=False) 435 | deviceslist = raw_deviceslist.json() 436 | pihole_dhcp = [] 437 | 438 | # Get Pi-hole local MAC-Adresses an IPs 439 | interfaces = get_pihole_interface_data() 440 | # Generate a theoretical lease period of +30min 441 | current_time = datetime.datetime.now() 442 | future_time = current_time + datetime.timedelta(minutes=30) 443 | dnsmasq_timestamp = int(future_time.timestamp()) 444 | 445 | for device in deviceslist['leases']: 446 | # skip lo interface if present 447 | if device['hwaddr'] == "00:00:00:00:00:00": 448 | continue 449 | 450 | pihole_scan = { 451 | "expires": device['expires'], 452 | "mac": device['hwaddr'], 453 | "ip": device['ip'], 454 | "hostname": device['name'] 455 | } 456 | pihole_dhcp.append(pihole_scan) 457 | 458 | 459 | # pihole_scan = { 460 | # "expires": 234442221, 461 | # "mac": 'ww:ww:rr:11:11:22', 462 | # "ip": '22.55.33.11', 463 | # "hostname": 'DemoHost' 464 | # } 465 | # pihole_dhcp.append(pihole_scan) 466 | 467 | return pihole_dhcp 468 | 469 | else: 470 | print(f" ...Skipped") 471 | return 472 | 473 | #------------------------------------------------------------------------------- 474 | def get_pihole_interface_data(): 475 | global PIHOLE6_URL 476 | global PIHOLE6_SES_VALID 477 | global PIHOLE6_SES_SID 478 | global PIHOLE6_SES_CSRF 479 | 480 | if PIHOLE6_SES_VALID == True: 481 | headers = { 482 | "X-FTL-SID": PIHOLE6_SES_SID, 483 | "X-FTL-CSRF": PIHOLE6_SES_CSRF 484 | } 485 | raw_interfacelist = requests.get(PIHOLE6_URL+'api/network/interfaces', headers=headers, verify=False) 486 | data = raw_interfacelist.json() 487 | result = {} 488 | 489 | for interface in data['interfaces']: 490 | mac_address = interface.get('address') 491 | 492 | if mac_address == "00:00:00:00:00:00": 493 | continue 494 | 495 | if 'addresses' in interface: 496 | ips = [addr['address'] for addr in interface['addresses'] if addr['family'] == 'inet'] 497 | if mac_address and ips: 498 | result[mac_address] = ips 499 | 500 | return result 501 | 502 | #------------------------------------------------------------------------------- 503 | def sorted_alphanumeric(data): 504 | convert = lambda text: int(text) if text.isdigit() else text.lower() 505 | alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 506 | return sorted(data, key=alphanum_key) 507 | 508 | #------------------------------------------------------------------------------- 509 | def execute_arpscan(): 510 | 511 | # check if arp-scan is active 512 | try: 513 | module_arpscan_status = ARPSCAN_ACTIVE 514 | except NameError: 515 | module_arpscan_status = True 516 | if not module_arpscan_status : 517 | unique_devices = [] 518 | return unique_devices 519 | 520 | print(' arp-scan Method...') 521 | 522 | # output of possible multiple interfaces 523 | arpscan_output = "" 524 | 525 | # multiple interfaces 526 | if type(SCAN_SUBNETS) is list: 527 | print(" arp-scan: Multiple interfaces") 528 | for interface in SCAN_SUBNETS : 529 | arpscan_output += execute_arpscan_on_interface (interface) 530 | # one interface only 531 | else: 532 | print(" arp-scan: One interface") 533 | arpscan_output += execute_arpscan_on_interface (SCAN_SUBNETS) 534 | 535 | # Search IP + MAC + Vendor as regular expresion 536 | re_ip = r'(?P((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))' 537 | re_mac = r'(?P([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2}))' 538 | re_hw = r'(?P.*)' 539 | re_pattern = re.compile(r'' + re_ip + r'\s+' + re_mac + r'\s' + re_hw) 540 | 541 | # Create Userdict of devices 542 | devices_list = [device.groupdict() 543 | for device in re.finditer (re_pattern, arpscan_output)] 544 | 545 | # Delete duplicate MAC 546 | unique_mac = [] 547 | unique_devices = [] 548 | 549 | for device in devices_list: 550 | if device['mac'] not in unique_mac: 551 | unique_mac.append(device['mac']) 552 | unique_devices.append(device) 553 | 554 | return unique_devices 555 | 556 | #------------------------------------------------------------------------------- 557 | def execute_arpscan_on_interface(SCAN_SUBNETS): 558 | # Prepare command arguments 559 | subnets = SCAN_SUBNETS.strip().split() 560 | # Retry is 3 to avoid false offline devices 561 | arpscan_args = ['sudo', 'arp-scan', '--ignoredups', '--bandwidth=256k', '--retry=6'] + subnets 562 | 563 | # Execute command 564 | try: 565 | # try runnning a subprocess 566 | result = subprocess.check_output (arpscan_args, universal_newlines=True) 567 | except subprocess.CalledProcessError as e: 568 | # An error occured, handle it 569 | print(e.output) 570 | result = "" 571 | 572 | return result 573 | 574 | #------------------------------------------------------------------------------- 575 | def read_fritzbox_active_hosts(): 576 | 577 | if not FRITZBOX_ACTIVE : 578 | return 579 | 580 | print(' Fritzbox Method...') 581 | 582 | fritzbox_network = [] 583 | 584 | try: 585 | from fritzconnection.lib.fritzhosts import FritzHosts 586 | except: 587 | print(' Missing python package') 588 | return fritzbox_network 589 | 590 | # copy Fritzbox Network list 591 | fh = FritzHosts(address=FRITZBOX_IP, user=FRITZBOX_USER, password=FRITZBOX_PASS) 592 | hosts = fh.get_hosts_info() 593 | for index, host in enumerate(hosts, start=1): 594 | if host['status'] : 595 | # status = 'active' if host['status'] else '-' 596 | ip = host['ip'] if host['ip'] else 'no IP' 597 | mac = host['mac'].lower() if host['mac'] else '-' 598 | hostname = host['name'] 599 | try: 600 | vendor = MacLookup().lookup(host['mac']) 601 | except: 602 | vendor = "Prefix is not registered" 603 | 604 | fritzbox_scan = { 605 | "mac": mac, 606 | "ip": ip, 607 | "hostname": hostname, 608 | "vendor": vendor 609 | } 610 | fritzbox_network.append(fritzbox_scan) 611 | return fritzbox_network 612 | 613 | #------------------------------------------------------------------------------- 614 | def read_mikrotik_leases(): 615 | 616 | if not MIKROTIK_ACTIVE: 617 | return 618 | 619 | print(' Mikrotik Method...') 620 | 621 | mikrotik_network = [] 622 | 623 | try: 624 | import routeros_api 625 | except: 626 | print(' Missing python package') 627 | return mikrotik_network 628 | 629 | data = [] 630 | conn = routeros_api.RouterOsApiPool(MIKROTIK_IP, MIKROTIK_USER, MIKROTIK_PASS, plaintext_login=True) 631 | api = conn.get_api() 632 | ret = api.get_resource('/ip/dhcp-server/lease').get() 633 | conn.disconnect() 634 | for row in ret: 635 | if 'active-mac-address' in row: 636 | mac = row['active-mac-address'].lower() 637 | ip = row['active-address'] 638 | hostname = row.get('host-name','') 639 | try: 640 | vendor = MacLookup().lookup(mac) 641 | except: 642 | vendor = "Prefix is not registered" 643 | 644 | mikrotik_scan = { 645 | "mac": mac, 646 | "ip": ip, 647 | "hostname": hostname, 648 | "vendor": vendor 649 | } 650 | 651 | mikrotik_network.append(mikrotik_scan) 652 | 653 | return mikrotik_network 654 | 655 | #------------------------------------------------------------------------------- 656 | def read_unifi_clients(): 657 | 658 | if not UNIFI_ACTIVE: 659 | return 660 | 661 | print(' UniFi Method...') 662 | 663 | unifi_network = [] 664 | 665 | try: 666 | from pyunifi.controller import Controller 667 | except: 668 | print(' Missing python package') 669 | return unifi_network 670 | 671 | # Enable self signed SSL / no warnings 672 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 673 | 674 | try: 675 | UNIFI_API_VERSION = UNIFI_API 676 | except NameError: # variable not defined, use a default 677 | UNIFI_API_VERSION = 'v5' 678 | 679 | try: 680 | data = [] 681 | c = Controller(UNIFI_IP,UNIFI_USER,UNIFI_PASS,8443,UNIFI_API_VERSION,'default',ssl_verify=False) 682 | clients = c.get_clients() 683 | for row in clients: 684 | mac = row['mac'].lower() 685 | ip = row.get('ip','no IP') 686 | hostname = row.get('hostname',row.get('name','')) 687 | vendor = row.get('oui',None) 688 | if not vendor: 689 | try: 690 | vendor = MacLookup().lookup(mac) 691 | except: 692 | vendor = "Prefix is not registered" 693 | 694 | unifi_scan = { 695 | "mac": mac, 696 | "ip": ip, 697 | "hostname": hostname, 698 | "vendor": vendor 699 | } 700 | 701 | unifi_network.append(unifi_scan) 702 | 703 | except Exception as e: 704 | print(' Could not connect to UniFi Controller') 705 | 706 | return unifi_network 707 | 708 | #------------------------------------------------------------------------------- 709 | def read_openwrt_clients(): 710 | 711 | if not OPENWRT_ACTIVE: 712 | return 713 | 714 | print(' OpenWRT Method...') 715 | 716 | openwrt_network = [] 717 | 718 | try: 719 | from openwrt_luci_rpc import OpenWrtRpc 720 | except: 721 | print(' Missing python package') 722 | return openwrt_network 723 | 724 | # Enable self signed SSL / no warnings 725 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 726 | 727 | try: 728 | escaped_password = repr(OPENWRT_PASS)[1:-1] 729 | 730 | router = OpenWrtRpc(str(OPENWRT_IP), str(OPENWRT_USER), escaped_password) 731 | result = router.get_all_connected_devices(only_reachable=True) 732 | 733 | for device in result: 734 | if str(device.hostname) == 'None': 735 | hostname = resolve_device_name(device.mac,device.ip) 736 | else: 737 | hostname = device.hostname 738 | 739 | device_data = { 740 | "mac": device.mac.lower(), 741 | "hostname": hostname, 742 | "ip": device.ip, 743 | "vendor": "(unknown)" 744 | } 745 | openwrt_network.append(device_data) 746 | 747 | except Exception as e: 748 | print(f' Could not connect to OpenWRT: {e}') 749 | 750 | return openwrt_network 751 | 752 | #------------------------------------------------------------------------------- 753 | def resolve_device_name_netbios(pIP): 754 | try: 755 | nbtscan_args =['nbtscan', '-v', '-s', ':', pIP+'/32'] 756 | newName = subprocess.run(nbtscan_args, capture_output=True, text=True, timeout=5) 757 | if newName.returncode == 0 and newName.stdout: 758 | lines = newName.stdout.strip().split('\n') 759 | for line in lines: 760 | if "00U" in line: 761 | segments = line.split(':') 762 | newName = segments[1].strip() 763 | else: 764 | newName = "" 765 | return newName 766 | # Error handling 767 | except subprocess.TimeoutExpired: 768 | newName = "" 769 | return newName 770 | 771 | #------------------------------------------------------------------------------- 772 | def resolve_device_name_avahi(pIP): 773 | try: 774 | avahi_args = ['avahi-resolve', '-a', pIP] 775 | newName = subprocess.run(avahi_args, capture_output=True, text=True, timeout=5) 776 | if newName.returncode == 0 and newName.stdout: 777 | ip_regex = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b') 778 | newName = re.sub(ip_regex, '', newName.stdout) 779 | else: 780 | newName = "" 781 | return newName.strip() 782 | # Error handling 783 | except subprocess.TimeoutExpired: 784 | newName = "" 785 | return newName 786 | except subprocess.CalledProcessError: 787 | newName = "" 788 | return newName 789 | 790 | #------------------------------------------------------------------------------- 791 | def resolve_device_name_dig(pIP): 792 | # DNS Server Fallback 793 | try: 794 | dnsserver = NETWORK_DNS_SERVER 795 | except NameError: 796 | dnsserver = "localhost" 797 | 798 | try: 799 | dig_args = ['dig', '+short', '-x', pIP, '@'+dnsserver] 800 | newName = subprocess.check_output (dig_args, universal_newlines=True, timeout=5) 801 | if ";; communications error to" in newName: 802 | newName = "" 803 | return newName.strip() 804 | # Error handling 805 | except subprocess.TimeoutExpired: 806 | newName = "" 807 | return newName 808 | except subprocess.CalledProcessError: 809 | newName = "" 810 | return newName 811 | 812 | #------------------------------------------------------------------------------- 813 | def resolve_device_name(pMAC, pIP): 814 | pMACstr = str(pMAC) 815 | 816 | # Check MAC parameter 817 | mac = pMACstr.replace (':','') 818 | if len(pMACstr) != 17 or len(mac) != 12 : 819 | return -2 820 | 821 | newName = resolve_device_name_avahi(pIP) 822 | if newName == "": 823 | newName = resolve_device_name_dig(pIP) 824 | if newName == "": 825 | newName = resolve_device_name_netbios(pIP) 826 | 827 | # Check returns 828 | newName = newName.strip() 829 | if len(newName) == 0 : 830 | newName = "(satellite network client)" 831 | 832 | # Eliminate local domain 833 | suffixes = ['.', '.lan', '.local', '.home'] 834 | 835 | for suffix in suffixes: 836 | if newName.endswith(suffix): 837 | newName = newName[:-len(suffix)] 838 | break 839 | 840 | return newName 841 | 842 | #------------------------------------------------------------------------------- 843 | def process_devices(network, scan_method, all_devices): 844 | if network: 845 | for device in network: 846 | if len(device['mac']) > 12: 847 | device_data = { 848 | 'cur_MAC': device['mac'], 849 | 'cur_IP': device['ip'], 850 | 'cur_hostname': device['hostname'], 851 | 'cur_Vendor': device['vendor'], 852 | 'cur_ScanMethod': scan_method, 853 | 'cur_SatelliteID': SATELLITE_TOKEN 854 | } 855 | all_devices.append(device_data) 856 | 857 | #------------------------------------------------------------------------------- 858 | def save_scanned_devices(p_internet_detection, p_arpscan_devices, p_fritzbox_network, p_mikrotik_network, p_unifi_network, p_openwrt_network, p_pihole_network, p_pihole_dhcp): 859 | 860 | all_devices = [] 861 | # Internet Check 862 | if bool(p_internet_detection): 863 | for device in p_internet_detection: 864 | if len(device['mac']) > 12: 865 | device_data = { 866 | 'cur_MAC': device['mac'], 867 | 'cur_IP': device['ip'], 868 | 'cur_Vendor': "", 869 | 'cur_ScanMethod': 'Internet Check', 870 | 'cur_SatelliteID': SATELLITE_TOKEN 871 | } 872 | all_devices.append(device_data) 873 | 874 | # Fritz!Box 875 | process_devices(p_fritzbox_network, 'Fritzbox', all_devices) 876 | # Mikrotik 877 | process_devices(p_mikrotik_network, 'Mikrotik', all_devices) 878 | # UniFi 879 | process_devices(p_unifi_network, 'UniFi', all_devices) 880 | # OpenWRT 881 | process_devices(p_openwrt_network, 'OpenWRT', all_devices) 882 | # Pihole Network 883 | process_devices(p_pihole_network, 'Pi-hole', all_devices) 884 | # Pihole Network 885 | if bool(p_pihole_dhcp): 886 | for device in p_pihole_dhcp: 887 | if len(device['mac']) > 12: 888 | device_data = { 889 | 'cur_expires': device['expires'], 890 | 'cur_hwaddr': device['mac'], 891 | 'cur_ip': device['ip'], 892 | 'cur_name': device['hostname'], 893 | 'cur_clientid': '*', 894 | 'cur_ScanMethod': 'Pi-hole DHCP', 895 | 'cur_SatelliteID': SATELLITE_TOKEN 896 | } 897 | all_devices.append(device_data) 898 | 899 | # Arpscan 900 | if bool(p_arpscan_devices): 901 | for device in p_arpscan_devices: 902 | if len(device['mac']) > 12: 903 | device_data = { 904 | 'cur_MAC': device['mac'], 905 | 'cur_IP': device['ip'], 906 | 'cur_hostname': resolve_device_name(device['mac'],device['ip']), 907 | 'cur_Vendor': device['hw'], 908 | 'cur_ScanMethod': 'arp-scan', 909 | 'cur_SatelliteID': SATELLITE_TOKEN 910 | } 911 | all_devices.append(device_data) 912 | 913 | # Get Satellite MAC 914 | local_mac_cmd = ["/sbin/ifconfig `ip -o route get 1 | sed 's/^.*dev \\([^ ]*\\).*$/\\1/;q'` | grep ether | awk '{print $2}'"] 915 | local_mac = subprocess.Popen (local_mac_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0].decode().strip() 916 | 917 | # Get Satellite IP 918 | local_ip_cmd = ["ip -o route get 1 | sed 's/^.*src \\([^ ]*\\).*$/\\1/;q'"] 919 | local_ip = subprocess.Popen (local_ip_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0].decode().strip() 920 | 921 | local_hostname = socket.gethostname() 922 | 923 | # Insert local data 924 | device_data = { 925 | 'cur_MAC': local_mac.lower(), 926 | 'cur_IP': local_ip, 927 | 'cur_hostname': 'Satellite - ' + local_hostname, 928 | 'cur_Vendor': 'unknown', 929 | 'cur_ScanMethod': 'local', 930 | 'cur_SatelliteID': SATELLITE_TOKEN 931 | } 932 | all_devices.append(device_data) 933 | 934 | # Get Uptime 935 | monotonic_time = monotonic() 936 | weeks = int(monotonic_time // 604800) 937 | days = int((monotonic_time % 604800) // 86400) 938 | hours = int((monotonic_time % 86400) // 3600) 939 | minutes = int((monotonic_time % 3600) // 60) 940 | seconds = int(monotonic_time % 60) 941 | 942 | if weeks > 0: 943 | formatted_uptime = f"{weeks}w {days}d {hours:02}h {minutes:02}m " 944 | else: 945 | formatted_uptime = f"{days}d {hours:02}h {minutes:02}m " 946 | 947 | # Get Process count 948 | get_proc_count = subprocess.run(['sh', '-c', 'ps -e | wc -l'], capture_output=True, text=True) 949 | proc_count = get_proc_count.stdout.strip() 950 | 951 | # Get System 952 | try: 953 | import distro 954 | distro_available = True 955 | except ImportError: 956 | distro_available = False 957 | 958 | os_name = platform.system() 959 | 960 | if distro_available: 961 | dist_name = distro.name(pretty=True) 962 | sat_os_name = f"{dist_name}" 963 | else: 964 | sat_os_name = os_name 965 | 966 | # Get local timezone 967 | sat_os_timezone = tzlocal.get_localzone() 968 | 969 | cpu_info = cpuinfo.get_cpu_info() 970 | 971 | try: 972 | cpu_brand = cpu_info['brand'] 973 | except KeyError: 974 | cpu_brand = cpu_info['brand_raw'] 975 | 976 | try: 977 | cpu_arch = cpu_info['arch'] 978 | except KeyError: 979 | cpu_arch = cpu_info['arch_string_raw'] 980 | 981 | # Prepare Satellite Meta Data 982 | satellite_meta_data = [{ 983 | 'hostname': local_hostname, 984 | 'satellite_version': VERSION_DATE, 985 | 'satellite_ip': local_ip, 986 | 'satellite_mac': local_mac, 987 | 'satellite_id': SATELLITE_TOKEN, 988 | 'scan_time': str(startTime), 989 | 'uptime': formatted_uptime, 990 | 'cpu_name': cpu_brand, 991 | 'cpu_arch': cpu_arch, 992 | 'cpu_cores': cpu_info['count'], 993 | 'cpu_freq': cpu_info['hz_actual'], 994 | 'ram_total': psutil.virtual_memory()[0], 995 | 'ram_used_percent': psutil.virtual_memory()[2], 996 | 'proc_count': proc_count, 997 | 'os_version': sat_os_name, 998 | 'os_timezone': str(sat_os_timezone), 999 | 'error_reporting': SATELLITE_ERROR_REPORT 1000 | }] 1001 | 1002 | satellite_scan_config = [{ 1003 | 'scan_arp': ARPSCAN_ACTIVE, 1004 | 'scan_fritzbox': FRITZBOX_ACTIVE, 1005 | 'scan_mikrotik': MIKROTIK_ACTIVE, 1006 | 'scan_unifi': UNIFI_ACTIVE, 1007 | 'scan_openwrt': OPENWRT_ACTIVE, 1008 | 'scan_pihole_net': PIHOLE_ACTIVE, 1009 | 'scan_pihole_dhcp': PIHOLE_DHCP_ACTIVE 1010 | }] 1011 | 1012 | # Write Data to JSON-file 1013 | export_all_scans = { 1014 | 'satellite_meta_data': satellite_meta_data, 1015 | 'satellite_scan_config': satellite_scan_config, 1016 | 'scan_results': all_devices 1017 | } 1018 | 1019 | return export_all_scans 1020 | 1021 | #------------------------------------------------------------------------------- 1022 | def encrypt_submit_scandata(json_data): 1023 | 1024 | if PROXY_MODE: 1025 | print(' Proxy-Mode enabled') 1026 | 1027 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 1028 | # Convert the dictionary to JSON and then to binary data 1029 | enc_json_data = json.dumps(json_data).encode('utf-8') 1030 | # OpenSSL command for encrypting the data 1031 | openssl_command = [ 1032 | "openssl", "enc", "-aes-256-cbc", "-salt", "-out", SATELLITE_BACK_PATH + "/encrypted_scandata", "-pbkdf2", 1033 | "-pass", "pass:{}".format(SATELLITE_PASSWORD) 1034 | ] 1035 | 1036 | with subprocess.Popen(openssl_command, stdin=subprocess.PIPE) as proc: 1037 | proc.stdin.write(enc_json_data) 1038 | 1039 | # DEBUG 1040 | # with open('output.json', 'w') as outfile: 1041 | # json.dump(json_data, outfile, indent=4) 1042 | 1043 | # Read the encrypted data from the file 1044 | with open(SATELLITE_BACK_PATH + "/encrypted_scandata", "rb") as f: 1045 | encrypted_data = f.read() 1046 | 1047 | transfer_mode = "proxy" if PROXY_MODE else "direct" 1048 | # The data for the API requeste 1049 | post_data = { 1050 | "token": SATELLITE_TOKEN, 1051 | "mode" : transfer_mode 1052 | } 1053 | # Files for the API request 1054 | files = { 1055 | "encrypted_data": ("encrypted_scandata", encrypted_data) 1056 | } 1057 | # API-URL 1058 | api_url = SATELLITE_MASTER_URL 1059 | # Send the request to the API, deactivating SSL verification in the process 1060 | response = requests.post(api_url, data=post_data, files=files, verify=False) 1061 | try: 1062 | response_data = response.json() 1063 | print(f" API-Response: {response_data}") 1064 | # if statuscode != 0 save Logs 1065 | if response_data.get('status') != '0': 1066 | save_error(response_data) 1067 | else: 1068 | # if a successful transmission takes place again after less than x logs, delete the logs 1069 | # if a successful transmission occurs again afterwards, delete the file and all logs 1070 | delete_error_files() 1071 | notification_stop('stop') 1072 | 1073 | except json.JSONDecodeError: 1074 | print(" API-Response: ERROR:") 1075 | print("------------------------------------------------------------------------") 1076 | print(" Raw output") 1077 | print("------------------------------------------------------------------------") 1078 | print(response.text) 1079 | print("------------------------------------------------------------------------") 1080 | save_error(response.text) 1081 | 1082 | #------------------------------------------------------------------------------- 1083 | def save_error(response_data): 1084 | if SATELLITE_ERROR_REPORT: 1085 | timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') 1086 | existing_files = [ 1087 | f for f in sorted_alphanumeric(os.listdir(SATELLITE_LOG_PATH)) 1088 | if f.endswith(".txt") and "_error_" in f and len(f.split('_error_')[1].replace('.txt', '')) == report_timestamp 1089 | ] 1090 | file_count = len(existing_files) + 1 1091 | 1092 | file_name = f"{file_count}_error_{timestamp}.txt" 1093 | file_path = os.path.join(SATELLITE_LOG_PATH, file_name) 1094 | 1095 | with open(file_path, 'w') as file: 1096 | json.dump(response_data, file) 1097 | 1098 | print(f" Error saved to file: {file_path}") 1099 | else: 1100 | print(f" Error reporting disabled") 1101 | delete_error_files() 1102 | 1103 | #------------------------------------------------------------------------------- 1104 | def delete_error_files(): 1105 | for file_name in sorted_alphanumeric(os.listdir(SATELLITE_LOG_PATH)): 1106 | # Check whether the file name corresponds to the naming scheme 1107 | if "_error_" in file_name and file_name.endswith(".txt"): 1108 | file_path = os.path.join(SATELLITE_LOG_PATH, file_name) 1109 | try: 1110 | os.remove(file_path) # Lösche die Datei 1111 | print(f" File deleted: {file_name}") 1112 | except Exception as e: 1113 | print(f" Error deleting file: {file_name}") 1114 | notification_stop('stop') 1115 | 1116 | #------------------------------------------------------------------------------- 1117 | def notification_stop(mode): 1118 | if mode == "start": 1119 | with open(STATUS_FILE_REPORTED, 'w') as file: 1120 | pass 1121 | 1122 | if mode == "stop": 1123 | if os.path.exists(STATUS_FILE_REPORTED): 1124 | os.remove(STATUS_FILE_REPORTED) 1125 | 1126 | #------------------------------------------------------------------------------- 1127 | def mail_notification(_Mode): 1128 | global log_timestamp 1129 | 1130 | if SATELLITE_ERROR_REPORT: 1131 | if _Mode == 'Test' : 1132 | print(f"\nTest Message") 1133 | notiMessage = "Test-Notification" 1134 | send_email (notiMessage, notiMessage, False) 1135 | # If further logs are sent after x logs, they are no longer sent because the file prevents it. 1136 | else: 1137 | print(f"\nSatellite error reporting") 1138 | # No test message 1139 | # If further logs are sent after x logs, they are no longer sent because the file prevents it. 1140 | # The stop file is checked 1141 | # Stop file does not exist 1142 | if not os.path.exists(STATUS_FILE_REPORTED): 1143 | # Count the reports to recognize whether a message should be sent 1144 | existing_files = [ 1145 | f for f in sorted_alphanumeric(os.listdir(SATELLITE_LOG_PATH)) 1146 | if f.endswith(".txt") and "_error_" in f and len(f.split('_error_')[1].replace('.txt', '')) == report_timestamp 1147 | ] 1148 | 1149 | # after x logs write an e-mail and attach the logs 1150 | if len(existing_files) >= COLLECT_REPORTS_FOR_MAIL: 1151 | notiTEXT = 'The threshold for repeated transmission errors from the satellite to the API has been reached.' 1152 | notiHTML = """\ 1153 | 1155 | 1156 | 1157 | 1158 | 1159 | E-Mail Beispiel 1160 | 1161 | 1162 |

The threshold for repeated transmission errors from the satellite to the API has been reached.

1163 | 1164 | 1165 | """ 1166 | send_email (notiTEXT, notiHTML, True) 1167 | # create a file that recognizes that a mail has been sent 1168 | notification_stop('start') 1169 | else: 1170 | print(' Nothing to report') 1171 | else: 1172 | print(' Reporting stopped because a mail has already been sent') 1173 | 1174 | else: 1175 | print(' Satellite error reporting is disabled') 1176 | #------------------------------------------------------------------------------- 1177 | def send_email(pText, pHTML, logs): 1178 | # Compose email 1179 | msg = MIMEMultipart() 1180 | msg['Subject'] = FRIENDLY_NAME + ' - Pi.Alert Satellite Message ' 1181 | msg['From'] = MAIL_FROM 1182 | msg['To'] = MAIL_TO 1183 | alternative = MIMEMultipart('alternative') 1184 | alternative.attach(MIMEText(pText, 'plain')) 1185 | alternative.attach(MIMEText(pHTML, 'html')) 1186 | msg.attach(alternative) 1187 | 1188 | if logs: 1189 | existing_files = [ 1190 | f for f in sorted_alphanumeric(os.listdir(SATELLITE_LOG_PATH)) 1191 | if f.endswith(".txt") and "_error_" in f and len(f.split('_error_')[1].replace('.txt', '')) == report_timestamp 1192 | ] 1193 | 1194 | for file_name in existing_files: 1195 | file_path = os.path.join(SATELLITE_LOG_PATH, file_name) 1196 | with open(file_path, 'rb') as file: 1197 | part = MIMEBase('application', 'octet-stream') 1198 | part.set_payload(file.read()) 1199 | encoders.encode_base64(part) 1200 | part.add_header('Content-Disposition', f'attachment; filename="{file_name}"') 1201 | msg.attach(part) 1202 | 1203 | # Send mail 1204 | try: 1205 | smtp_connection = smtplib.SMTP (SMTP_SERVER, SMTP_PORT) 1206 | smtp_connection.ehlo() 1207 | if not SafeParseGlobalBool("SMTP_SKIP_TLS"): 1208 | smtp_connection.starttls() 1209 | smtp_connection.ehlo() 1210 | if not SafeParseGlobalBool("SMTP_SKIP_LOGIN"): 1211 | escaped_password = repr(SMTP_PASS)[1:-1] 1212 | smtp_connection.login (SMTP_USER, escaped_password) 1213 | smtp_connection.sendmail (MAIL_FROM, MAIL_TO, msg.as_string()) 1214 | except Exception as e: 1215 | print(f" Error sending the e-mail") 1216 | finally: 1217 | smtp_connection.quit() 1218 | print(f" Message sent") 1219 | 1220 | 1221 | #------------------------------------------------------------------------------- 1222 | def SafeParseGlobalBool(boolVariable): 1223 | return eval(boolVariable) if boolVariable in globals() else False 1224 | 1225 | #=============================================================================== 1226 | # UTIL 1227 | #=============================================================================== 1228 | def print_log (pText): 1229 | global log_timestamp 1230 | 1231 | # Check LOG actived 1232 | if not PRINT_LOG : 1233 | return 1234 | 1235 | # Current Time 1236 | log_timestamp2 = datetime.datetime.now() 1237 | 1238 | # Print line + time + elapsed time + text 1239 | print('--------------------> ', 1240 | log_timestamp2, ' ', 1241 | log_timestamp2 - log_timestamp, ' ', 1242 | pText) 1243 | 1244 | # Save current time to calculate elapsed time until next log 1245 | log_timestamp = log_timestamp2 1246 | 1247 | #=============================================================================== 1248 | # BEGIN 1249 | #=============================================================================== 1250 | if __name__ == '__main__': 1251 | sys.exit(main()) 1252 | -------------------------------------------------------------------------------- /back/update_vendors.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ------------------------------------------------------------------------------ 3 | # Pi.Alert 4 | # Open Source Network Guard / WIFI & LAN intrusion detector 5 | # 6 | # update_vendors.sh - Back module. IEEE Vendors db update 7 | # ------------------------------------------------------------------------------ 8 | # Puche 2021 pi.alert.application@gmail.com GNU GPLv3 9 | # ------------------------------------------------------------------------------ 10 | 11 | # ---------------------------------------------------------------------- 12 | # Main directories to update: 13 | # /usr/share/arp-scan 14 | # /usr/share/ieee-data 15 | # /var/lib/ieee-data 16 | # ---------------------------------------------------------------------- 17 | 18 | # ---------------------------------------------------------------------- 19 | echo "Updating... /usr/share/ieee-data/" 20 | cd /usr/share/ieee-data/ 21 | 22 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui/oui.csv" 23 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui/oui.txt" 24 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui36/oui36.csv" 25 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui36/oui36.txt" 26 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui28/mam.csv" 27 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/oui28/mam.txt" 28 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/iab/iab.csv" 29 | sudo aria2c --dir=/usr/share/ieee-data --max-connection-per-server=3 --allow-overwrite=true --quiet=true "https://standards-oui.ieee.org/iab/iab.txt" 30 | 31 | # ---------------------------------------------------------------------- 32 | echo "" 33 | echo "Updating... /usr/share/arp-scan/" 34 | cd /usr/share/arp-scan 35 | 36 | # Update from /var/lib/ieee-data 37 | sudo get-oui -v 38 | 39 | # Update from ieee website 40 | # sudo get-iab -v -u https://standards-oui.ieee.org/iab/iab.txt 41 | # sudo get-oui -v -u https://standards-oui.ieee.org/oui/oui.txt 42 | 43 | # Update from Sanitized oui (linuxnet.ca) 44 | # sudo get-oui -v -u https://linuxnet.ca/ieee/oui.txt 45 | 46 | -------------------------------------------------------------------------------- /config/satellite.conf: -------------------------------------------------------------------------------- 1 | # General Settings 2 | # ---------------------- 3 | SATELLITE_PATH = '/home/pi/pialert_satellite' 4 | LOG_PATH = SATELLITE_PATH + '/log' 5 | PRINT_LOG = False 6 | VENDORS_DB = '/usr/share/arp-scan/ieee-oui.txt' 7 | QUERY_MYIP_SERVER = 'https://myipv4.p1.opendns.com/get_my_ip' 8 | INTERNET_DETECTION = False 9 | SATELLITE_TOKEN = 'Demo' 10 | SATELLITE_PASSWORD = 'Demo' 11 | SATELLITE_MASTER_URL = 'http://localhost/pialert/api/satellite.php' 12 | PROXY_MODE = False 13 | SATELLITE_ERROR_REPORT = False 14 | NETWORK_DNS_SERVER = 'localhost' 15 | 16 | # Mail-Account Settings 17 | # ---------------------- 18 | SMTP_SERVER = 'smtp.gmail.com' 19 | SMTP_PORT = 587 20 | SMTP_USER = 'user@gmail.com' 21 | SMTP_PASS = 'password' 22 | SMTP_SKIP_TLS = False 23 | SMTP_SKIP_LOGIN = False 24 | FRIENDLY_NAME = 'My Satellite' 25 | MAIL_FROM = FRIENDLY_NAME + ' - Pi.Alert Satellite <' + SMTP_USER + '>' 26 | MAIL_TO = 'destination@example.com' 27 | COLLECT_REPORTS_FOR_MAIL = 12 28 | # Since a scan is performed every 5 minutes, 12 corresponds to a period of 1 hour during 29 | # which no successful transmission takes place until a notification is sent. 30 | 31 | # Arp-scan Options & Samples 32 | # ---------------------- 33 | ARPSCAN_ACTIVE = False 34 | SCAN_SUBNETS = '--localnet' 35 | # SCAN_SUBNETS = '--localnet' 36 | # SCAN_SUBNETS = '--localnet --interface=eth0' 37 | # SCAN_SUBNETS = ['192.168.1.0/24 --interface=eth0','192.168.2.0/24 --interface=eth1'] 38 | 39 | # Fritzbox Configuration 40 | # ---------------------- 41 | FRITZBOX_ACTIVE = False 42 | FRITZBOX_IP = '192.168.179.1' 43 | FRITZBOX_USER = 'admin' 44 | FRITZBOX_PASS = 'password' 45 | 46 | # Mikrotik Configuration 47 | # ---------------------- 48 | MIKROTIK_ACTIVE = False 49 | MIKROTIK_IP = '10.0.0.1' 50 | MIKROTIK_USER = 'user' 51 | MIKROTIK_PASS = 'password' 52 | 53 | # UniFi Configuration 54 | # ------------------- 55 | UNIFI_ACTIVE = False 56 | UNIFI_IP = '10.0.0.2' 57 | UNIFI_API = 'v5' 58 | UNIFI_USER = 'user' 59 | UNIFI_PASS = 'password' 60 | # Possible UNIFI APIs are v4, v5, unifiOS, UDMP-unifiOS 61 | 62 | # OpenWRT Configuration 63 | # ---------------------- 64 | OPENWRT_ACTIVE = False 65 | OPENWRT_IP = '192.168.1.1' 66 | OPENWRT_USER = 'root' 67 | OPENWRT_PASS = '' 68 | 69 | # Pi-hole Configuration 70 | # ---------------------- 71 | PIHOLE_ACTIVE = False 72 | PIHOLE_DHCP_ACTIVE = False 73 | PIHOLE6_URL = '' 74 | PIHOLE6_PASSWORD = '' 75 | PIHOLE6_API_MAXCLIENTS = 100 76 | -------------------------------------------------------------------------------- /config/version.conf: -------------------------------------------------------------------------------- 1 | VERSION = '' 2 | VERSION_YEAR = '2025' 3 | VERSION_DATE = '2025-04-13' 4 | -------------------------------------------------------------------------------- /docs/CONFIG_FILE.md: -------------------------------------------------------------------------------- 1 | ## Main Config flie parameter 2 | 3 | | PARAMETER | DESCRIPTION | 4 | | ------------------------ | ----------- | 5 | | SATELLITE_PATH | This variable is set during installation and should not be changed | 6 | | LOG_PATH | This variable is set during installation and should not be changed | 7 | | PRINT_LOG | If this entry is set to True, additional timestamps for the individual sub-functions are added to the scan log. By default this entry is set to False | 8 | | VENDORS_DB | This variable is set during installation and should not be changed | 9 | | QUERY_MYIP_SERVER | The satellite uses this URL to check the current public IP | 10 | | INTERNET_DETECTION | Activates or deactivates the public IP check (the parameter currently has no function) | 11 | | SATELLITE_TOKEN | This token (48 alphanumeric characters long) is generated by Pi.Alert and must be entered here. It uniquely identifies this satellite within the Pi.Alert instance | 12 | | SATELLITE_PASSWORD | The password (96 alphanumeric characters long) is generated by Pi.Alert individually for each satellite and must be entered here. | 13 | | SATELLITE_MASTER_URL | This is the URL of the API to which the satellite sends its scan results. This can either be Pi.Alert directly or an external web server on which the API for proxy mode has been installed. | 14 | | PROXY_MODE | Activates the proxy mode in the satellite. If the satellite informs the API that it is working in proxy mode, the API does not attempt to unpack the received data. | 15 | | SATELLITE_ERROR_REPORT | This can be used to activate notification of satellite transmission errors. | 16 | | NETWORK_DNS_SERVER | For host name resolving | 17 | 18 | 19 | #### Mail-Account Settings 20 | 21 | | Option | Description | 22 | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| 23 | | SMTP_SERVER | Address of the e-mail server (e.g. smtp.gmail.com) | 24 | | SMTP_PORT | The port of the SMTP server. The port may vary depending on the server configuration. | 25 | | SMTP_USER | User name | 26 | | SMTP_PASS | Password | 27 | | SMTP_SKIP_TLS | If this entry is set to True, transport encryption of the e-mail is enabled. If the server does not support this, the entry must be set to False. | 28 | | SMTP_SKIP_LOGIN | There are SMTP servers which do not require a login. In such a case, this value can be set to True. | 29 | | MAIL_TO | destination@example.com 30 | | COLLECT_REPORTS_FOR_MAIL | This parameter defines the threshold at which notification of transmission errors takes place. The saved logs are attached to the mail. After this mail, further error notifications are stopped until a successful transmission has taken place. | 31 | 32 | #### Fritzbox Configuration 33 | 34 | | Option | Description | 35 | |-----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| 36 | | FRITZBOX_ACTIVE | If a Fritzbox is used in the network, it can be used as a data source. This can be activated or deactivated at this point. | 37 | | FRITZBOX_IP | IP address of the Fritzbox. | 38 | | FRITZBOX_USER | This assumes that the Fritzbox is configured for a login with username and password, instead of password only. A login with password only is not supported. | 39 | | FRITZBOX_PASS | Password | 40 | 41 | 42 | #### Mikrotik Configuration 43 | 44 | | Option | Description | 45 | |-----------------|------------------------------------------------------------------------------------------------------------------------------| 46 | | MIKROTIK_ACTIVE | If a Mikrotik router is used in the network, it can be used as a data source. This can be enabled or disabled at this point. | 47 | | MIKROTIK_IP | IP address of the Mikrotik router. | 48 | | MIKROTIK_USER | Username | 49 | | MIKROTIK_PASS | Password | 50 | 51 | 52 | #### UniFi Configuration 53 | 54 | | Option | Description | 55 | |--------------|---------------------------------------------------------------------------------------------------------------------------| 56 | | UNIFI_ACTIVE | If a UniFi system is used in the network, it can be used as a data source. This can be enabled or disabled at this point. | 57 | | UNIFI_IP | IP address of the Unifi system. | 58 | | UNIFI_API | Possible UNIFI APIs are v4, v5, unifiOS, UDMP-unifiOS, default | 59 | | UNIFI_USER | Username | 60 | | UNIFI_PASS | Password | 61 | 62 | 63 | #### OpenWRT Configuration 64 | 65 | | Option | Description | 66 | |----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 67 | | OPENWRT_ACTIVE | The package `luci-mod-rpc`need to be installed, on your OpenWrt router. If a OpenWRT is used in the network, it can be used as a data source. This can be activated or deactivated at this point. | 68 | | OPENWRT_IP | IP address of the OpenWRT router. | 69 | | OPENWRT_USER | Username | 70 | | OPENWRT_PASS | Password 71 | 72 | #### Pi-hole Configuration 73 | 74 | | Option | Description | 75 | |--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 76 | | PIHOLE_ACTIVE | This variable is set during installation. | 77 | | PIHOLE_DHCP_ACTIVE | This variable is valid for the DHCP server of Pihole 5.x as well as for 6.x | 78 | | PIHOLE6_URL | If you want to access the Pi-hole data of version 6, enter the URL to the web interface (without the "/admin" suffix) here. | 79 | | PIHOLE6_PASSWORD | Enter the password for the Pi-hole web interface here. | 80 | | PIHOLE6_API_MAXCLIENTS | Specifies the maximum number of clients that are returned as a response from the API | 81 | 82 | [Back](https://github.com/leiweibau/Pi.Alert-Satellite?tab=readme-ov-file#pialert-satellite) -------------------------------------------------------------------------------- /docs/JSON_DEMO.md: -------------------------------------------------------------------------------- 1 | ## DEMO json 2 | 3 | Here you can see the basic structure of the unencrypted json, which is sent encrypted to the API. 4 | 5 | 6 | ```json 7 | { 8 | "satellite_meta_data": [ 9 | { 10 | "hostname": "Pialert-Satellite-Host", 11 | "satellite_version": "2024-07-03", 12 | "satellite_ip": "", 13 | "satellite_mac": "", 14 | "satellite_id": "", 15 | "scan_time": "2024-07-16 15:28:00", 16 | "uptime": "0d 00h 17m ", 17 | "cpu_name": "Intel(R) Celeron(R) CPU N2830 @ 2.16GHz", 18 | "cpu_arch": "x86_64", 19 | "cpu_cores": 2, 20 | "cpu_freq": "2.4167 GHz", 21 | "ram_total": 773668864, 22 | "ram_used_percent": 44.9, 23 | "proc_count": "138", 24 | "os_version": "Debian GNU/Linux 11 (bullseye)", 25 | "os_timezone": "Europe/London", 26 | "error_reporting": "" 27 | } 28 | ], 29 | "satellite_scan_config": [ 30 | { 31 | "scan_arp": true, 32 | "scan_fritzbox": false, 33 | "scan_mikrotik": false, 34 | "scan_unifi": false, 35 | "scan_openwrt": true 36 | } 37 | ], 38 | "scan_results": [ 39 | { 40 | "cur_MAC": "Internet - ", 41 | "cur_IP": "", 42 | "cur_hostname": "Satellite - Internet", 43 | "cur_Vendor": "", 44 | "cur_ScanMethod": "Internet Check", 45 | "cur_SatelliteID": "" 46 | }, 47 | { 48 | "cur_MAC": "00:11:22:aa:bb:cc", 49 | "cur_IP": "192.168.1.85", 50 | "cur_hostname": "(satellite network client)", 51 | "cur_Vendor": "(Unknown: locally administered)", 52 | "cur_ScanMethod": "arp-scan", 53 | "cur_SatelliteID": "" 54 | } 55 | ] 56 | } 57 | ``` 58 | 59 | [Back](https://github.com/leiweibau/Pi.Alert-Satellite) 60 | -------------------------------------------------------------------------------- /docs/NOTIFICATION_MAIL.md: -------------------------------------------------------------------------------- 1 | ## Configure Mail Notification 2 | 3 | You can also activate an email notification from the satellite. However, this is only triggered if a previously configured 4 | threshold (`COLLECT_REPORTS_FOR_MAIL`) of consecutive faulty transmissions has been reached. When the threshold is exceeded, 5 | the log files collected up to that point are attached to the email and sent to the destination address. No further 6 | notifications are sent. Only when a scan has been successfully transmitted is a new notification possible when the configured 7 | threshold is reached. 8 | 9 | ``` 10 | # Mail-Account Settings 11 | # ---------------------- 12 | SMTP_SERVER = 'smtp.gmail.com' 13 | SMTP_PORT = 587 14 | SMTP_USER = 'user@gmail.com' 15 | SMTP_PASS = 'password' 16 | SMTP_SKIP_TLS = False 17 | SMTP_SKIP_LOGIN = False 18 | FRIENDLY_NAME = 'My Satellite' 19 | MAIL_FROM = FRIENDLY_NAME + ' - Pi.Alert Satellite <' + SMTP_USER + '>' 20 | MAIL_TO = 'destination@example.com' 21 | COLLECT_REPORTS_FOR_MAIL = 12 22 | # Since a scan is performed every 5 minutes, 12 corresponds to a period of 1 hour during which no successful transmission takes place until a notification is sent. 23 | 24 | ``` 25 | 26 | 27 | To test the mail configuration, you can send a test mail in the “back” directory in the Pi.Alert Satallite directory (e.g. “$HOME/pialert_satellite”). 28 | 29 | ``` 30 | cd $HOME/pialert_satellite/back 31 | python3 satellite.py email_test` 32 | ``` 33 | 34 | [Gmail Support Document](https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor) 35 | 36 | [iCloud Support Document](https://support.apple.com/en-us/102654) 37 | 38 | [Outlook Support Document](https://support.microsoft.com/en-us/account-billing/how-to-get-and-use-app-passwords-5896ed9b-4263-e681-128a-a6f2979a7944) 39 | 40 | 41 | [Back](https://github.com/leiweibau/Pi.Alert-Satellite) -------------------------------------------------------------------------------- /docs/PROXY_MODE.md: -------------------------------------------------------------------------------- 1 | ## Use case: 2 | If it is not desired for security reasons that the Satellite sends the data directly to the Pi.Alert API, a second web server can be used as a "proxy". 3 | In this case, the satellite sends the data to the proxy and Pi.Alert retrieves the data from it. The data is not decrypted on the proxy. 4 | 5 | ## Requirements: 6 | 7 | - Web server with PHP support 8 | - Web server must support file upload 9 | - The web server must be accessible for both the satellite and the Pi.Alert instance itself 10 | - An already installed version of Pi.Alert for creation of a configuration file 11 | 12 | ## Installation: 13 | 14 | You can find the API files in the "api" folder of the Pi.Alert Satellite Archive. 15 | 16 | This step only needs to be performed once and can be used for multiple satellites. 17 | Create a new folder for the Pi.Alert API Proxy on your web server within the web root (it can also be a subfolder). For the purposes of this guide, 18 | I will use the folder "pialert_proxy". Place the "api" folder and its contents into this directory. Additionally, create the "satellites" folder. 19 | The resulting folder structure should be as follows: 20 | 21 | ``` 22 | pialert_proxy 23 | ├── api 24 | ├───── satellite.php 25 | └── satellites 26 | ``` 27 | 28 | The URL for the API is now, for example: https://example.com/pialert_proxy/api/satellite.php 29 | 30 | ## Configuration: 31 | In the configuration file of the satellite ("config/satellite.conf"), the variable "PROXY_MODE" must be set to "True". The URL of the proxy is entered 32 | as the value for the variable "SATELLITE_MASTER_URL" according to the example above. Finally, a file called "config.php", which can be downloaded from 33 | the Pi.Alert satellite settings, is also copied to the "api" directory. This file contains the tokens of all created satellites and ensures that only 34 | valid satellites are allowed to interact with the API. 35 | 36 | ``` 37 | pialert_proxy 38 | ├── api 39 | ├───── satellite.php 40 | ├───── config.php 41 | └── satellites 42 | ``` 43 | 44 | ## Additional information 45 | 46 | The specification of a token and the mode used is mandatory for the API. If this is not the case, it outputs an HTTP status code 404 including a 47 | corresponding error page. All other states are "answered" in the form of a JSON message when using the "proxy" and "direct" modes. The "get" mode is 48 | used to download the files and has the additional function of deleting all scan results on the proxy that are older than 10 minutes. The reason for this 49 | is that if the satellite or the Internet connection from the satellite fails, the last available scan is not constantly loaded, making it appear as if 50 | everything is OK. By deleting the old scans, the satellite and all connected devices are displayed as offline. 51 | 52 | [Back](https://github.com/leiweibau/Pi.Alert-Satellite?tab=readme-ov-file#pialert-satellite) -------------------------------------------------------------------------------- /install/pialert_satellite_install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # ------------------------------------------------------------------------------ 3 | # pialert_satellite_install.sh - Installation script 4 | # ------------------------------------------------------------------------------ 5 | # Puche 2021 pi.alert.application@gmail.com GNU GPLv3 6 | # leiweibau 2024 GNU GPLv3 7 | # ------------------------------------------------------------------------------ 8 | 9 | # ------------------------------------------------------------------------------ 10 | # Variables 11 | # ------------------------------------------------------------------------------ 12 | SAT_TOKEN=$1 13 | SAT_PASSWORD=$2 14 | SAT_PROXY_MODE=$3 15 | SAT_URL=$4 16 | 17 | INSTALL_DIR=~ 18 | PIALERT_SATELLITE_HOME="$INSTALL_DIR/pialert_satellite" 19 | LOG="satellite_install_`date +"%Y-%m-%d_%H-%M"`.log" 20 | 21 | USE_PYTHON_VERSION=0 22 | PYTHON_BIN=python 23 | 24 | # ------------------------------------------------------------------------------ 25 | # Main 26 | # ------------------------------------------------------------------------------ 27 | main() { 28 | print_superheader "Pi.Alert-Satellite Installation" 29 | log "`date`" 30 | log "Logfile: $LOG" 31 | install_dependencies 32 | 33 | check_pialert_satellite_home 34 | 35 | set -e 36 | 37 | install_additional_dependencies 38 | install_pialert_satellite 39 | 40 | print_header "Installation process finished" 41 | print_msg "" 42 | 43 | move_logfile 44 | } 45 | 46 | 47 | # ------------------------------------------------------------------------------ 48 | # Install arp-scan & dnsutils 49 | # ------------------------------------------------------------------------------ 50 | install_additional_dependencies() { 51 | print_header "arp-scan, dnsutils and nmap" 52 | 53 | print_msg "- Installing arp-scan..." 54 | sudo apt-get install arp-scan -y 2>&1 >> "$LOG" 55 | sudo mkdir -p /usr/share/ieee-data 2>&1 >> "$LOG" 56 | if [ -f "/usr/share/arp-scan/ieee-iab.txt.bak" ]; then 57 | sudo mv /usr/share/arp-scan/ieee-iab.txt.bak /usr/share/arp-scan/ieee-iab.txt 2>&1 >> "$LOG" 58 | fi 59 | if [ -d "/usr/share/arp-scan/2_backup" ]; then 60 | sudo rm -rf /usr/share/arp-scan/2_backup 2>&1 >> "$LOG" 61 | fi 62 | print_msg "- Testing arp-scan..." 63 | sudo arp-scan -l | head -n -3 | tail +3 | tee -a "$LOG" 64 | 65 | print_msg "- Installing dnsutils & net-tools..." 66 | sudo apt-get install dnsutils net-tools curl libwww-perl libtext-csv-perl -y 2>&1 >> "$LOG" 67 | 68 | print_msg "- Installation of tools for hostname detection..." 69 | sudo apt-get install avahi-utils nbtscan -y 2>&1 >> "$LOG" 70 | 71 | print_msg "- Installing aria2" 72 | sudo apt-get install aria2 -y 2>&1 >> "$LOG" 73 | 74 | print_header "Python" 75 | 76 | check_python_versions 77 | 78 | if $PYTHON3 ; then 79 | print_msg " - Python 3 is available" 80 | USE_PYTHON_VERSION=3 81 | elif $PYTHON2 ; then 82 | print_msg " - Python 2 is available but not compatible with Pi.Alert-Satellite" 83 | print_msg " - Python 3 will be installed" 84 | USE_PYTHON_VERSION=3 85 | else 86 | print_msg " - Python is not available in this system" 87 | print_msg " - Python 3 will be installed" 88 | USE_PYTHON_VERSION=3 89 | fi 90 | 91 | if $PYTHON3 ; then 92 | print_msg "- Using Python 3" 93 | sudo apt-get install python3-pip python3-cryptography python3-requests python3-cpuinfo python3-distro python3-psutil python3-tz python3-tzlocal -y 2>&1 >> "$LOG" 94 | else 95 | print_msg "- Installing Python 3..." 96 | sudo apt-get install python3 python3-pip python3-cryptography python3-requests python3-cpuinfo python3-distro python3-psutil python3-tz python3-tzlocal -y 2>&1 >> "$LOG" 97 | fi 98 | print_msg " - Install additional packages" 99 | if [ -f /usr/lib/python3.*/EXTERNALLY-MANAGED ]; then 100 | pip3 -q install mac-vendor-lookup --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 101 | pip3 -q install fritzconnection --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 102 | pip3 -q install routeros_api --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 103 | pip3 -q install pyunifi --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 104 | pip3 -q install openwrt-luci-rpc --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 105 | else 106 | pip3 -q install mac-vendor-lookup --no-warn-script-location 2>&1 >> "$LOG" 107 | pip3 -q install fritzconnection --no-warn-script-location 2>&1 >> "$LOG" 108 | pip3 -q install routeros_api --no-warn-script-location 2>&1 >> "$LOG" 109 | pip3 -q install pyunifi --no-warn-script-location 2>&1 >> "$LOG" 110 | pip3 -q install openwrt-luci-rpc --no-warn-script-location 2>&1 >> "$LOG" 111 | fi 112 | 113 | PYTHON_BIN="python3" 114 | 115 | } 116 | 117 | # ------------------------------------------------------------------------------ 118 | # Check Python versions available 119 | # ------------------------------------------------------------------------------ 120 | check_python_versions() { 121 | if [ -f /usr/bin/python ] ; then 122 | PYTHON2=true 123 | else 124 | PYTHON2=false 125 | fi 126 | 127 | print_msg "- Checking Python 3..." 128 | if [ -f /usr/bin/python3 ] ; then 129 | print_msg " - Python 3 is installed" 130 | print_msg " - `python3 -V 2>&1`" 131 | PYTHON3=true 132 | else 133 | print_msg " - Python 3 is NOT installed" 134 | PYTHON3=false 135 | fi 136 | echo "" 137 | } 138 | 139 | # ------------------------------------------------------------------------------ 140 | # Install Pi.Alert 141 | # ------------------------------------------------------------------------------ 142 | install_pialert_satellite() { 143 | print_header "Pi.Alert-Satellite" 144 | 145 | download_satellite 146 | configure_satellite 147 | configure_user 148 | test_satellite 149 | add_jobs_to_crontab 150 | } 151 | 152 | # ------------------------------------------------------------------------------ 153 | # Download and uncompress Pi.Alert 154 | # ------------------------------------------------------------------------------ 155 | download_satellite() { 156 | if [ -f "$INSTALL_DIR/pialert_satellite_latest.tar" ] ; then 157 | print_msg "- Deleting previous downloaded tar file" 158 | rm -r "$INSTALL_DIR/pialert_satellite_latest.tar" 159 | fi 160 | 161 | print_msg "- Downloading installation tar file..." 162 | URL="https://github.com/leiweibau/Pi.Alert-Satellite/raw/main/tar/pialert_satellite_latest.tar" 163 | 164 | wget -q --show-progress -O "$INSTALL_DIR/pialert_satellite_latest.tar" "$URL" 165 | echo "" 166 | 167 | print_msg "- Uncompressing tar file" 168 | tar xf "$INSTALL_DIR/pialert_satellite_latest.tar" -C "$INSTALL_DIR" --checkpoint=100 --checkpoint-action="ttyout=." 2>&1 >> "$LOG" 169 | echo "" 170 | 171 | print_msg "- Deleting downloaded tar file..." 172 | rm -r "$INSTALL_DIR/pialert_satellite_latest.tar" 2>&1 >> "$LOG" 173 | 174 | } 175 | 176 | # ------------------------------------------------------------------------------ 177 | # Configure Pi.Alert-Satellite parameters 178 | # ------------------------------------------------------------------------------ 179 | configure_satellite() { 180 | print_msg "- Setting Pi.Alert-Satellite config file" 181 | 182 | if [ -n "$SAT_TOKEN" ]; then 183 | set_satellite_parameter SATELLITE_TOKEN "'$SAT_TOKEN'" 184 | fi 185 | 186 | if [ -n "$SAT_PASSWORD" ]; then 187 | set_satellite_parameter SATELLITE_PASSWORD "'$SAT_PASSWORD'" 188 | fi 189 | if [ -n "$SAT_PROXY_MODE" ]; then 190 | set_satellite_parameter PROXY_MODE "$SAT_PROXY_MODE" 191 | fi 192 | 193 | if [ -n "$SAT_URL" ]; then 194 | set_satellite_parameter SATELLITE_MASTER_URL "'$SAT_URL'" 195 | fi 196 | 197 | set_satellite_parameter SATELLITE_PATH "'$PIALERT_SATELLITE_HOME'" 198 | 199 | } 200 | 201 | # ------------------------------------------------------------------------------ 202 | # Configure User 203 | # ------------------------------------------------------------------------------ 204 | configure_user() { 205 | SAT_USER=$(whoami) 206 | print_msg "Pi.Alert-Satellite User: $SAT_USER" 207 | echo -e " ...Create Satellite sudoer file to be able to run \"arp-scan\"" 208 | echo "${SAT_USER} ALL=(ALL) NOPASSWD: /usr/sbin/arp-scan" | sudo tee /etc/sudoers.d/pialert-satellite 209 | } 210 | 211 | # ------------------------------------------------------------------------------ 212 | # Set Pi.Alert-Satellite parameter 213 | # ------------------------------------------------------------------------------ 214 | set_satellite_parameter() { 215 | if [ "$2" = "false" ] ; then 216 | VALUE="False" 217 | elif [ "$2" = "true" ] ; then 218 | VALUE="True" 219 | else 220 | VALUE="$2" 221 | fi 222 | 223 | sed -i "/^$1.*=/s|=.*|= $VALUE|" $PIALERT_SATELLITE_HOME/config/satellite.conf 2>&1 >> "$LOG" 224 | } 225 | 226 | # ------------------------------------------------------------------------------ 227 | # Test Pi.Alert 228 | # ------------------------------------------------------------------------------ 229 | test_satellite() { 230 | print_msg "- Testing Pi.Alert-Satellite HW vendors database update process..." 231 | print_msg "- Prepare directories..." 232 | if [ ! -e /var/lib/ieee-data ]; then 233 | sudo ln -s /usr/share/ieee-data/ /var/lib/ieee-data 2>&1 >> "$LOG" 234 | fi 235 | 236 | stdbuf -i0 -o0 -e0 $PYTHON_BIN $PIALERT_SATELLITE_HOME/back/satellite.py update_vendors_silent 2>&1 | tee -ai "$LOG" 237 | } 238 | 239 | # ------------------------------------------------------------------------------ 240 | # Add Pi.Alert-Satellite jobs to crontab 241 | # ------------------------------------------------------------------------------ 242 | add_jobs_to_crontab() { 243 | if crontab -l 2>/dev/null | grep -Fq satellite ; then 244 | print_msg "- Pi.Alert-Satellite crontab jobs already exists. This is your crontab:" 245 | crontab -l | grep -F satellite 2>&1 | tee -ai "$LOG" 246 | return 247 | fi 248 | 249 | print_msg "- Adding jobs to the crontab..." 250 | 251 | (crontab -l 2>/dev/null || : ; cat $PIALERT_SATELLITE_HOME/install/satellite.cron) | crontab - 252 | } 253 | 254 | # ------------------------------------------------------------------------------ 255 | # Check Pi.Alert-Satellite Installation Path 256 | # ------------------------------------------------------------------------------ 257 | check_pialert_satellite_home() { 258 | mkdir -p "$INSTALL_DIR" 259 | if [ ! -d "$INSTALL_DIR" ] ; then 260 | process_error "Installation path does not exists: $INSTALL_DIR" 261 | fi 262 | 263 | if [ -e "$PIALERT_SATELLITE_HOME" ] || [ -L "$PIALERT_SATELLITE_HOME" ] ; then 264 | process_error "Pi.Alert-Satellite path already exists: $PIALERT_SATELLITE_HOME" 265 | fi 266 | sudo apt-get install cron whiptail -y 267 | } 268 | 269 | # ------------------------------------------------------------------------------ 270 | # Check Pi.Alert-Satellite Installation Path 271 | # ------------------------------------------------------------------------------ 272 | install_dependencies() { 273 | print_msg "- Installing dependencies..." 274 | if [ $(id -u) -eq 0 ]; then 275 | apt-get install sudo -y 2>&1 >> "$LOG" 276 | fi 277 | 278 | sudo apt-get install cron whiptail -y 2>&1 >> "$LOG" 279 | } 280 | 281 | # ------------------------------------------------------------------------------ 282 | # Move Logfile 283 | # ------------------------------------------------------------------------------ 284 | move_logfile() { 285 | NEWLOG="$PIALERT_SATELLITE_HOME/log/$LOG" 286 | 287 | mkdir -p "$PIALERT_SATELLITE_HOME/log" 288 | mv $LOG $NEWLOG 289 | 290 | LOG="$NEWLOG" 291 | NEWLOG="" 292 | } 293 | 294 | # ------------------------------------------------------------------------------ 295 | # Log 296 | # ------------------------------------------------------------------------------ 297 | log() { 298 | echo "$1" | tee -a "$LOG" 299 | } 300 | 301 | log_no_screen () { 302 | echo "$1" >> "$LOG" 303 | } 304 | 305 | log_only_screen () { 306 | echo "$1" 307 | } 308 | 309 | print_msg() { 310 | log_no_screen "" 311 | log "$1" 312 | } 313 | 314 | print_superheader() { 315 | log "" 316 | log "############################################################" 317 | log " $1" 318 | log "############################################################" 319 | } 320 | 321 | print_header() { 322 | log "" 323 | log "------------------------------------------------------------" 324 | log " $1" 325 | log "------------------------------------------------------------" 326 | } 327 | 328 | process_error() { 329 | log "" 330 | log "************************************************************" 331 | log "************************************************************" 332 | log "** ERROR INSTALLING PI.ALERT-SATELLITE **" 333 | log "************************************************************" 334 | log "************************************************************" 335 | log "" 336 | log "$1" 337 | log "" 338 | log "Use 'cat $LOG' to view installation log" 339 | log "" 340 | 341 | # msgbox "****** ERROR INSTALLING Pi.Alert-Satellite ******" "$1" 342 | exit 1 343 | } 344 | 345 | # ------------------------------------------------------------------------------ 346 | main 347 | exit 0 348 | -------------------------------------------------------------------------------- /install/pialert_satellite_uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # ------------------------------------------------------------------------------ 3 | # pialert_satellite_uninstall.sh - Uninstallation script 4 | # ------------------------------------------------------------------------------ 5 | # Puche 2021 pi.alert.application@gmail.com GNU GPLv3 6 | # leiweibau 2024 GNU GPLv3 7 | # ------------------------------------------------------------------------------ 8 | 9 | # ------------------------------------------------------------------------------ 10 | # Variables 11 | # ------------------------------------------------------------------------------ 12 | 13 | INSTALL_DIR=$HOME 14 | PIALERT_HOME="$INSTALL_DIR/pialert_satellite" 15 | LOG="pialert_uninstall_`date +"%Y-%m-%d_%H-%M"`.log" 16 | 17 | # ------------------------------------------------------------------------------ 18 | # Main 19 | # ------------------------------------------------------------------------------ 20 | main() { 21 | print_superheader "Pi.Alert Uninstallation" 22 | log "`date`" 23 | log "Logfile: $LOG" 24 | 25 | log "The uninstallation process will start now" 26 | 27 | # Uninstall prrocess 28 | print_header "Removing files" 29 | sudo rm -r "$PIALERT_HOME" 2>&1 >> "$LOG" 30 | #sudo rm /etc/sudoers.d/pialert-backend 2>&1 >> "$LOG" 31 | #sudo rm /etc/sudoers.d/pialert-frontend 2>&1 >> "$LOG" 32 | 33 | # Uninstall crontab jobs 34 | print_header "Removing crontab jobs" 35 | crontab -l 2>/dev/null | sed '/satellite.py/d' | crontab - 36 | 37 | # final message 38 | log "Uninstallation process finished" 39 | } 40 | 41 | # ------------------------------------------------------------------------------ 42 | # Log 43 | # ------------------------------------------------------------------------------ 44 | log() { 45 | echo "$1" | tee -a "$LOG" 46 | } 47 | 48 | log_no_screen () { 49 | echo "$1" >> "$LOG" 50 | } 51 | 52 | log_only_screen () { 53 | echo "$1" 54 | } 55 | 56 | print_msg() { 57 | log_no_screen "" 58 | log "$1" 59 | } 60 | 61 | print_superheader() { 62 | log "" 63 | log "############################################################" 64 | log " $1" 65 | log "############################################################" 66 | } 67 | 68 | print_header() { 69 | log "" 70 | log "------------------------------------------------------------" 71 | log " $1" 72 | log "------------------------------------------------------------" 73 | } 74 | 75 | # ------------------------------------------------------------------------------ 76 | main 77 | exit 0 78 | -------------------------------------------------------------------------------- /install/pialert_satellite_update.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # ------------------------------------------------------------------------------ 3 | # pialert_satellite_update.sh - Update script 4 | # ------------------------------------------------------------------------------ 5 | # leiweibau 2024+ GNU GPLv3 6 | # ------------------------------------------------------------------------------ 7 | 8 | # ------------------------------------------------------------------------------ 9 | # Variables 10 | # ------------------------------------------------------------------------------ 11 | if [ "$1" = "--lxc" ]; then 12 | INSTALL_DIR="/opt" 13 | else 14 | INSTALL_DIR="$HOME" 15 | fi 16 | PIALERT_SATELLITE_HOME="$INSTALL_DIR/pialert_satellite" 17 | LOG="pialert_satellite_update_`date +"%Y-%m-%d_%H-%M"`.log" 18 | PYTHON_BIN=python3 19 | 20 | 21 | # ------------------------------------------------------------------------------ 22 | # Main 23 | # ------------------------------------------------------------------------------ 24 | main() { 25 | print_superheader "Pi.Alert Satellite Update" 26 | log "`date`" 27 | log "Logfile: $LOG" 28 | log "" 29 | 30 | set -e 31 | 32 | check_pialert_home 33 | check_python_version 34 | create_backup 35 | check_packages 36 | download_satellite 37 | update_config 38 | configure_user 39 | 40 | test_pialert 41 | 42 | print_header "Update process finished" 43 | print_msg "" 44 | 45 | move_logfile 46 | } 47 | 48 | configure_user() { 49 | SAT_USER=$(whoami) 50 | print_msg "Pi.Alert-Satellite User: $SAT_USER" 51 | echo -e " ...Create Satellite sudoer file to be able to run \"arp-scan\"" 52 | echo "${SAT_USER} ALL=(ALL) NOPASSWD: /usr/sbin/arp-scan" | sudo tee /etc/sudoers.d/pialert-satellite 53 | } 54 | 55 | # ------------------------------------------------------------------------------ 56 | # Create backup 57 | # ------------------------------------------------------------------------------ 58 | create_backup() { 59 | # Previous backups are deleted to preserve storage 60 | print_msg "- Deleting previous Pi.Alert backups..." 61 | rm -f "$INSTALL_DIR/"satellite_update_backup_*.tar 62 | print_msg "- Creating new Pi.Alert backup..." 63 | cd "$INSTALL_DIR" 64 | tar cvf "$INSTALL_DIR"/satellite_update_backup_`date +"%Y-%m-%d_%H-%M"`.tar pialert_satellite --checkpoint=100 --checkpoint-action="ttyout=." 2>&1 >> "$LOG" 65 | } 66 | 67 | # ------------------------------------------------------------------------------ 68 | # Check packages 69 | # ------------------------------------------------------------------------------ 70 | check_packages() { 71 | sudo apt-get update 2>&1 >>"$LOG" 72 | packages=("apt-utils" "git" "dnsutils" "net-tools" "nbtscan" "avahi-utils" "python3-requests" "python3-cpuinfo" "python3-psutil" "python3-distro" "python3-cryptography" "python3-tz" "python3-tzlocal" "libwww-perl" "mmdb-bin" "libtext-csv-perl" "aria2") 73 | print_msg "- Checking packages..." 74 | missing_packages=() 75 | for package in "${packages[@]}"; do 76 | if ! dpkg -l | grep -q "$package"; then 77 | missing_packages+=("$package") 78 | fi 79 | done 80 | if [ ${#missing_packages[@]} -gt 0 ]; then 81 | print_msg "- Installing missing packages: ${missing_packages[*]}" 82 | sudo apt-get install -y "${missing_packages[@]}" 2>&1 >>"$LOG" 83 | fi 84 | } 85 | 86 | # ------------------------------------------------------------------------------ 87 | # Download and uncompress Pi.Alert 88 | # ------------------------------------------------------------------------------ 89 | download_satellite() { 90 | if [ -e "$HOME/Pi.Alert-Satellite" ] ; then 91 | rm -rf "$HOME/Pi.Alert-Satellite" 92 | fi 93 | 94 | Clone_Update=`(git clone --quiet https://github.com/leiweibau/Pi.Alert-Satellite) 2>&1 >> "$LOG"` 95 | #git clone --quiet https://github.com/leiweibau/Pi.Alert-Satellite 2>&1 >> "$LOG" 96 | cp -rf "$HOME/Pi.Alert-Satellite/back" "$PIALERT_SATELLITE_HOME/" 97 | cp -rf "$HOME/Pi.Alert-Satellite/api/satellite.php" "$PIALERT_SATELLITE_HOME/api/satellite.php" 98 | cp -rf "$HOME/Pi.Alert-Satellite/config/version.conf" "$PIALERT_SATELLITE_HOME/config/version.conf" 99 | cp -rf "$HOME/Pi.Alert-Satellite/api/satellite.php" "$PIALERT_SATELLITE_HOME/api/satellite.php" 100 | cp -rf "$HOME/Pi.Alert-Satellite/docs" "$PIALERT_SATELLITE_HOME/" 101 | cp -rf "$HOME/Pi.Alert-Satellite/install" "$PIALERT_SATELLITE_HOME/" 102 | cp -rf "$HOME/Pi.Alert-Satellite/README.md" "$PIALERT_SATELLITE_HOME/" 103 | 104 | rm -rf "$HOME/Pi.Alert-Satellite" 105 | } 106 | 107 | # ------------------------------------------------------------------------------ 108 | # Update conf file 109 | # ------------------------------------------------------------------------------ 110 | update_config() { 111 | print_msg "- Config backup..." 112 | cp "$PIALERT_SATELLITE_HOME/config/satellite.conf" "$PIALERT_SATELLITE_HOME/config/satellite.conf.back" 2>&1 >> "$LOG" 113 | 114 | print_msg "- Updating config file..." 115 | 116 | # 2024-11-01 117 | if ! grep -Fq "# Mail-Account Settings" "$PIALERT_SATELLITE_HOME/config/satellite.conf" ; then 118 | cat << EOF >> "$PIALERT_SATELLITE_HOME/config/satellite.conf" 119 | 120 | SATELLITE_ERROR_REPORT = False 121 | 122 | # Mail-Account Settings 123 | # ---------------------- 124 | SMTP_SERVER = 'smtp.gmail.com' 125 | SMTP_PORT = 587 126 | SMTP_USER = 'user@gmail.com' 127 | SMTP_PASS = 'password' 128 | SMTP_SKIP_TLS = False 129 | SMTP_SKIP_LOGIN = False 130 | FRIENDLY_NAME = 'My Satellite' 131 | MAIL_FROM = FRIENDLY_NAME + ' - Pi.Alert Satellite <' + SMTP_USER +'>' 132 | MAIL_TO = 'destination@example.com' 133 | COLLECT_REPORTS_FOR_MAIL = 12 134 | # Since a scan is performed every 5 minutes, 12 corresponds to a period of 1 hour during which no successful transmission takes place until a notification is sent. 135 | EOF 136 | fi 137 | 138 | # 2025-01-17 139 | if ! grep -Fq "# OpenWRT Configuration" "$PIALERT_SATELLITE_HOME/config/satellite.conf" ; then 140 | cat << EOF >> "$PIALERT_SATELLITE_HOME/config/satellite.conf" 141 | 142 | # OpenWRT Configuration 143 | # ---------------------- 144 | OPENWRT_ACTIVE = False 145 | OPENWRT_IP = '192.168.1.1' 146 | OPENWRT_USER = 'root' 147 | OPENWRT_PASS = '' 148 | 149 | 150 | NETWORK_DNS_SERVER = 'localhost' 151 | EOF 152 | fi 153 | 154 | # 2025-04-13 155 | if ! grep -Fq "# Pi-hole Configuration" "$PIALERT_SATELLITE_HOME/config/satellite.conf" ; then 156 | cat << EOF >> "$PIALERT_SATELLITE_HOME/config/satellite.conf" 157 | 158 | # Pi-hole Configuration 159 | # ---------------------- 160 | PIHOLE_ACTIVE = False 161 | PIHOLE_DHCP_ACTIVE = False 162 | PIHOLE6_URL = '' 163 | PIHOLE6_PASSWORD = '' 164 | PIHOLE6_API_MAXCLIENTS = 100 165 | EOF 166 | fi 167 | 168 | } 169 | 170 | # ------------------------------------------------------------------------------ 171 | # Test Pi.Alert-Satellite 172 | # ------------------------------------------------------------------------------ 173 | test_pialert() { 174 | print_msg "- Testing Pi.Alert-Satellite Network scan..." 175 | stdbuf -i0 -o0 -e0 $PYTHON_BIN $PIALERT_SATELLITE_HOME/back/satellite.py scan 2>&1 | tee -ai "$LOG" 176 | } 177 | 178 | # ------------------------------------------------------------------------------ 179 | # Check Pi.Alert Installation Path 180 | # ------------------------------------------------------------------------------ 181 | check_pialert_home() { 182 | if [ ! -e "$PIALERT_SATELLITE_HOME" ] ; then 183 | process_error "Pi.Alert directory dosn't exists: $PIALERT_SATELLITE_HOME" 184 | fi 185 | } 186 | 187 | # ------------------------------------------------------------------------------ 188 | # Check Python versions available 189 | # ------------------------------------------------------------------------------ 190 | check_and_install_package() { 191 | package_name="$1" 192 | if pip3 show "$package_name" > /dev/null 2>&1; then 193 | print_msg "- $package_name is already installed" 194 | else 195 | print_msg "- Installing $package_name..." 196 | if [ -f /usr/lib/python3.*/EXTERNALLY-MANAGED ]; then 197 | pip3 -q install "$package_name" --break-system-packages --no-warn-script-location 2>&1 >> "$LOG" 198 | else 199 | pip3 -q install "$package_name" --no-warn-script-location 2>&1 >> "$LOG" 200 | fi 201 | print_msg "- $package_name is now installed" 202 | fi 203 | } 204 | check_python_version() { 205 | print_msg "- Checking Python..." 206 | PYTHON_BIN="" 207 | if [ -f /usr/bin/python3 ]; then 208 | PYTHON_BIN="python3" 209 | print_msg "Python 3 is installed on your system" 210 | check_and_install_package "mac-vendor-lookup" 211 | check_and_install_package "fritzconnection" 212 | check_and_install_package "routeros_api" 213 | check_and_install_package "pyunifi" 214 | check_and_install_package "openwrt_luci_rpc" 215 | else 216 | print_msg "Python 3 NOT installed" 217 | process_error "Python 3 is required for this application" 218 | fi 219 | } 220 | 221 | # ------------------------------------------------------------------------------ 222 | # Move Logfile 223 | # ------------------------------------------------------------------------------ 224 | move_logfile() { 225 | NEWLOG="$PIALERT_SATELLITE_HOME/log/$LOG" 226 | 227 | mkdir -p "$PIALERT_SATELLITE_HOME/log" 228 | mv $LOG $NEWLOG 229 | 230 | LOG="$NEWLOG" 231 | NEWLOG="" 232 | } 233 | 234 | # ------------------------------------------------------------------------------ 235 | # Log 236 | # ------------------------------------------------------------------------------ 237 | log() { 238 | echo "$1" | tee -a "$LOG" 239 | } 240 | 241 | log_no_screen () { 242 | echo "$1" >> "$LOG" 243 | } 244 | 245 | log_only_screen () { 246 | echo "$1" 247 | } 248 | 249 | print_msg() { 250 | log_no_screen "" 251 | log "$1" 252 | } 253 | 254 | print_superheader() { 255 | log "" 256 | log "############################################################" 257 | log " $1" 258 | log "############################################################" 259 | } 260 | 261 | print_header() { 262 | log "" 263 | log "------------------------------------------------------------" 264 | log " $1" 265 | log "------------------------------------------------------------" 266 | } 267 | 268 | process_error() { 269 | log "" 270 | log "************************************************************" 271 | log "************************************************************" 272 | log "** ERROR UPDATING PI.ALERT **" 273 | log "************************************************************" 274 | log "************************************************************" 275 | log "" 276 | log "$1" 277 | log "" 278 | log "Use 'cat $LOG' to view update log" 279 | log "" 280 | 281 | exit 1 282 | } 283 | 284 | # ------------------------------------------------------------------------------ 285 | main 286 | exit 0 287 | -------------------------------------------------------------------------------- /install/satellite.cron: -------------------------------------------------------------------------------- 1 | 0 3 * * 1 python3 $HOME/pialert_satellite/back/satellite.py update_vendors >$HOME/pialert_satellite/log/satellite.vendors.log 2>&1 2 | */5 * * * * python3 $HOME/pialert_satellite/back/satellite.py scan >$HOME/pialert_satellite/log/satellite.scan.log 2>&1 3 | -------------------------------------------------------------------------------- /log/satellite.scan.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leiweibau/Pi.Alert-Satellite/834246b1d570e764823e537cc59d5033b7d210da/log/satellite.scan.log -------------------------------------------------------------------------------- /tar/create.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | PIALERT_DEV_PATH=../../ 4 | cd $PIALERT_DEV_PATH 5 | pwd 6 | PIALERT_VERSION=`awk '$1=="VERSION" { print $3 }' pialert_satellite/config/version.conf | tr -d \'` 7 | 8 | # ------------------------------------------------------------------------------ 9 | ls -l pialert_satellite/tar/pialert_satellite*.tar 10 | tar tvf pialert_satellite/tar/pialert_satellite_latest.tar | wc -l 11 | rm pialert_satellite/tar/pialert_satellite*.tar 12 | 13 | # ------------------------------------------------------------------------------ 14 | tar cvf pialert_satellite/tar/pialert_satellite_latest.tar --no-mac-metadata --no-xattrs --exclude="pialert_satellite/tar" --exclude="pialert_satellite/.git" --exclude="pialert_satellite/.github" --exclude=".gitignore" --exclude=".DS_Store" pialert_satellite | wc -l 15 | 16 | --------------------------------------------------------------------------------