├── LICENSE ├── README.md └── gtp_dialer.py /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 | # GTPv1/GTPv2 Dialer 2 | This application is a GTP dialer to create sessions towards a SGW, PGW or GGSN. 3 | It can act as SGSN (gn/gp or S4), MME (S11), SGW (S5/S8), ePDG (S2b) or TWAG (S2a). 4 | The application implements not only the control plane, but also the user plane, so it's really useful to perform user plane tests for any APN, under specific conditions (IMSI, MSISDN, APN, IMEI, ULI, RAT, Charging Characteristics, Fixed IP APNs, DHCP, PDP Type, Authentication, etc...) 5 | 6 | After the PDP/PDN session is established, a tunnel is created with the IP(s) received from the GGSN/PGW. 7 | A default route is created pointing to the tunnel interface, so that applications can use the PDN/PDP established. 8 | 9 | There is an option to use Namespaces. 10 | PDP/PDN types ipv4, ipv6 and ipv4v6 are supported. 11 | 12 | The application has the following options: 13 | 14 | ``` 15 | root@ubuntu:/home/fabricio/Documents# python3 gtp_dialer.py -h 16 | Usage: gtp_dialer.py [options] 17 | 18 | Options: 19 | -h, --help show this help message and exit 20 | -t TUNNEL_TYPE, --tunnel_type=TUNNEL_TYPE 21 | tunnel Type: GTP (Default), GTPv2 22 | -d TUNNEL_DST_IP, --tunnel_dst_ip=TUNNEL_DST_IP 23 | tunnel IP GTP endpoint 24 | -i DEV_ID, --dev_id=DEV_ID 25 | tun/tap device index 26 | -a APN_NAME, --apn_name=APN_NAME 27 | APN name 28 | -I IMSI, --imsi=IMSI IMSI 29 | -M MSISDN, --msisdn=MSISDN 30 | MSISDN 31 | -p PDPTYPE, --pdptype=PDPTYPE 32 | PDP type (ipv4, ipv6 or ipv4v6) 33 | -s GTP_ADDRESS, --gtp_source_address=GTP_ADDRESS 34 | GTP source address (for GTP-C and GTP-U) 35 | -S IP_SOURCE_ADDRESS, --ip_source_address=IP_SOURCE_ADDRESS 36 | IP source address. If not specified, the bind is done 37 | for all IPs 38 | -g GATEWAY_IP_ADDRESS, --gateway_ip_address=GATEWAY_IP_ADDRESS 39 | gateway IP address 40 | -n NODETYPE, --nodetype=NODETYPE 41 | Node type (SGSN, MME, SGW, EPDG or TWAN) 42 | -E IMEI, --imei=IMEI IMEI 43 | -f FIXED_IPV4, --fixed_ipv4=FIXED_IPV4 44 | Static IPv4 for session 45 | -F FIXED_IPV6, --fixed_ipv6=FIXED_IPV6 46 | Static IPv6 for session 47 | -U USERNAME, --username=USERNAME 48 | username (for gtp proxy access) 49 | -P PASSWORD, --password=PASSWORD 50 | password (for gtp proxy access) 51 | -G GGSN, --ggsn=GGSN ggsn/pgw ip address (for gtp proxy access or when set 52 | to SGSN/MME node in GTPv2) 53 | -H PASSWORD_TO_HASH, --hash=PASSWORD_TO_HASH 54 | password hash calculation (for gtp proxy access) 55 | -v, --version version 56 | -u USERNAME_PCO, --username_pco=USERNAME_PCO 57 | username (for APN) 58 | -w PASSWORD_PCO, --password_pco=PASSWORD_PCO 59 | password (for APN) 60 | -A AUTHENTICATION_TYPE, --authentication_type=AUTHENTICATION_TYPE 61 | authentication type: PAP (default), CHAP 62 | -T TIMEOUT, --timeout=TIMEOUT 63 | timeout for session establishment 64 | -D, --dhcp Deferred IP allocation using DHCP (ipv4) 65 | -C CC, --cc=CC Charging Characteristics 66 | -O OPERATOR, --operator=OPERATOR 67 | Operator MCCMNC for ULI 68 | -R RAT, --rat=RAT Radio Access Type 69 | -Q, --quit Quit immediately after activating session 70 | -N NETNS, --netns=NETNS 71 | Name of network namespace for tun device 72 | -Z, --gtp-kernel Use GTP Kernel. Needs libgtpnl. 73 | root@ubuntu:/home/fabricio/Documents# 74 | ``` 75 | 76 | Example of using the application as SGW: 77 | 78 | ``` 79 | root@ubuntu:/home/fabricio/Documents# python3 gtp_dialer.py -d 172.16.168.5 -s 172.16.168.130 -a gtptester -n SGW -t GTPv2 -g 172.16.168.5 80 | 81 | _____ _______ _____ _____ _ _ 82 | / ____|__ __| __ \ | __ \(_) | | 83 | | | __ | | | |__) | | | | |_ __ _| | ___ _ __ 84 | | | |_ | | | | ___/ | | | | |/ _` | |/ _ \ '__| 85 | | |__| | | | | | | |__| | | (_| | | __/ | 86 | \_____| |_| |_| |_____/|_|\__,_|_|\___|_| by fasferraz@gmail (2012-2022) 87 | 88 | 1. Adding route to GGSN IP Address pointing to the current default gateway 89 | 2. Creating GTP-C Socket 90 | 3. Sending Create Session Request to SGW/PGW 91 | 4. Answer received and GTPv2 decoded. 92 | => PGW GTP-U IP Adresss: 172.16.168.5 93 | => PGW GTP-C IP Adresss: 172.16.168.5 94 | => End-User IPv4 Adresss: 192.168.255.2 95 | => TEID Data Remote: 2147491841 96 | => TEID Control Remote: 2147491841 97 | => DNS Addresses Ipv4: ['8.8.8.8', '8.8.4.4'] 98 | => DNS Addresses IPv6: None 99 | 5. Creating GTP-U Socket 100 | 6. Creating Tunnel Interface 101 | 7. DNS: Backing up current /etc/resolv.conf. Creating a new one: 102 | => Adding DNS IPv4 8.8.8.8 103 | => Adding DNS IPv4 8.8.4.4 104 | 8. Configuring End User Address in the Tunnel interface 105 | cmd: ip addr add 192.168.255.2/32 dev tun10 106 | 9.1 Adding default routes (0.0.0.0/1 and 128.0.0.0/1) pointing to the tunnel interface (to prevail over any current default route (0.0.0.0/0) already existing in the system) 107 | cmd: route add -net 0.0.0.0/1 gw 192.168.255.2 108 | cmd: route add -net 128.0.0.0/1 gw 192.168.255.2 109 | 10. Starting threads: GTP-U encapsulation and GTP-U decapsulation. 110 | 111 | Press q to quit 112 | 113 | ``` 114 | 115 | Example of using the application as MME (-G options is needed to set the PGW/GGSN IP Address): 116 | 117 | ``` 118 | root@ubuntu:/home/fabricio/Documents# python3 gtp_dialer.py -d 172.16.168.3 -s 172.16.168.130 -a gtptester -n MME -t GTPv2 -g 172.16.168.3 -G 172.16.168.5 119 | 120 | _____ _______ _____ _____ _ _ 121 | / ____|__ __| __ \ | __ \(_) | | 122 | | | __ | | | |__) | | | | |_ __ _| | ___ _ __ 123 | | | |_ | | | | ___/ | | | | |/ _` | |/ _ \ '__| 124 | | |__| | | | | | | |__| | | (_| | | __/ | 125 | \_____| |_| |_| |_____/|_|\__,_|_|\___|_| by fasferraz@gmail (2012-2022) 126 | 127 | 1. Adding route to GGSN IP Address pointing to the current default gateway 128 | 2. Creating GTP-C Socket 129 | 3. Sending Create Session Request to SGW/PGW 130 | 4. Answer received and GTPv2 decoded. 131 | => SGW GTP-U IP Adresss: 172.16.168.3 132 | => SGW GTP-C IP Adresss: 172.16.168.3 133 | => End-User IPv4 Adresss: 192.168.255.3 134 | => TEID Data Remote: 2147500033 135 | => TEID Control Remote: 2147500033 136 | => DNS Addresses Ipv4: ['8.8.8.8', '8.8.4.4'] 137 | => DNS Addresses IPv6: None 138 | 4.1. Sending Modify Bearer Request to SGW 139 | 5. Creating GTP-U Socket 140 | 6. Creating Tunnel Interface 141 | 7. DNS: Backing up current /etc/resolv.conf. Creating a new one: 142 | => Adding DNS IPv4 8.8.8.8 143 | => Adding DNS IPv4 8.8.4.4 144 | 8. Configuring End User Address in the Tunnel interface 145 | cmd: ip addr add 192.168.255.3/32 dev tun10 146 | 9.1 Adding default routes (0.0.0.0/1 and 128.0.0.0/1) pointing to the tunnel interface (to prevail over any current default route (0.0.0.0/0) already existing in the system) 147 | cmd: route add -net 0.0.0.0/1 gw 192.168.255.3 148 | cmd: route add -net 128.0.0.0/1 gw 192.168.255.3 149 | 10. Starting threads: GTP-U encapsulation and GTP-U decapsulation. 150 | 151 | Press q to quit 152 | ``` 153 | 154 | # Notes: 155 | - if you are running the application in a VM, the -s option (the GTP address present at GTP level) must match the output IP address that will reach the SGW/PGW/GGSN. 156 | - Use option -S to choose which IP source address to use when there are multiple interfaces in the OS. 157 | - Use option -g to set the gateway statically when there are multiple interfaces, and the SGW/PGW/GGSN is not reachable via the current default route, but through a different interface. This IP address will be used as the gateway for GTP-c and GTP-u traffic. 158 | 159 | # Updated version (2022/12/28): 160 | - Support of gtp kernel (libgtpnl and modprobe gtp) for default namespace. New option -Z 161 | - Still trying to see if I can do it also in namespace :) 162 | -------------------------------------------------------------------------------- /gtp_dialer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Example: 4 | python3 gtp_dialer.py -d 10.10.1.1 -a internet -g 172.16.62.2 -s 10.15.8.1 -n SGW -t GTPv2 5 | python3 gtp_dialer.py -d 10.10.1.2 -a internet -g 172.16.62.2 -s 10.15.8.1 -G 1.2.3.4 -n MME -t GTPv2 -f 10.128.1.2 -u testes@apnxpto -w paswordxpto 6 | 7 | 8 | ''' 9 | 10 | 11 | 12 | import sys 13 | 14 | if sys.platform != "linux" and sys.platform != "linux2": 15 | print("Operating system not supported. Exiting.\n") 16 | exit(1) 17 | 18 | import fcntl 19 | import os 20 | import struct 21 | import socket 22 | import subprocess 23 | import random 24 | import select 25 | import signal 26 | import hashlib 27 | import binascii 28 | 29 | import time 30 | from threading import Thread 31 | from optparse import OptionParser 32 | 33 | 34 | GTP_LOCAL_HOST = '' 35 | GTP_C_LOCAL_PORT = 2123 36 | GTP_C_REMOTE_PORT = 2123 37 | GTP_U_LOCAL_PORT = 2152 38 | GTP_U_REMOTE_PORT = 2152 39 | 40 | DEFAULT_IMSI = '123456789012345' 41 | DEFAULT_MSISDN = '1234567890' 42 | DEFAULT_IMEI = '1234567812345678' 43 | DEFAULT_OPERATOR = '12345' 44 | DEFAULT_APN = 'internet' 45 | 46 | DEFAULT_NSAPI = 5 47 | 48 | HASH_PASS = '123456qwertyasdfghzxcvbn' 49 | 50 | DHCP_CLIENT_NAME = 'GTP Dialer' 51 | 52 | ie_size = { 1:1, 2:8, 3:6, 4:4, 5:4, 8:1, 9:28, 11:1, 12:3, 13:1, 14:1, 15:1, 16:4, 17:4, 18:5, 19:1, 20:1, 21:1, 22:9, 23:1, 24:1, 25:2, 26:2, 27:2, 28:2, 29:1, 127:4 } 53 | 54 | class bcolors: 55 | BLUE = '\u001b[34m' 56 | YELLOW = '\u001b[33m' 57 | GREEN = '\u001b[32m' 58 | RED = '\u001b[31m' 59 | ENDC = '\033[0m' 60 | BOLD = '\033[1m' 61 | BACKGROUNDBLACK = '\u001b[40m' 62 | 63 | def bytes2hex(byteArray): 64 | return ''.join(hex(i).replace("0x", "0x0")[-2:] for i in byteArray) 65 | 66 | def hex2bytes(hexString): 67 | return bytearray.fromhex(hexString) 68 | 69 | 70 | def mac2str(mac): 71 | mac_hex = bytes2hex(mac) 72 | mac_str = '' 73 | for i in range(0,len(mac_hex),2): 74 | mac_str += mac_hex[i:i+2] + ':' 75 | return mac_str[:-1] 76 | 77 | def str2bytes(word): 78 | str_bytes = word.encode() 79 | return str_bytes 80 | 81 | def bytes_to_int(b): 82 | return int(binascii.hexlify(b),16) 83 | 84 | def int_to_bytes(i): 85 | return struct.pack("!I",i) 86 | 87 | def checksum_carry_around_add(a,b): 88 | c = bytes_to_int(a) + bytes_to_int(b) 89 | c = int_to_bytes(c) 90 | r = (bytes_to_int(c) & bytes_to_int(b'\x00\x00\xFF\xFF')) + (bytes_to_int(c) >> 16) 91 | r = int_to_bytes(r) 92 | return r 93 | 94 | def checksum(msg): 95 | s = b'\x00\x00' 96 | 97 | #padding 98 | if len(msg) % 2 !=0: 99 | msg += b'\x00' 100 | 101 | for i in range(0, len(msg), 2): 102 | w = struct.pack("!BB",int(msg[i]), int(msg[i+1])) 103 | s = checksum_carry_around_add(s,w) 104 | 105 | r = int_to_bytes(~bytes_to_int(s) & bytes_to_int(b'\x00\x00\xFF\xFF')) 106 | 107 | #print("checksum: " + str(r[2:])) 108 | 109 | return r[2:] 110 | 111 | 112 | 113 | def dhcp_option(id, size, value): 114 | return struct.pack("!B", id) + struct.pack("!B", size) + value 115 | 116 | 117 | def dhcp_request_packet(dhcp_type, xid, mac, ip): 118 | op = b'\x01' # Boot Request 119 | htype = b'\x01' # Ethernet 120 | hlen = b'\x06' # 6 bytes (MAC addr) 121 | hops = b'\x00' # 0 hop (hop > 1 when DHCP Relay) 122 | #xid = b'\x00\x00\x00\x00' # Transaction ID, a random number chosen by the client, used by the client and server to associate messages and responses between a client and a server. 123 | secs = b'\x00\x00' # Filled in by client, seconds elapsed since client began address acquisition or renewal process 124 | flags = b'\x00\x00' # Unicast 125 | ciaddr = str2ip("0.0.0.0") # Client IP address; only filled in if client is in BOUND, RENEW or REBINDING state and can respond to ARP requests. 126 | yiaddr = str2ip("0.0.0.0") # 'your' (client) IP address 0.0.0.0 in requests 127 | siaddr = str2ip("0.0.0.0") # IP address of next server to use in bootstrap; returned in DHCPOFFER, DHCPACK by server. 128 | giaddr = str2ip("0.0.0.0") # Relay agent IP address, used in booting via a relay agent. 129 | chaddr = mac + bytes(10) # Client hardware address (16 bytes) 130 | sname = bytes(64) # Optional server host name, null terminated string. (64 bytes) 131 | file = bytes(128) # Boot file name, null terminated string; "generic" name or null in DHCPDISCOVER, fully qualified directory-path name in DHCPOFFER. (128 bytes) 132 | magic = b'\x63\x82\x53\x63' # RFC 951 133 | 134 | opt_dhcp_type = dhcp_option(53,1, struct.pack("!B", dhcp_type)) 135 | opt_dhcp_client_identifier = dhcp_option(61,7, b'\x01' + mac) 136 | opt_dhcp_hostname = dhcp_option(12,len(DHCP_CLIENT_NAME)+17, str2bytes(DHCP_CLIENT_NAME + mac2str(mac))) 137 | 138 | if ip == '': 139 | opt_ip = '' 140 | else: 141 | opt_ip = dhcp_option(50,4, ip) 142 | 143 | opt_dhcp_parameter_request_list = dhcp_option(55,9, b'\x01\x21\x03\x06\x0f\x1c\x33\x3a\x3b') 144 | opt_dhcp_end = b'\xff' 145 | 146 | p = op + htype + hlen + hops + xid + secs + flags 147 | p = p + ciaddr + yiaddr + siaddr + giaddr + chaddr + sname + file + magic 148 | p = p + opt_dhcp_type 149 | p = p + opt_dhcp_client_identifier 150 | p = p + opt_dhcp_hostname 151 | if opt_ip != '': 152 | p = p + opt_ip 153 | p = p + opt_dhcp_parameter_request_list 154 | p = p + opt_dhcp_end 155 | 156 | return p 157 | 158 | def dhcp_decode(dhcp_packet): 159 | dhcp_param = dict() 160 | dhcp_param["op"] = dhcp_packet[0:1] 161 | dhcp_param["htype"] = dhcp_packet[1:2] 162 | dhcp_param["hlen"] = dhcp_packet[2:3] 163 | dhcp_param["hops"] = dhcp_packet[3:4] 164 | dhcp_param["xid"] = dhcp_packet[4:8] 165 | dhcp_param["secs"] = dhcp_packet[8:10] 166 | dhcp_param["flags"] = dhcp_packet[10:12] 167 | dhcp_param["ciaddr"] = dhcp_packet[12:16] 168 | dhcp_param["yiaddr"] = dhcp_packet[16:20] 169 | dhcp_param["siaddr"] = dhcp_packet[20:24] 170 | dhcp_param["giaddr"] = dhcp_packet[24:28] 171 | dhcp_param["chaddr"] = dhcp_packet[28:34] 172 | dhcp_param["sname"] = dhcp_packet[44:108] 173 | dhcp_param["file"] = dhcp_packet[108:236] 174 | dhcp_param["magic"] = dhcp_packet[236:240] 175 | 176 | pointer = 240 177 | 178 | while pointer < len(dhcp_packet): 179 | if dhcp_packet[pointer:pointer+1] == b'\xff': 180 | break 181 | else: 182 | t = struct.unpack('!B', dhcp_packet[pointer:pointer+1])[0] 183 | l = struct.unpack('!B', dhcp_packet[pointer+1:pointer+2])[0] 184 | dhcp_param[str(t)] = dhcp_packet[pointer+2:pointer+2+l] 185 | pointer = pointer + 2 + l 186 | 187 | return dhcp_param 188 | 189 | 190 | 191 | def udp_header(scr_port, dst_port, payload_length): 192 | 193 | udp_src_port = struct.pack("!H", scr_port) 194 | udp_dst_port = struct.pack("!H", dst_port) 195 | udp_length = struct.pack("!H", payload_length + 8) #add UDP 8 byte header 196 | udp_checksum = struct.pack("!H", 0) 197 | 198 | return udp_src_port + udp_dst_port + udp_length + udp_checksum 199 | 200 | 201 | 202 | def ip_header_with_length(source_address, destination_address, protocol, calc_checksum, payload_length): 203 | ip_version_and_header_length = b'\x45' 204 | ip_dscp = b'\x00' 205 | ip_total_length = struct.pack("!H", 20 + payload_length) 206 | #ip_total_length = b'\x00\x00' 207 | ip_identification = struct.pack("!H", 0) 208 | ip_flags_and_fragment_offset = b'\x40\x00' 209 | ip_ttl = struct.pack("!B", 64) 210 | ip_protocol = struct.pack("!B", protocol) 211 | ip_header_checksum = b'\x00\x00' 212 | ip_source_addr = str2ip(source_address) 213 | ip_destination_addr = str2ip(destination_address) 214 | 215 | h_begin = ip_version_and_header_length + ip_dscp + ip_total_length + ip_identification + ip_flags_and_fragment_offset + ip_ttl + ip_protocol 216 | h_end = ip_source_addr + ip_destination_addr 217 | 218 | if calc_checksum == 1: 219 | ip_header_checksum = checksum(h_begin + ip_header_checksum + h_end) 220 | 221 | return h_begin + ip_header_checksum + h_end 222 | 223 | 224 | def ip2str(ip_bytes): 225 | return socket.inet_ntop(socket.AF_INET,ip_bytes) 226 | 227 | def str2ip(ip_str): 228 | return socket.inet_aton(ip_str) 229 | 230 | def gtp_u_header(teid, length): 231 | 232 | gtp_flags = b'\x30' 233 | gtp_message_type = b'\xff' 234 | gtp_length = struct.pack("!H", length) 235 | gtp_teid = struct.pack("!I", teid) 236 | 237 | return gtp_flags + gtp_message_type + gtp_length + gtp_teid 238 | 239 | 240 | def open_tun(n): 241 | TUNSETIFF = 0x400454ca 242 | IFF_TUN = 0x0001 243 | IFF_TAP = 0x0002 244 | IFF_NO_PI = 0x1000 # No Packet Information - to avoid 4 extra bytes 245 | 246 | TUNMODE = IFF_TUN | IFF_NO_PI 247 | MODE = 0 248 | DEBUG = 0 249 | if sys.platform == "linux" or sys.platform == "linux2": 250 | f = os.open("/dev/net/tun", os.O_RDWR) 251 | ifs = fcntl.ioctl(f, TUNSETIFF, struct.pack("16sH", bytes("tun%d" % n, "utf-8"), TUNMODE)) 252 | #ifname = ifs[:16].strip("\x00") 253 | subprocess.call("ifconfig tun%d up" % n, shell=True) 254 | 255 | return f 256 | 257 | def bcd(chars): 258 | 259 | bcd_string = "" 260 | for i in range(len(chars) // 2): 261 | bcd_string += chars[1+2*i] + chars[2*i] 262 | bcd_bytes = bytearray.fromhex(bcd_string) 263 | 264 | return bcd_bytes 265 | 266 | 267 | ###### GTPv1 ###### 268 | 269 | def add_imsi(imsi): 270 | if len(imsi) % 2 == 1: 271 | imsi += "f" 272 | imsi = bcd(imsi) 273 | return b'\x02' + imsi 274 | 275 | def add_selection_mode(sel_mode): 276 | return b'\x0f' + bytes([(252+int(sel_mode)) % 256]) 277 | 278 | def add_random_teid(teid_type): 279 | global teid_local_control, teid_local_data 280 | 281 | rand_number = random.randrange(pow(2,32)-1) 282 | if teid_type == "data": 283 | teid_local_data = rand_number 284 | return b'\x10' + struct.pack("!L", rand_number) 285 | elif teid_type == "control": 286 | teid_local_control = rand_number 287 | return b'\x11' + struct.pack("!L", rand_number) 288 | 289 | def add_nsapi(value): 290 | return b'\x14' + struct.pack("!B", value % 256) 291 | 292 | def add_eua_ipv4(): 293 | return b'\x80\x00\x02\xf1\x21' 294 | 295 | def add_eua_ipv6(): 296 | return b'\x80\x00\x02\xf1\x57' 297 | 298 | def add_eua_ipv4v6(): 299 | return b'\x80\x00\x02\xf1\x8d' 300 | 301 | def add_apn(apn): 302 | apn_bytes = bytes() 303 | apn_list = apn.split(".") 304 | 305 | for word in apn_list: 306 | apn_bytes += struct.pack("!B", len(word)) + word.encode() 307 | return b'\x83\x00' + struct.pack("!B",len(apn_bytes)) + apn_bytes 308 | 309 | def add_gsn_address(address): 310 | return b'\x85\x00\x04' + str2ip(address) 311 | 312 | def add_msisdn(msisdn): 313 | if len(msisdn) % 2 == 1: 314 | msisdn += "f" 315 | msisdn = bcd(msisdn) 316 | return b'\x86' + struct.pack("!H", len(msisdn) + 1) + b'\x91' + msisdn 317 | 318 | def return_random_bytes(size): 319 | if size == 0: return b'' 320 | if size == 4: return struct.pack('!I', random.randrange(pow(2,32)-1)) 321 | if size == 8: return struct.pack('!Q', random.randrange(pow(2,64)-1)) 322 | if size == 16: return struct.pack('!Q', random.randrange(pow(2,64)-1)) + struct.pack('!Q', random.randrange(pow(2,64)-1)) 323 | 324 | def add_pco(pdptype, username, password, dhcp_flag, authentication_type): 325 | len_pco = 0 326 | pap = b'' 327 | chap = b'' 328 | dhcp = b'' 329 | if username != None and password != None: 330 | if authentication_type == 'PAP': 331 | len_username = struct.pack("!B", len(username)) 332 | username = username.encode() 333 | len_password = struct.pack("!B", len(password)) 334 | password = password.encode() 335 | len_pap_2B = struct.pack("!H", len(username)+len(password) + 6) 336 | len_pap_1B = struct.pack("!B", len(username)+len(password) + 6) 337 | len_pco = len(username)+len(password) + 6 + 3 338 | pap = b'\xc0\x23' + len_pap_1B + b'\x01\x01' + len_pap_2B + len_username + username + len_password + password 339 | chap = b'' 340 | elif authentication_type == 'CHAP': 341 | value = return_random_bytes(16) 342 | name = b'GTP Dialer' 343 | length = struct.pack("!H", len(value) + len(name) + 5) 344 | chap_challenge = b'\xc2\x23' + length[-1:] + b'\x01\x01' + length + b'\x10' + value + name 345 | username = username.encode() 346 | password = password.encode() 347 | m = hashlib.md5() 348 | m.update(b'\x01' + password + value) 349 | hash = m.digest() 350 | length = struct.pack("!H", len(hash) + len(username) + 5) 351 | chap_response = b'\xc2\x23' + length[-1:] + b'\x02\x01' + length + b'\x10' + hash + username 352 | chap = chap_challenge + chap_response 353 | len_pco = len(chap) 354 | pap = b'' 355 | 356 | if dhcp_flag == True: 357 | dhcp = b'\x00\x0b\x00' 358 | len_pco += 3 359 | 360 | if pdptype == "ipv4": 361 | len_pco = struct.pack("!H", 35 + len_pco) 362 | return b'\x84' + len_pco + b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x0c\x00' + pap + chap + dhcp 363 | elif pdptype == "ipv6": 364 | len_pco = struct.pack("!H", 7 + len_pco) 365 | return b'\x84' + len_pco + b'\x80\x00\x03\x00\x00\x01\x00' + pap + chap + dhcp 366 | elif pdptype == "ipv4v6": 367 | len_pco = struct.pack("!H", 41 + len_pco) 368 | return b'\x84' + len_pco + b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x03\x00\x00\x0c\x00\x00\x01\x00' + pap + chap + dhcp 369 | 370 | def add_qos(): 371 | # quick version. requests 70Mbits DL and 5.8Mbits UL 372 | return b'\x87\x00\x0f\x01\x23\x43\x1f\x73\x96\xd2\xfe\x74\x83\xff\xff\x00\x80\x00' 373 | 374 | def add_rat(rat): 375 | return b'\x97\x00\x01' + bytes([rat]) 376 | 377 | def add_common_flags(): 378 | return b'\x94\x00\x01\x80' 379 | 380 | def add_imei(imei): 381 | if len(imei) % 2 == 1: 382 | imei += "f" 383 | imei = bcd(imei) 384 | return b'\x9a' + struct.pack("!H", len(imei)) + imei 385 | 386 | def add_private_extension(identifier, value, value2): 387 | if identifier == 0: 388 | value_bytes = b'\x7a\x57\x00' 389 | value_bytes += value.encode() 390 | elif identifier == 1: 391 | m = hashlib.md5() 392 | n = hashlib.sha1() 393 | m.update((value + HASH_PASS).encode()) 394 | m_digest_password = m.digest() 395 | n.update(m_digest_password + HASH_PASS.encode() + value2) #value2 == TEID Control 396 | value_bytes = b'\x7a\x57\x01' 397 | value_bytes += n.digest() 398 | elif identifier == 2: 399 | value_bytes = b'\x7a\x57\x02' 400 | value_bytes += socket.inet_aton(value) 401 | return b'\xff\x00' + struct.pack("!B",len(value_bytes)) + value_bytes 402 | 403 | 404 | ### GTPv1 messages ### 405 | def cpc_request(apn, gtp_address, imsi, msisdn, pdptype, username, password, ggsn, username_pco, password_pco, dhcp, cc, operator, imei, authentication_type, rat, sel_mode, gtp_u_address): 406 | 407 | global sequence_number 408 | 409 | gtp_flags = b'\x32' 410 | gtp_message_type = b'\x10' 411 | gtp_length = b'\x00\x00' #length = 0. filled in the end 412 | gtp_teid = b'\x00\x00\x00\x00' 413 | gtp_sequence_number = struct.pack("!H", sequence_number) 414 | gtp_n_pdu = b'\x00' 415 | gtp_next_extension_header = b'\x00' 416 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header 417 | 418 | gtp_imsi = add_imsi(imsi) 419 | gtp_routing_area_identity = add_routing_area_identity(operator) 420 | gtp_selection_mode = add_selection_mode(sel_mode) 421 | gtp_teid_local_data = add_random_teid("data") 422 | gtp_teid_local_control = add_random_teid("control") 423 | gtp_nsapi = add_nsapi(DEFAULT_NSAPI) 424 | gtp_cc = b'\x1a' + hex2bytes(cc) 425 | 426 | if pdptype == "ipv4": 427 | gtp_end_user_address = add_eua_ipv4() 428 | elif pdptype == "ipv6": 429 | gtp_end_user_address = add_eua_ipv6() 430 | elif pdptype == "ipv4v6": 431 | gtp_end_user_address = add_eua_ipv4v6() 432 | gtp_apn = add_apn(apn) 433 | gtp_pco = add_pco(pdptype, username_pco, password_pco, dhcp, authentication_type) 434 | gtp_gsn_address = add_gsn_address(gtp_address) 435 | gtp_gsn_u_address = add_gsn_address(gtp_u_address) 436 | gtp_msisdn = add_msisdn(msisdn) 437 | gtp_qos = add_qos() 438 | gtp_common_flags = add_common_flags() 439 | if rat is None: 440 | gtp_rat = add_rat(1) 441 | else: 442 | gtp_rat = add_rat(int(rat)) 443 | gtp_imei = add_imei(imei) 444 | 445 | gtp_ie = gtp_imsi + gtp_routing_area_identity + gtp_selection_mode + gtp_teid_local_data + gtp_teid_local_control + gtp_nsapi + gtp_cc + gtp_end_user_address + gtp_apn + gtp_pco + gtp_gsn_address + gtp_gsn_u_address + gtp_msisdn + gtp_qos + gtp_common_flags + gtp_rat + gtp_imei 446 | 447 | if username is not None and password is not None: 448 | gtp_pe1 = add_private_extension(0, username,None) 449 | gtp_pe2 = add_private_extension(1, password, gtp_teid_local_control[1:]) 450 | gtp_ie += gtp_pe1 + gtp_pe2 451 | if ggsn is not None: 452 | gtp_pe3 = add_private_extension(2, ggsn, None) 453 | gtp_ie += gtp_pe3 454 | 455 | cpc_packet = bytearray(gtp_header + gtp_ie) 456 | 457 | length = len(cpc_packet) - 8 458 | cpc_packet[3] = length % 256 459 | cpc_packet[2] = length // 256 460 | 461 | sequence_number +=1 462 | 463 | return cpc_packet 464 | 465 | 466 | def dpc_request(teid): 467 | 468 | global sequence_number 469 | 470 | gtp_flags = b'\x32' 471 | gtp_message_type = b'\x14' 472 | gtp_length = b'\x00\x08' 473 | gtp_teid = struct.pack("!L", teid) 474 | gtp_sequence_number = struct.pack("!H", sequence_number) 475 | gtp_n_pdu = b'\x00' 476 | gtp_next_extension_header = b'\x00' 477 | gtp_teardown_nsapi = b'\x13\xff\x14' + bytes([DEFAULT_NSAPI]) 478 | 479 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header 480 | 481 | sequence_number +=1 482 | 483 | return gtp_header + gtp_teardown_nsapi 484 | 485 | 486 | def dpc_response(teid, request_seq_num): 487 | 488 | gtp_flags = b'\x32' 489 | gtp_message_type = b'\x15' 490 | gtp_length = b'\x00\x06' 491 | gtp_teid = struct.pack("!L", teid) 492 | gtp_sequence_number = request_seq_num 493 | gtp_n_pdu = b'\x00' 494 | gtp_next_extension_header = b'\x00' 495 | 496 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header 497 | 498 | gtp_cause = b'\x01\x80' 499 | 500 | return gtp_header + gtp_cause 501 | 502 | 503 | def upc_response(teid, request_seq_num, qos): 504 | 505 | gtp_flags = b'\x32' 506 | gtp_message_type = b'\x13' 507 | gtp_length = b'\x00\x00' 508 | gtp_teid = struct.pack("!L", teid) 509 | gtp_sequence_number = request_seq_num 510 | gtp_n_pdu = b'\x00' 511 | gtp_next_extension_header = b'\x00' 512 | 513 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header 514 | 515 | gtp_cause = b'\x01\x80' 516 | 517 | upc_packet = bytearray(gtp_header + gtp_cause) 518 | if qos != None: 519 | gtp_qos = b'\x87' + struct.pack("!H",len(qos)) + qos 520 | upc_packet += bytearray(gtp_qos) 521 | 522 | length = len(upc_packet) - 8 523 | 524 | upc_packet[3] = length % 256 525 | upc_packet[2] = length // 256 526 | 527 | return upc_packet 528 | 529 | 530 | 531 | # Version not ready for extension headers. Validates TEID and cause=Requested Accepted in case of answer messages 532 | # Uses a dictionary. Index is the IE, value are the data bytes. Length bytes (when they do exist) are discarted 533 | def decode_gtpc(gtp_packet): 534 | global request_sequence_number 535 | 536 | valid = 0 537 | 538 | if int(gtp_packet[0]) // 16 == 3 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 1: #Response and Cause =128,129,130 539 | if int(gtp_packet[0]) % 16 == 0 and (gtp_packet[8:10] == b'\x01\x80' or gtp_packet[8:10] == b'\x01\x81' or gtp_packet[8:10] == b'\x01\x82'): 540 | pointer = 8 541 | valid = 1 542 | elif int(gtp_packet[0:1]) % 16 < 4 and (gtp_packet[12:14] == b'\x01\x80' or gtp_packet[12:14] == b'\x01\x81' or gtp_packet[12:14] == b'\x01\x82'): 543 | pointer = 12 544 | valid = 1 545 | 546 | # Proxy specific: if returned error is 240 - it means authentication is needed 547 | elif (int(gtp_packet[0]) % 16 == 0 and gtp_packet[8:10] == b'\x01\xF0') or (int(gtp_packet[0]) % 16 < 4 and gtp_packet[12:14] == b'\x01\xF0'): 548 | return 240 549 | # Proxy specific: if returned error is 239 - it means authentication is wrong 550 | elif (int(gtp_packet[0]) % 16 == 0 and gtp_packet[8:10] == b'\x01\xef') or (int(gtp_packet[0]) % 16 < 4 and gtp_packet[12:14] == b'\x01\xef'): 551 | return 239 552 | 553 | elif int(gtp_packet[0]) // 16 == 3 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 0: #Requests 554 | if int(gtp_packet[0]) % 16 == 0: 555 | pointer = 8 556 | valid = 1 557 | request_sequence_number = None 558 | elif int(gtp_packet[0]) % 16 < 4: 559 | pointer = 12 560 | valid = 1 561 | if int(gtp_packet[0]) % 16 > 1: 562 | request_sequence_number = gtp_packet[8:10] 563 | 564 | if valid == 1: 565 | decode_dict = {} 566 | while pointer < len(gtp_packet): 567 | if gtp_packet[pointer] < 128: 568 | decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+1:pointer+1+ie_size[gtp_packet[pointer]]] 569 | pointer += 1+ie_size[gtp_packet[pointer]] 570 | else: 571 | length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2] 572 | if gtp_packet[pointer] == 133: 573 | # 133 is the first GSN (control) and 1133 is the second GSN (user plane) 574 | if 133 in decode_dict: 575 | decode_dict[1133] = gtp_packet[pointer+3:pointer+3+length] 576 | else: 577 | decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+3:pointer+3+length] 578 | else: 579 | decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+3:pointer+3+length] 580 | pointer += 3 + length 581 | 582 | return decode_dict 583 | else: 584 | return None 585 | 586 | 587 | ####### Endof GTPv1 ####### 588 | 589 | ############################################################################################################################################################### 590 | 591 | ####### GTPv2 ########## 592 | 593 | 594 | def decode_gtpc_v2(gtp_packet): 595 | global request_sequence_number 596 | 597 | valid = 0 598 | response = False 599 | if int(gtp_packet[0]) // 16 == 4 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 1: #Response 600 | pointer = 12 601 | valid = 1 602 | response = True 603 | 604 | elif int(gtp_packet[0]) // 16 == 4 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 0: #Requests 605 | pointer = 12 606 | valid = 1 607 | request_sequence_number = gtp_packet[8:11] 608 | 609 | if valid == 1: 610 | decode_dict = {} 611 | while pointer < len(gtp_packet): 612 | type = gtp_packet[pointer] 613 | instance = gtp_packet[pointer + 3] 614 | length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2] 615 | 616 | decode_dict[(type,instance)]= gtp_packet[pointer+4:pointer+4+length] 617 | pointer += 4 + length 618 | if response: 619 | if (2,0) in decode_dict: # Cause 620 | if decode_dict[(2,0)][0:1] == b'\x10' or decode_dict[(2,0)][0:1] == b'\x11' or decode_dict[(2,0)][0:1] == b'\x12' or decode_dict[(2,0)][0:1] == b'\x13': 621 | return decode_dict 622 | else: 623 | return -1 624 | else: 625 | return -1 626 | return decode_dict 627 | else: 628 | return None 629 | 630 | 631 | def decode_ie_v2(gtp_packet): 632 | 633 | decode_dict = {} 634 | pointer = 0 635 | while pointer < len(gtp_packet): 636 | type = gtp_packet[pointer] 637 | instance = gtp_packet[pointer + 3] 638 | length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2] 639 | 640 | decode_dict[(type,instance)]= gtp_packet[pointer+4:pointer+4+length] 641 | pointer += 4 + length 642 | return decode_dict 643 | 644 | 645 | def add_imsi_v2( instance, imsi): 646 | if len(imsi) % 2 == 1: 647 | imsi += "f" 648 | imsi = bcd(imsi) 649 | return b'\x01' + struct.pack("!H", len(imsi)) + struct.pack("!B",instance) + imsi 650 | 651 | def add_imei_v2( instance, imei): 652 | if len(imei) % 2 == 1: 653 | imei += "f" 654 | imei = bcd(imei) 655 | return b'\x4b' + struct.pack("!H", len(imei)) + struct.pack("!B",instance) + imei 656 | 657 | def add_msisdn_v2(instance, msisdn): 658 | if len(msisdn) % 2 == 1: 659 | msisdn += "f" 660 | msisdn = bcd(msisdn) 661 | return b'\x4c' + struct.pack("!H", len(msisdn)) + struct.pack("!B",instance) + msisdn 662 | 663 | def add_serving_network_v2(instance, mccmnc): 664 | if len(mccmnc)==5: 665 | mnc3 = 'f' 666 | else: 667 | mnc3 = mccmnc[5] 668 | return b'\x53' + struct.pack("!H", 3) + struct.pack("!B",instance) + bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4]) 669 | 670 | def add_routing_area_identity(mccmnc): 671 | if len(mccmnc)==5: 672 | mnc3 = 'f' 673 | else: 674 | mnc3 = mccmnc[5] 675 | return b'\x03' + bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4]) + b'\xff\xfe\xff' 676 | 677 | def add_user_location_info_v2(instance, mccmnc, rat): # rat = 1 (sgsn) or 6 (mme ou sgw) 678 | if len(mccmnc)==5: 679 | mnc3 = 'f' 680 | else: 681 | mnc3 = mccmnc[5] 682 | mcc_mnc = bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4]) # 3 bytes 683 | 684 | if rat == 1: 685 | return b'\x56' + struct.pack("!H", 8) + struct.pack("!B",instance) + b'\x02' + mcc_mnc + b'\x00\x01\x00\x01' 686 | else: 687 | return b'\x56' + struct.pack("!H", 13) + struct.pack("!B",instance) + b'\x18' + mcc_mnc + b'\x00\x01' + mcc_mnc + b'\x00\x00\x00\x01' 688 | 689 | 690 | def add_rat_v2(instance, rat): # rat = 1 (sgsn) or 6 (mme ou sgw) or 3 (epdg, twan) but user can also set RAT to test erroneous scenarios 691 | return b'\x52' + struct.pack("!H", 1) + struct.pack("!B",instance) + bytes([rat]) 692 | 693 | def add_indication_v2(instance, b1, b2, b3, b4, b5, b6): 694 | return b'\x4d' + struct.pack("!H", 6) + struct.pack("!B",instance) + bytes([b1,b2,b3,b4,b5,b6]) 695 | 696 | def add_random_f_teid_v2(instance, int_type, ip, teid): # if teid=0 it generates a new random TEID, else it uses the received value (used in modify bearer) 697 | global teid_local_control, teid_local_data 698 | 699 | if teid==0: 700 | rand_number = random.randrange(pow(2,32)-1) 701 | else: 702 | rand_number = teid 703 | 704 | if int_type == "s11_c_mme": 705 | teid_local_control = rand_number 706 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+10]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 707 | 708 | elif int_type == "s5_c_sgw": 709 | teid_local_control = rand_number 710 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+6]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 711 | 712 | elif int_type == "s5_c_pgw": 713 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+7]) + struct.pack("!L", 0) + socket.inet_aton(ip) 714 | 715 | elif int_type == "s2b_c_pgw": 716 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+32]) + struct.pack("!L", 0) + socket.inet_aton(ip) 717 | 718 | elif int_type == "s2a_c_pgw": 719 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+36]) + struct.pack("!L", 0) + socket.inet_aton(ip) 720 | 721 | elif int_type == "s4_c_sgsn": 722 | teid_local_control = rand_number 723 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+17]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 724 | 725 | elif int_type == "s1_u_enb": 726 | teid_local_data = rand_number 727 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+0]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 728 | 729 | elif int_type == "s4_u_sgsn": 730 | teid_local_data = rand_number 731 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+15]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 732 | 733 | elif int_type == "s5_u_sgw": 734 | teid_local_data = rand_number 735 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+4]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 736 | 737 | elif int_type == "s2b_c_epdg": 738 | teid_local_control = rand_number 739 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+30]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 740 | 741 | elif int_type == "s2b_u_epdg": 742 | teid_local_data = rand_number 743 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+31]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 744 | 745 | elif int_type == "s2a_c_twan": 746 | teid_local_control = rand_number 747 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+35]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 748 | 749 | elif int_type == "s2a_u_twan": 750 | teid_local_data = rand_number 751 | return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+34]) + struct.pack("!L", rand_number) + socket.inet_aton(ip) 752 | 753 | 754 | 755 | def add_apn_v2(instance,apn,operator): 756 | apn_bytes = bytes() 757 | if len(operator)==5: 758 | apn = apn + '.mnc0' + operator [3:5] + '.mcc' + operator [0:3] + '.gprs' 759 | else: 760 | apn = apn + '.mnc' + operator [3:6] + '.mcc' + operator [0:3] + '.gprs' 761 | 762 | apn_l = apn.split(".") 763 | 764 | for word in apn_l: 765 | apn_bytes += struct.pack("!B", len(word)) + word.encode() 766 | return b'\x47' + struct.pack("!H",len(apn_bytes)) + struct.pack("!B",instance) + apn_bytes 767 | 768 | def add_selection_mode_v2(sel_mode): 769 | return b'\x80\x00\x01\x00' + bytes([int(sel_mode) % 256]) 770 | 771 | def add_pco_v2(pdptype, username, password, dhcp_flag, authentication_type, node): 772 | len_pco = 0 773 | pap = b'' 774 | chap = b'' 775 | dhcp = b'' 776 | if username != None and password != None: 777 | if authentication_type == 'PAP': 778 | len_username = struct.pack("!B", len(username)) 779 | username = username.encode() 780 | len_password = struct.pack("!B", len(password)) 781 | password = password.encode() 782 | len_pap_2B = struct.pack("!H", len(username)+len(password) + 6) 783 | len_pap_1B = struct.pack("!B", len(username)+len(password) + 6) 784 | len_pco = len(username)+len(password) + 6 + 3 785 | pap = b'\xc0\x23' + len_pap_1B + b'\x01\x01' + len_pap_2B + len_username + username + len_password + password 786 | chap = b'' 787 | elif authentication_type == 'CHAP': 788 | value = return_random_bytes(16) 789 | name = b'GTP Dialer' 790 | length = struct.pack("!H", len(value) + len(name) + 5) 791 | chap_challenge = b'\xc2\x23' + length[-1:] + b'\x01\x01' + length + b'\x10' + value + name 792 | 793 | username = username.encode() 794 | password = password.encode() 795 | m = hashlib.md5() 796 | m.update(b'\x01' + password + value) 797 | hash = m.digest() 798 | length = struct.pack("!H", len(hash) + len(username) + 5) 799 | chap_response = b'\xc2\x23' + length[-1:] + b'\x02\x01' + length + b'\x10' + hash + username 800 | 801 | chap = chap_challenge + chap_response 802 | len_pco = len(chap) 803 | pap = b'' 804 | 805 | if dhcp_flag == True: 806 | dhcp = b'\x00\x0b\x00' 807 | len_pco += 3 808 | 809 | if node in ("SGSN", "MME", "SGW"): 810 | ie_type = b'\x4e' # PCO 811 | else: 812 | ie_type = b'\xa3' # Additional PCO (APCO) for ePDG and TWAN 813 | 814 | if pdptype == "ipv4": 815 | len_pco = struct.pack("!H", 35 + len_pco) 816 | return ie_type + len_pco + b'\x00\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x0c\x00' + pap + chap + dhcp 817 | elif pdptype == "ipv6": 818 | len_pco = struct.pack("!H", 7 + len_pco) 819 | return ie_type + len_pco + b'\x00\x80\x00\x03\x00\x00\x01\x00' + pap + chap + dhcp 820 | 821 | elif pdptype == "ipv4v6": 822 | len_pco = struct.pack("!H", 41 + len_pco) 823 | return ie_type + len_pco + b'\x00\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x03\x00\x00\x0c\x00\x00\x01\x00' + pap + chap + dhcp 824 | 825 | def add_pdn_type_v2(instance,pdn_type): 826 | return b'\x63\x00\x01\x00' + bytes([pdn_type]) 827 | 828 | def add_pdn_address_v2(instance, pdn_type, ipv4, ipv6): 829 | if pdn_type == 1: 830 | return b'\x4f' + struct.pack("!H",5) + struct.pack("!B",instance) + bytes([pdn_type]) + socket.inet_aton(ipv4) 831 | elif pdn_type == 2: 832 | return b'\x4f' + struct.pack("!H",18) + struct.pack("!B",instance) + bytes([pdn_type]) + b'\x00' + socket.inet_pton(socket.AF_INET6, ipv6) 833 | elif pdn_type == 3: 834 | return b'\x4f' + struct.pack("!H",22) + struct.pack("!B",instance) + bytes([pdn_type]) + b'\x00' + socket.inet_pton(socket.AF_INET6, ipv6) + socket.inet_aton(ipv4) 835 | 836 | def add_apn_restriction_v2(): 837 | return b'\x7f\x00\x01\x00\x00' 838 | 839 | def add_ambr_v2(): 840 | return b'\x48\x00\x08\x00\x00\x0f\x42\x40\x00\x0f\x42\x40' 841 | 842 | def add_ebi_v2(instance,ebi): 843 | return b'\x49\x00\x01' + struct.pack("!B",instance) + bytes([ebi]) 844 | 845 | def add_bearer_qos_v2(instance, qci): 846 | return b'\x50\x00\x16' + struct.pack("!B",instance) + b'\x55' + struct.pack("!B",int(qci)) + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 847 | 848 | def add_bearer_context_v2(instance, payload_bytes): 849 | return b'\x5d' + struct.pack("!H",len(payload_bytes)) + struct.pack("!B",instance) + payload_bytes 850 | 851 | def add_timezone_v2(): 852 | return b'\x72\x00\x02\x00\x8f\x02' 853 | 854 | 855 | ### GTPv2 messages ### 856 | def create_session_request(apn, gtp_address, imsi, msisdn, pdptype, ggsn, node, fixed_ipv4, fixed_ipv6, username, password, dhcp, cc, operator, rat, imei, authentication_type, qci, sel_mode, gtp_u_address): 857 | 858 | global sequence_number 859 | 860 | gtp_flags = b'\x48' 861 | gtp_message_type = b'\x20' 862 | gtp_length = b'\x00\x00' 863 | gtp_teid = b'\x00\x00\x00\x00' 864 | 865 | gtp_sequence_number = struct.pack("!B", sequence_number >> 16) + struct.pack("!H", sequence_number & 0xffff) 866 | gtp_spare = b'\x00' 867 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare 868 | 869 | gtp_imsi = add_imsi_v2(0,imsi) 870 | gtp_imei = add_imei_v2(0,imei) 871 | gtp_msisdn = add_msisdn_v2(0,msisdn) 872 | gtp_serving_network = add_serving_network_v2(0,operator) 873 | 874 | if node == "SGSN": 875 | if rat is None: 876 | gtp_user_location_info = add_user_location_info_v2(0,operator,1) 877 | gtp_rat = add_rat_v2(0, 1) 878 | else: 879 | gtp_user_location_info = add_user_location_info_v2(0,operator,int(rat)) 880 | gtp_rat = add_rat_v2(0, int(rat)) 881 | 882 | elif node in ("EPDG", "TWAN"): 883 | if rat is None: 884 | gtp_user_location_info = b'' 885 | gtp_rat = add_rat_v2(0, 3) 886 | else: 887 | gtp_user_location_info = b'' 888 | gtp_rat = add_rat_v2(0, int(rat)) 889 | else: 890 | gtp_user_location_info = add_user_location_info_v2(0,operator,6) 891 | if rat is not None: 892 | gtp_rat = add_rat_v2(0,int(rat)) 893 | else: 894 | gtp_rat = add_rat_v2(0, 6) 895 | 896 | if pdptype == "ipv4v6": 897 | gtp_indication = add_indication_v2(0,128,0,0,0,0,0) 898 | else: 899 | gtp_indication = add_indication_v2(0,0,0,0,0,0,0) 900 | gtp_indication = b'' 901 | 902 | if node == "MME": 903 | gtp_teid_control = add_random_f_teid_v2(0,"s11_c_mme", gtp_address, 0) + add_random_f_teid_v2(1, "s5_c_pgw", ggsn, 0) 904 | elif node == "SGSN": 905 | gtp_teid_control = add_random_f_teid_v2(0,"s4_c_sgsn", gtp_address, 0) + add_random_f_teid_v2(1, "s5_c_pgw", ggsn, 0) 906 | elif node == "SGW": 907 | gtp_teid_control = add_random_f_teid_v2(0,"s5_c_sgw", gtp_address, 0) 908 | elif node == "EPDG": 909 | gtp_teid_control = add_random_f_teid_v2(0,"s2b_c_epdg", gtp_address, 0) 910 | elif node == "TWAN": 911 | gtp_teid_control = add_random_f_teid_v2(0,"s2a_c_twan", gtp_address, 0) 912 | 913 | gtp_apn = add_apn_v2(0,apn,operator) 914 | gtp_selection_mode = add_selection_mode_v2(sel_mode) 915 | 916 | if pdptype == "ipv4": 917 | gtp_pdn_type = add_pdn_type_v2(0,1) 918 | if fixed_ipv4 == None: 919 | gtp_pdn_address = add_pdn_address_v2(0,1,"0.0.0.0","::") 920 | else: 921 | gtp_pdn_address = add_pdn_address_v2(0,1,fixed_ipv4,"::") 922 | gtp_pco = add_pco_v2("ipv4", username, password, dhcp, authentication_type, node) 923 | 924 | elif pdptype == "ipv6": 925 | gtp_pdn_type = add_pdn_type_v2(0,2) 926 | if fixed_ipv6 == None: 927 | gtp_pdn_address = add_pdn_address_v2(0,2,"0.0.0.0","::") 928 | else: 929 | gtp_pdn_address = add_pdn_address_v2(0,2,"0.0.0.0",fixed_ipv6) 930 | gtp_pco = add_pco_v2("ipv6", username, password, dhcp, authentication_type, node) 931 | 932 | elif pdptype == "ipv4v6": 933 | gtp_pdn_type = add_pdn_type_v2(0,3) 934 | if fixed_ipv4 == None and fixed_ipv6 == None: 935 | gtp_pdn_address = add_pdn_address_v2(0,3,"0.0.0.0","::") 936 | elif fixed_ipv4 != None and fixed_ipv6 == None: 937 | gtp_pdn_address = add_pdn_address_v2(0,3,fixed_ipv4,"::") 938 | elif fixed_ipv4 == None and fixed_ipv6 != None: 939 | gtp_pdn_address = add_pdn_address_v2(0,3,"0.0.0.0",fixed_ipv6) 940 | else: 941 | gtp_pdn_address = add_pdn_address_v2(0,3,fixed_ipv4,fixed_ipv6) 942 | gtp_pco = add_pco_v2("ipv4v6", username, password, dhcp, authentication_type, node) 943 | 944 | gtp_apn_restriction = add_apn_restriction_v2() 945 | gtp_ambr = add_ambr_v2() 946 | 947 | # ie from grouped gtp_bearer_context 948 | gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI) 949 | if node == "SGSN": 950 | gtp_teid_data = add_random_f_teid_v2(1,"s4_u_sgsn", gtp_u_address, 0) 951 | elif node == "SGW": 952 | gtp_teid_data = add_random_f_teid_v2(2,"s5_u_sgw", gtp_u_address, 0) 953 | elif node == "EPDG": 954 | gtp_teid_data = add_random_f_teid_v2(5,"s2b_u_epdg", gtp_u_address, 0) 955 | elif node == "TWAN": 956 | gtp_teid_data = add_random_f_teid_v2(6,"s2a_u_twan", gtp_u_address, 0) 957 | else: 958 | gtp_teid_data = b'' 959 | gtp_bearer_qos = add_bearer_qos_v2(0, qci) 960 | 961 | gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_teid_data + gtp_bearer_qos) 962 | 963 | gtp_timezone = add_timezone_v2() 964 | gtp_cc = b'\x5f\x00\x02\x00' + hex2bytes(cc) 965 | 966 | gtp_ie = gtp_imsi + gtp_imei + gtp_msisdn + gtp_serving_network + gtp_user_location_info + gtp_rat + gtp_indication + gtp_teid_control + gtp_apn + gtp_selection_mode + gtp_pdn_type + gtp_pdn_address + gtp_pco + gtp_apn_restriction + gtp_ambr + gtp_bearer_context + gtp_timezone + gtp_cc 967 | 968 | create_session_request_packet = bytearray(gtp_header + gtp_ie) 969 | 970 | length = len(create_session_request_packet) - 4 971 | 972 | create_session_request_packet[3] = length % 256 973 | create_session_request_packet[2] = length // 256 974 | 975 | sequence_number +=1 976 | 977 | return create_session_request_packet 978 | 979 | 980 | def modify_bearer_request(gtp_address, node): # only for mme or sgsn mode 981 | 982 | global sequence_number, teid_local_control, teid_local_data, teid_remote_data, teid_remote_control 983 | 984 | gtp_flags = b'\x48' 985 | gtp_message_type = b'\x22' 986 | gtp_length = b'\x00\x00' 987 | gtp_teid = struct.pack("!L", teid_remote_control) 988 | 989 | gtp_sequence_number = struct.pack("!B", sequence_number >> 16) + struct.pack("!H", sequence_number & 0xffff) 990 | gtp_spare = b'\x00' 991 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare 992 | 993 | 994 | gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI) 995 | if node == "SGSN": 996 | gtp_teid_data = add_random_f_teid_v2(3,"s4_u_sgsn", gtp_address, teid_local_data) 997 | elif node == "MME": 998 | gtp_teid_data = add_random_f_teid_v2(0,"s1_u_enb", gtp_address, 0) 999 | 1000 | gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_teid_data) 1001 | 1002 | modify_bearer_request_packet = bytearray(gtp_header + gtp_bearer_context) 1003 | 1004 | length = len(modify_bearer_request_packet) - 4 1005 | 1006 | modify_bearer_request_packet[3] = length % 256 1007 | modify_bearer_request_packet[2] = length // 256 1008 | 1009 | sequence_number +=1 1010 | 1011 | return modify_bearer_request_packet 1012 | 1013 | 1014 | def delete_session_request(gtp_address, node): 1015 | 1016 | global sequence_number, teid_local_control, teid_local_data, teid_remote_data, teid_remote_control 1017 | 1018 | gtp_flags = b'\x48' 1019 | gtp_message_type = b'\x24' 1020 | gtp_length = b'\x00\x00' 1021 | gtp_teid = struct.pack("!L", teid_remote_control) 1022 | 1023 | gtp_sequence_number = struct.pack("!B", sequence_number >> 16) + struct.pack("!H", sequence_number & 0xffff) 1024 | gtp_spare = b'\x00' 1025 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare 1026 | 1027 | gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI) 1028 | 1029 | if node == "SGSN" or node == "MME": 1030 | gtp_indication = add_indication_v2(0,8,0,0,0,0,0) 1031 | else: 1032 | gtp_indication = b'' 1033 | 1034 | if node == "MME": 1035 | gtp_teid_control = add_random_f_teid_v2(0,"s11_c_mme", gtp_address, teid_local_control) 1036 | elif node == "SGSN": 1037 | gtp_teid_control = add_random_f_teid_v2(0,"s4_c_sgsn", gtp_address, teid_local_control) 1038 | elif node == "SGW": 1039 | gtp_teid_control = add_random_f_teid_v2(0,"s5_c_sgw", gtp_address, teid_local_control) 1040 | elif node == "EPDG": 1041 | gtp_teid_control = add_random_f_teid_v2(0,"s2b_c_epdg", gtp_address, teid_local_control) 1042 | elif node == "TWAN": 1043 | gtp_teid_control = add_random_f_teid_v2(0,"s2a_c_twan", gtp_address, teid_local_control) 1044 | 1045 | delete_session_request_packet = bytearray(gtp_header + gtp_bearer_id + gtp_indication + gtp_teid_control) 1046 | 1047 | length = len(delete_session_request_packet) - 4 1048 | 1049 | delete_session_request_packet[3] = length % 256 1050 | delete_session_request_packet[2] = length // 256 1051 | 1052 | sequence_number +=1 1053 | 1054 | return delete_session_request_packet 1055 | 1056 | 1057 | def create_bearer_response(sequence_number): # current version rejects dedicated bearer creation from pgw 1058 | 1059 | global teid_remote_control 1060 | 1061 | gtp_flags = b'\x48' 1062 | gtp_message_type = b'\x60' 1063 | gtp_length = b'\x00\x00' 1064 | gtp_teid = struct.pack("!L", teid_remote_control) 1065 | 1066 | gtp_sequence_number = sequence_number 1067 | gtp_spare = b'\x00' 1068 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare 1069 | 1070 | gtp_cause = b'\x02\x00\x02\x00\x72\x01' 1071 | gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI+1) 1072 | 1073 | gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_cause) 1074 | 1075 | create_bearer_response_packet = bytearray(gtp_header + gtp_cause + gtp_bearer_context) 1076 | 1077 | length = len(create_bearer_response_packet) - 4 1078 | 1079 | create_bearer_response_packet[3] = length % 256 1080 | create_bearer_response_packet[2] = length // 256 1081 | 1082 | return create_bearer_response_packet 1083 | 1084 | 1085 | def update_bearer_response(sequence_number): 1086 | 1087 | global teid_remote_control 1088 | 1089 | gtp_flags = b'\x48' 1090 | gtp_message_type = b'\x62' 1091 | gtp_length = b'\x00\x00' 1092 | gtp_teid = struct.pack("!L", teid_remote_control) 1093 | 1094 | gtp_sequence_number = sequence_number 1095 | gtp_spare = b'\x00' 1096 | gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare 1097 | 1098 | gtp_cause = b'\x02\x00\x02\x00\x10\x00' 1099 | gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI) 1100 | 1101 | gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_cause) 1102 | 1103 | update_bearer_response_packet = bytearray(gtp_header + gtp_cause + gtp_bearer_context) 1104 | 1105 | length = len(update_bearer_response_packet) - 4 1106 | 1107 | update_bearer_response_packet[3] = length % 256 1108 | update_bearer_response_packet[2] = length // 256 1109 | 1110 | return update_bearer_response_packet 1111 | 1112 | 1113 | ####### Endof GTPv2 ######## 1114 | 1115 | ########################################################################################################################################################## 1116 | 1117 | def signal_handler(signum, frame): 1118 | raise Exception("Timed out!") 1119 | 1120 | def get_default_gateway_linux(): 1121 | """Read the default gateway directly from /proc.""" 1122 | with open("/proc/net/route") as fh: 1123 | for line in fh: 1124 | fields = line.strip().split() 1125 | if fields[1] != '00000000' or not int(fields[3], 16) & 2: 1126 | continue 1127 | return socket.inet_ntoa(struct.pack(" 12: 1191 | for i in range(len(pco)-12): 1192 | if pco[i] == 129 and pco[i+1] == 6 and pco[i+6] == 131 and pco[i+7] == 6: 1193 | dns_primary = socket.inet_ntoa(bytes(pco[i+2:i+6])) 1194 | dns_secondary = socket.inet_ntoa(bytes(pco[i+8:i+12])) 1195 | dns_result.append(dns_primary) 1196 | dns_result.append(dns_secondary) 1197 | return dns_result 1198 | for i in range(len(pco)-6+1): 1199 | if pco[i] == 129 and pco[i+1] == 6: 1200 | dns_primary = socket.inet_ntoa(bytes(pco[i+2:i+6])) 1201 | dns_result.append(dns_primary) 1202 | return dns_result 1203 | 1204 | else: 1205 | return None 1206 | 1207 | def pco_dns_ipv6(pco): 1208 | dns_result = [] 1209 | # fast method to search for DNS without decoding PCO IE 1210 | if len(pco) > 12: 1211 | for i in range(len(pco)-19+1): 1212 | if pco[i] == 0 and pco[i+1] == 3 and pco[i+2] == 16: 1213 | dns = socket.inet_ntop(socket.AF_INET6, bytes(pco[i+3:i+19])) 1214 | dns_result.append(dns) 1215 | if dns_result == []: 1216 | return None 1217 | else: 1218 | return dns_result 1219 | else: 1220 | return None 1221 | 1222 | 1223 | def pco_pcscf(pco): 1224 | pcscf_result = [] 1225 | # fast method to search for PCSCF without decoding PCO IE 1226 | if len(pco) > 6: 1227 | for i in range(len(pco)-6): 1228 | if pco[i] == 0 and pco[i+1] == 12 and pco[i+2] == 4: 1229 | pcscf = socket.inet_ntoa(bytes(pco[i+3:i+7])) 1230 | pcscf_result.append(pcscf) 1231 | if pcscf_result == []: 1232 | return None 1233 | else: 1234 | return pcscf_result 1235 | else: 1236 | return None 1237 | 1238 | def pco_pcscf_ipv6(pco): 1239 | pcscf_result = [] 1240 | # fast method to search for P-CSCF IPv6 without decoding PCO IE 1241 | if len(pco) > 18: 1242 | for i in range(len(pco)-18): 1243 | if pco[i] == 0 and pco[i+1] == 1 and pco[i+2] == 16: 1244 | pcscf = socket.inet_ntop(socket.AF_INET6, bytes(pco[i+3:i+19])) 1245 | pcscf_result.append(pcscf) 1246 | if pcscf_result == []: 1247 | return None 1248 | else: 1249 | return pcscf_result 1250 | else: 1251 | return None 1252 | 1253 | 1254 | 1255 | ####################################################################### 1256 | 1257 | def encapsulate_gtp_u(args): 1258 | 1259 | global s_gtpu 1260 | 1261 | tap_fd = args[0] 1262 | gre_dst_ip = args[1] 1263 | teid = args[2] 1264 | 1265 | while True: 1266 | tap_packet = os.read(tap_fd, 1514) 1267 | s_gtpu.sendto(gtp_u_header(teid, len(tap_packet)) + tap_packet, (gre_dst_ip, GTP_U_REMOTE_PORT)) 1268 | 1269 | return 0 1270 | 1271 | 1272 | def decapsulate_gtp_u(args): 1273 | 1274 | global s_gtpu 1275 | 1276 | tap_fd = args[0] 1277 | gtp_src_ip = args[1] 1278 | teid = args[2] 1279 | 1280 | while True: 1281 | gtp_packet, gtp_address = s_gtpu.recvfrom(2000) 1282 | # check packet source 1283 | if gtp_address[0] == gtp_src_ip: 1284 | #is G-PDU? has the correct TEID? 1285 | if gtp_packet[0:2] == b'\x30\xff' and gtp_packet[4:8] == struct.pack("!L", teid): 1286 | os.write(tap_fd,gtp_packet[8:]) 1287 | elif gtp_packet[1:2] == b'\xff' and gtp_packet[4:8] == struct.pack("!L", teid): 1288 | os.write(tap_fd,gtp_packet[12:]) 1289 | # is echo request? 1290 | elif gtp_packet[1:2] == b'\x01': 1291 | gtp_echo_response = bytearray(gtp_packet) + b'\x0e\x00' 1292 | gtp_echo_response[1] = 2 1293 | gtp_echo_response[3] += 2 1294 | s_gtpu.sendto(gtp_echo_response, gtp_address) 1295 | 1296 | return 0 1297 | 1298 | def exec_in_netns(netns_name, cmd, shell=True): 1299 | if netns_name: 1300 | cmd = "ip netns exec %s %s" % (netns_name, cmd) 1301 | print("cmd: %s" % cmd) 1302 | subprocess.call(cmd, shell=shell) 1303 | 1304 | def add_dir(netns_name): 1305 | if not os.path.isdir('/etc/netns'): 1306 | os.mkdir('/etc/netns') 1307 | if not os.path.isdir('/etc/netns/' + netns_name): 1308 | os.mkdir('/etc/netns/' + netns_name) 1309 | 1310 | 1311 | ########################################################## M A I N ########################################################## 1312 | 1313 | def main(): 1314 | 1315 | global options 1316 | 1317 | global s_gtpc, s_gtpu, sequence_number, teid_local_control, teid_local_data, ie_size, dns_addresses, dns_addresses_ipv6, request_sequence_number, teid_remote_data, teid_remote_control 1318 | 1319 | parser = OptionParser() 1320 | parser.add_option("-t", "--tunnel_type", dest="tunnel_type", default="GTP", help="tunnel Type: GTP (Default), GTPv2") 1321 | parser.add_option("-d", "--tunnel_dst_ip", dest="tunnel_dst_ip", help="tunnel IP GTP endpoint") 1322 | parser.add_option("-i", "--dev_id", dest="dev_id", default=10, help="tun/tap device index") 1323 | parser.add_option("-a", "--apn_name", dest="apn_name", default=DEFAULT_APN, help="APN name") 1324 | parser.add_option("-I", "--imsi", dest="imsi", default=DEFAULT_IMSI, help="IMSI") 1325 | parser.add_option("-M", "--msisdn", dest="msisdn", default=DEFAULT_MSISDN, help="MSISDN") 1326 | parser.add_option("-p", "--pdptype", dest="pdptype", default="ipv4", help="PDP type (ipv4, ipv6 or ipv4v6)") 1327 | parser.add_option("-s", "--gtp_source_address", dest="gtp_address", help="GTP source address (for GTP-C and GTP-U)") 1328 | parser.add_option("-S", "--ip_source_address", dest="ip_source_address", help="IP source address. If not specified, the bind is done for all IPs") 1329 | parser.add_option("-g", "--gateway_ip_address", dest="gateway_ip_address", help="gateway IP address") 1330 | parser.add_option("-n", "--nodetype", dest="nodetype", default="SGSN", help="Node type (SGSN, MME, SGW, EPDG or TWAN)") 1331 | parser.add_option("-E", "--imei", dest="imei", default=DEFAULT_IMEI, help="IMEI") 1332 | parser.add_option("-f", "--fixed_ipv4", dest="fixed_ipv4", help="Static IPv4 for session") 1333 | parser.add_option("-F", "--fixed_ipv6", dest="fixed_ipv6", help="Static IPv6 for session") 1334 | parser.add_option("-U", "--username", dest="username", help="username (for gtp proxy access)") 1335 | parser.add_option("-P", "--password", dest="password", help="password (for gtp proxy access)") 1336 | parser.add_option("-G", "--ggsn", dest="ggsn", help="ggsn/pgw ip address (for gtp proxy access or when set to SGSN/MME node in GTPv2)") 1337 | parser.add_option("-H", "--hash", dest="password_to_hash", help="password hash calculation (for gtp proxy access)") 1338 | parser.add_option("-v", "--version", action="store_true", dest="version", default=False, help="version") 1339 | parser.add_option("-u", "--username_pco", dest="username_pco", help="username (for APN)") 1340 | parser.add_option("-w", "--password_pco", dest="password_pco", help="password (for APN)") 1341 | parser.add_option("-A", "--authentication_type", dest="authentication_type", default="PAP", help="authentication type: PAP (default), CHAP") 1342 | parser.add_option("-T", "--timeout", dest="timeout", default="2", help="timeout for session establishment") 1343 | parser.add_option("-D", "--dhcp", action="store_true", dest="dhcp", default=False, help="Deferred IP allocation using DHCP (ipv4)") 1344 | parser.add_option("-C", "--cc", dest="cc", default="0800", help="Charging Characteristics") 1345 | parser.add_option("-O", "--operator", dest="operator", default=DEFAULT_OPERATOR, help="Operator MCCMNC for ULI") 1346 | parser.add_option("-R", "--rat", dest="rat", help="Radio Access Type") 1347 | parser.add_option("-Q", "--quit", action="store_true", dest="quit", default=False, help="Quit immediately after activating session") 1348 | parser.add_option("-N", "--netns", dest="netns", help="Name of network namespace for tun device") 1349 | parser.add_option("-Z", "--gtp-kernel", action="store_true", dest="gtp_kernel", help="Use GTP Kernel. Needs libgtpnl", default=False) 1350 | parser.add_option("-X", "--no-default", action="store_true", dest="no_default", help="Does not install default route", default=False) 1351 | parser.add_option("-q", "--qci", dest="qci", default="8", help="QCI") 1352 | parser.add_option("--selmode", dest="sel_mode", default="0", help="Selection Mode (0, 1 oe 2)") 1353 | parser.add_option("--gtp_u_source_address", dest="gtp_u_address", help="GTP source address for GTP-U") 1354 | parser.add_option("--ip_source_address_gtpu", dest="ip_source_address_gtpu", help="IP source address for GTP-U. If not specified it will the same value as --ip_source_address") 1355 | parser.add_option("--ip_net_veth_gtpu", dest="ip_net_veth_gtpu", help="IP/Mask of veth for GTP-U. --ip_source_address_gtpu must be set and belong to the same network. Routing for this network must exist (downlink must reach host machine)") 1356 | 1357 | 1358 | (options, args) = parser.parse_args() 1359 | 1360 | if options.version == True: 1361 | print("GTP Dialer: Version 4.0 by Fabricio Ferraz (fasferraz@gmail.com) 2024") 1362 | exit(1) 1363 | if options.password_to_hash is not None: 1364 | m = hashlib.md5() 1365 | m.update((options.password_to_hash + HASH_PASS).encode()) 1366 | print('\n' + bytes2hex(m.digest()) + '\n') 1367 | exit(1) 1368 | 1369 | if options.gtp_address is None: 1370 | if sys.platform == "linux" or sys.platform == "linux2": 1371 | options.gtp_address = get_default_source_address() 1372 | 1373 | if options.gateway_ip_address is None: 1374 | if sys.platform == "linux" or sys.platform == "linux2": 1375 | options.gateway_ip_address = get_default_gateway_linux()[0] 1376 | 1377 | if options.tunnel_type == "GTP" or options.tunnel_type == "GTPv2": 1378 | if sys.platform != "linux" and sys.platform != "linux2": 1379 | print("Operating system not supported. Exiting.\n") 1380 | exit(1) 1381 | if options.tunnel_dst_ip is None: 1382 | print("A Tunnel IP endpoint is required!\n") 1383 | exit(1) 1384 | if options.apn_name is None: 1385 | print("An APN name is required!\n") 1386 | exit(1) 1387 | if options.gtp_address is None: 1388 | print("A GTP source address is required!\n") 1389 | exit(1) 1390 | if options.pdptype not in ("ipv4", "ipv6", "ipv4v6"): 1391 | print ("Unknown PDP Type!\n") 1392 | exit(1) 1393 | if options.nodetype not in ("SGSN", "MME", "SGW", "EPDG", "TWAN"): 1394 | print ("Unknown Node Type!\n") 1395 | exit(1) 1396 | if options.tunnel_type == "GTP" and (options.nodetype in ("MME", "SGW", "EPDG", "TWAN")): 1397 | print ("Node type not compatible with GTP version") 1398 | exit(1) 1399 | if options.tunnel_type == "GTP" and (options.fixed_ipv4 != None or options.fixed_ipv6 != None): 1400 | print ("Static IP functionality is not implemented for GTP") 1401 | exit(1) 1402 | if len(options.operator) < 5 or len(options.operator) > 6: 1403 | print ("MCC-MNC should be 5 or 6 hex digits long") 1404 | exit(1) 1405 | if len(options.cc) != 4: 1406 | print ("CC should be 4 hex digits long") 1407 | exit(1) 1408 | if options.netns is not None and options.gtp_kernel == True: 1409 | if options.ip_net_veth_gtpu is None or options.ip_source_address_gtpu is None or options.gtp_u_address is None: 1410 | print("option --ip_net_veth_gtpu must be set. IP/Mask of veth for GTP-U") 1411 | print("option --ip_source_address_gtpu must be set and belong to the same network as --ip_net_veth_gtpu.") 1412 | print("option --gtp_u_source_address must be set. GTP source address for GTP-U must match ip_source_address_gtpu") 1413 | print("Routing for this network must exist (downlink must reach host machine)") 1414 | exit(1) 1415 | if options.gtp_u_address is None: 1416 | options.gtp_u_address = options.gtp_address 1417 | if options.ip_source_address_gtpu is None: 1418 | options.ip_source_address_gtpu = options.ip_source_address 1419 | 1420 | 1421 | teid_remote_data = 0 1422 | teid_local_data = 0 1423 | teid_remote_control = 0 1424 | sequence_number = 0 1425 | remote_destinations = [] 1426 | remote_destinations.append(options.tunnel_dst_ip) 1427 | 1428 | print (bcolors.BOLD) 1429 | print (bcolors.YELLOW + " _____ _______ _____ _____ _ _ ") 1430 | print (bcolors.YELLOW + " / ____|__ __| __ \ | __ \(_) | | ") 1431 | print (bcolors.YELLOW + " | | __ | | | |__) | | | | |_ __ _| | ___ _ __ ") 1432 | print (bcolors.GREEN + " | | |_ | | | | ___/ | | | | |/ _` | |/ _ \ '__|") 1433 | print (bcolors.GREEN + " | |__| | | | | | | |__| | | (_| | | __/ | ") 1434 | print (bcolors.BLUE + " \_____| |_| |_| |_____/|_|\__,_|_|\___|_| by fasferraz@gmail (2012-2022)") 1435 | print (bcolors.ENDC) 1436 | 1437 | print (" 1. Adding route to GGSN IP Address pointing to the current default gateway") 1438 | # Add route for destination Node ip address pointing to the default gateway 1439 | if sys.platform == "linux" or sys.platform == "linux2": 1440 | subprocess.call("route add " + options.tunnel_dst_ip + " gw " + options.gateway_ip_address, shell=True) 1441 | 1442 | ###################################################################### 1443 | ########################## Control Plane ########################## 1444 | ###################################################################### 1445 | 1446 | print (" 2. Creating GTP-C Socket") 1447 | # GTP_C Socket 1448 | s_gtpc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 1449 | 1450 | # Bind socket to local host and port 1451 | try: 1452 | if options.ip_source_address is None: 1453 | s_gtpc.bind((GTP_LOCAL_HOST, GTP_C_LOCAL_PORT)) 1454 | else: 1455 | s_gtpc.bind((options.ip_source_address, GTP_C_LOCAL_PORT)) 1456 | 1457 | except socket.error as msg: 1458 | print (' 3. Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n') 1459 | print (" 4. Deleting route to GGSN IP created in step 1. Exiting\n") 1460 | if sys.platform == "linux" or sys.platform == "linux2": 1461 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1462 | exit(1) 1463 | 1464 | ### GTPv1 tree ### 1465 | ### GTPv1 tree ### 1466 | ### GTPv1 tree ### 1467 | if options.tunnel_type == "GTP": 1468 | 1469 | print (" 3. Sending Create PDP Context to GGSN") 1470 | # Create session 1471 | s_gtpc.sendto(cpc_request(options.apn_name, options.gtp_address, options.imsi, options.msisdn, options.pdptype, options.username, options.password, options.ggsn, options.username_pco, options.password_pco, options.dhcp, options.cc, options.operator, options.imei, options.authentication_type, options.rat, options.sel_mode, options.gtp_u_address), (options.tunnel_dst_ip, GTP_C_REMOTE_PORT)) 1472 | 1473 | # alarm triggering for timeout, in case there is no answer from GGSN 1474 | signal.signal(signal.SIGALRM, signal_handler) 1475 | signal.alarm(int(options.timeout)) 1476 | try: 1477 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 1478 | signal.alarm(0) 1479 | 1480 | except Exception as msg: 1481 | print (' 4. No answer from GGSN. Exiting. Message: ' + str(msg) + '\n') 1482 | if sys.platform == "linux" or sys.platform == "linux2": 1483 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1484 | exit(1) 1485 | 1486 | if gtp_address[0] != options.tunnel_dst_ip: 1487 | print (" 4. Answer received but not from the GGSN. Deleting route to GGSN created in step 1. Exiting\n") 1488 | if sys.platform == "linux" or sys.platform == "linux2": 1489 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1490 | 1491 | exit(1) 1492 | 1493 | if gtp_packet[1:2] == b'\x01': 1494 | gtp_echo_response = bytearray(gtp_packet) + b'\x0e\x00' 1495 | gtp_echo_response[1] = 2 1496 | gtp_echo_response[3] += 2 1497 | s_gtpc.sendto(gtp_echo_response, gtp_address) 1498 | 1499 | # alarm triggering for timeout, in case there is no answer from GGSN 1500 | signal.signal(signal.SIGALRM, signal_handler) 1501 | signal.alarm(int(options.timeout)) 1502 | try: 1503 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 1504 | signal.alarm(0) 1505 | 1506 | except Exception as msg: 1507 | print (' 4. No answer from GGSN. Exiting. Message: ' + str(msg) + '\n') 1508 | if sys.platform == "linux" or sys.platform == "linux2": 1509 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1510 | exit(1) 1511 | 1512 | 1513 | # gtpc decoding 1514 | cpc_response = decode_gtpc(bytearray(gtp_packet)) 1515 | if cpc_response == None or cpc_response == 240 or cpc_response == 239: 1516 | if cpc_response == None: 1517 | print (" 4. Answer received but decode failed. Deleting route to GGSN created in step 1. Exiting") 1518 | elif cpc_response == 240: 1519 | print (" 4. Answer received. Authentication needed. Please use -U and -P options to provide username and password. Deleting route to GGSN created in step 1. Exiting") 1520 | elif cpc_response == 239: 1521 | print (" 4. Answer received. Authentication failed: Wrong username or password. Deleting route to GGSN created in step 1. Exiting") 1522 | if sys.platform == "linux" or sys.platform == "linux2": 1523 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1524 | exit(1) 1525 | 1526 | print (" 4. Answer received and GTP decoded.") 1527 | tunnel_dst_ip_gtpu = ip2str(cpc_response[1133]) 1528 | print (' => GGSN GTP-U IP Adresss: ' + str(tunnel_dst_ip_gtpu)) 1529 | 1530 | if tunnel_dst_ip_gtpu not in remote_destinations: 1531 | remote_destinations.append(tunnel_dst_ip_gtpu) 1532 | 1533 | tunnel_dst_ip_gtpc = ip2str(cpc_response[133]) 1534 | print (' => GGSN GTP-C IP Adresss: ' + str(tunnel_dst_ip_gtpc)) 1535 | 1536 | if tunnel_dst_ip_gtpc not in remote_destinations: 1537 | remote_destinations.append(tunnel_dst_ip_gtpc) 1538 | 1539 | end_user_address = "" 1540 | end_user_address_ipv6 = "" 1541 | ipv6_identifier_aux = [] 1542 | ipv6_prefix_aux = [] 1543 | if len(cpc_response[128]) == 6: 1544 | end_user_address = ip2str(cpc_response[128][2:]) 1545 | elif len(cpc_response[128]) == 18: 1546 | end_user_address_ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(cpc_response[128][2:])) 1547 | ipv6_identifier_aux = cpc_response[128][2:] 1548 | ipv6_prefix_aux = cpc_response[128][2:] 1549 | elif len(cpc_response[128]) == 22: 1550 | end_user_address = ip2str(cpc_response[128][2:6]) 1551 | end_user_address_ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(cpc_response[128][6:])) 1552 | ipv6_identifier_aux = cpc_response[128][6:] 1553 | ipv6_prefix_aux = cpc_response[128][6:] 1554 | 1555 | if end_user_address != "": 1556 | print (' => End-User IPv4 Adresss: ' + str(end_user_address)) 1557 | if end_user_address_ipv6 != "": 1558 | for x in range(0, 8): 1559 | ipv6_prefix_aux[x+8] = 0 1560 | ipv6_identifier_aux[x] = 0 1561 | ipv6_identifier_aux[0] = 254 1562 | ipv6_identifier_aux[1] = 128 1563 | ipv6_prefix = socket.inet_ntop(socket.AF_INET6, bytes(ipv6_prefix_aux)) 1564 | ipv6_identifier = socket.inet_ntop(socket.AF_INET6, bytes(ipv6_identifier_aux)) 1565 | print (' => End-User IPv6 Address: ' + str(end_user_address_ipv6)) 1566 | print (' => End-User IPv6 Address (Prefix): ' + str(ipv6_prefix)) 1567 | print (' => End-User IPv6 Address (Identifier): ' + str(ipv6_identifier)) 1568 | 1569 | teid_remote_data = struct.unpack("!L", cpc_response[16])[0] 1570 | print (' => TEID Data Remote: ' + str(teid_remote_data)) 1571 | teid_remote_control = struct.unpack("!L", cpc_response[17])[0] 1572 | print (' => TEID Control Remote: ' + str(teid_remote_control)) 1573 | dns_addresses = pco_dns(cpc_response[132]) 1574 | print (' => DNS Addresses IPv4: ' + str(dns_addresses)) 1575 | dns_addresses_ipv6 = pco_dns_ipv6(cpc_response[132]) 1576 | print (' => DNS Addresses IPv6: ' + str(dns_addresses_ipv6)) 1577 | pcscf_addresses = pco_pcscf(cpc_response[132]) 1578 | print (' => P-CSCF Addresses IPv4: ' + str(pcscf_addresses)) 1579 | pcscf_addresses_ipv6 = pco_pcscf_ipv6(cpc_response[132]) 1580 | print (' => P-CSCF Addresses IPv6: ' + str(pcscf_addresses_ipv6)) 1581 | if end_user_address == "" and end_user_address_ipv6 == "": 1582 | print (" 5. No End-User Address Received. Exiting.\n") 1583 | exit(1) 1584 | 1585 | ### GTPv2 tree ### 1586 | ### GTPv2 tree ### 1587 | ### GTPv2 tree ### 1588 | elif options.tunnel_type == "GTPv2": 1589 | 1590 | print (" 3. Sending Create Session Request to SGW/PGW") 1591 | # Create session 1592 | s_gtpc.sendto(create_session_request(options.apn_name, options.gtp_address, options.imsi, options.msisdn, options.pdptype, options.ggsn, options.nodetype, options.fixed_ipv4, options.fixed_ipv6, options.username_pco, options.password_pco, options.dhcp, options.cc, options.operator, options.rat, options.imei, options.authentication_type, options.qci, options.sel_mode, options.gtp_u_address), (options.tunnel_dst_ip, GTP_C_REMOTE_PORT)) 1593 | 1594 | # alarm triggering for timeout, in case there is no answer from SGW or PGW 1595 | signal.signal(signal.SIGALRM, signal_handler) 1596 | signal.alarm(int(options.timeout)) # 2 seconds 1597 | try: 1598 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 1599 | signal.alarm(0) 1600 | 1601 | except Exception as msg: 1602 | print (' 4. No answer from SGW/PGW. Exiting. Message: ' + str(msg) + '\n') 1603 | if sys.platform == "linux" or sys.platform == "linux2": 1604 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1605 | exit(1) 1606 | 1607 | if gtp_address[0] != options.tunnel_dst_ip: 1608 | print (" 4. Answer received but not from the SGW/PGW. Deleting route to SGW/PGW created in step 1. Exiting\n") 1609 | if sys.platform == "linux" or sys.platform == "linux2": 1610 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1611 | exit(1) 1612 | 1613 | if gtp_packet[1:2] == b'\x01': 1614 | gtp_echo_response = bytearray(gtp_packet) 1615 | gtp_echo_response[1] = 2 1616 | s_gtpc.sendto(gtp_echo_response, gtp_address) 1617 | 1618 | # alarm triggering for timeout, in case there is no answer from GGSN 1619 | signal.signal(signal.SIGALRM, signal_handler) 1620 | signal.alarm(int(options.timeout)) 1621 | try: 1622 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 1623 | signal.alarm(0) 1624 | 1625 | except Exception as msg: 1626 | print (' 4. No answer from GGSN. Exiting. Message: ' + str(msg) + '\n') 1627 | if sys.platform == "linux" or sys.platform == "linux2": 1628 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1629 | exit(1) 1630 | 1631 | 1632 | # gtpc v2 decoding 1633 | create_session_response = decode_gtpc_v2(bytearray(gtp_packet)) 1634 | if create_session_response == None or create_session_response == -1: 1635 | if create_session_response == None: 1636 | print (" 4. Answer received but decode failed. Deleting route to SGW/PGW created in step 1. Exiting") 1637 | elif create_session_response == -1: 1638 | print (" 4. Answer received. Request not Accepted. Exiting") 1639 | 1640 | if sys.platform == "linux" or sys.platform == "linux2": 1641 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1642 | exit(1) 1643 | 1644 | print (" 4. Answer received and GTPv2 decoded.") 1645 | 1646 | bearer_context_decode = decode_ie_v2(create_session_response[(93,0)]) 1647 | if options.nodetype == "SGW": 1648 | tunnel_dst_ip_gtpu = ip2str(bearer_context_decode[(87,2)][5:9]) 1649 | print (' => PGW GTP-U IP Adresss: ' + str(tunnel_dst_ip_gtpu)) 1650 | if tunnel_dst_ip_gtpu not in remote_destinations: 1651 | remote_destinations.append(tunnel_dst_ip_gtpu) 1652 | tunnel_dst_ip_gtpc = ip2str(create_session_response[(87,1)][5:9]) 1653 | print (' => PGW GTP-C IP Adresss: ' + str(tunnel_dst_ip_gtpc)) 1654 | if tunnel_dst_ip_gtpc not in remote_destinations: 1655 | remote_destinations.append(tunnel_dst_ip_gtpc) 1656 | elif options.nodetype == "EPDG": 1657 | tunnel_dst_ip_gtpu = ip2str(bearer_context_decode[(87,4)][5:9]) 1658 | print (' => PGW GTP-U IP Adresss: ' + str(tunnel_dst_ip_gtpu)) 1659 | if tunnel_dst_ip_gtpu not in remote_destinations: 1660 | remote_destinations.append(tunnel_dst_ip_gtpu) 1661 | tunnel_dst_ip_gtpc = ip2str(create_session_response[(87,1)][5:9]) 1662 | print (' => PGW GTP-C IP Adresss: ' + str(tunnel_dst_ip_gtpc)) 1663 | if tunnel_dst_ip_gtpc not in remote_destinations: 1664 | remote_destinations.append(tunnel_dst_ip_gtpc) 1665 | elif options.nodetype == "TWAN": 1666 | tunnel_dst_ip_gtpu = ip2str(bearer_context_decode[(87,5)][5:9]) 1667 | print (' => PGW GTP-U IP Adresss: ' + str(tunnel_dst_ip_gtpu)) 1668 | if tunnel_dst_ip_gtpu not in remote_destinations: 1669 | remote_destinations.append(tunnel_dst_ip_gtpu) 1670 | tunnel_dst_ip_gtpc = ip2str(create_session_response[(87,1)][5:9]) 1671 | print (' => PGW GTP-C IP Adresss: ' + str(tunnel_dst_ip_gtpc)) 1672 | if tunnel_dst_ip_gtpc not in remote_destinations: 1673 | remote_destinations.append(tunnel_dst_ip_gtpc) 1674 | else: 1675 | if options.nodetype == "SGSN": 1676 | tunnel_dst_ip_gtpu = ip2str(bearer_context_decode[(87,1)][5:9]) 1677 | elif options.nodetype == "MME": 1678 | tunnel_dst_ip_gtpu = ip2str(bearer_context_decode[(87,0)][5:9]) 1679 | print (' => SGW GTP-U IP Adresss: ' + str(tunnel_dst_ip_gtpu)) 1680 | if tunnel_dst_ip_gtpu not in remote_destinations: 1681 | remote_destinations.append(tunnel_dst_ip_gtpu) 1682 | tunnel_dst_ip_gtpc = ip2str(create_session_response[(87,0)][5:9]) 1683 | print (' => SGW GTP-C IP Adresss: ' + str(tunnel_dst_ip_gtpc)) 1684 | if tunnel_dst_ip_gtpc not in remote_destinations: 1685 | remote_destinations.append(tunnel_dst_ip_gtpc) 1686 | 1687 | 1688 | end_user_address = "" 1689 | end_user_address_ipv6 = "" 1690 | ipv6_identifier_aux = [] 1691 | ipv6_prefix_aux = [] 1692 | if len(create_session_response[(79,0)]) == 5: 1693 | end_user_address = ip2str(create_session_response[(79,0)][1:]) 1694 | elif len(create_session_response[(79,0)]) == 18: 1695 | end_user_address_ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(create_session_response[(79,0)][2:])) 1696 | ipv6_identifier_aux = create_session_response[(79,0)][2:] 1697 | ipv6_prefix_aux = create_session_response[(79,0)][2:] 1698 | elif len(create_session_response[(79,0)]) == 22: 1699 | end_user_address = ip2str(create_session_response[(79,0)][18:]) 1700 | end_user_address_ipv6 = socket.inet_ntop(socket.AF_INET6, bytes(create_session_response[(79,0)][2:18])) 1701 | ipv6_identifier_aux = create_session_response[(79,0)][2:18] 1702 | ipv6_prefix_aux = create_session_response[(79,0)][2:18] 1703 | 1704 | if end_user_address != "": 1705 | print (' => End-User IPv4 Adresss: ' + str(end_user_address)) 1706 | if end_user_address_ipv6 != "": 1707 | for x in range(0, 8): 1708 | ipv6_prefix_aux[x+8] = 0 1709 | ipv6_identifier_aux[x] = 0 1710 | ipv6_identifier_aux[0] = 254 1711 | ipv6_identifier_aux[1] = 128 1712 | ipv6_prefix = socket.inet_ntop(socket.AF_INET6, bytes(ipv6_prefix_aux)) 1713 | ipv6_identifier = socket.inet_ntop(socket.AF_INET6, bytes(ipv6_identifier_aux)) 1714 | 1715 | print (' => End-User IPv6 Address: ' + str(end_user_address_ipv6)) 1716 | print (' => End-User IPv6 Address (Prefix): ' + str(ipv6_prefix)) 1717 | print (' => End-User IPv6 Address (Identifier): ' + str(ipv6_identifier)) 1718 | 1719 | if options.nodetype == "SGW": 1720 | teid_remote_data = struct.unpack("!L", bearer_context_decode[(87,2)][1:5])[0] 1721 | elif options.nodetype == "SGSN": 1722 | teid_remote_data = struct.unpack("!L", bearer_context_decode[(87,1)][1:5])[0] 1723 | elif options.nodetype == "MME": 1724 | teid_remote_data = struct.unpack("!L", bearer_context_decode[(87,0)][1:5])[0] 1725 | elif options.nodetype == "EPDG": 1726 | teid_remote_data = struct.unpack("!L", bearer_context_decode[(87,4)][1:5])[0] 1727 | elif options.nodetype == "TWAN": 1728 | teid_remote_data = struct.unpack("!L", bearer_context_decode[(87,5)][1:5])[0] 1729 | print (' => TEID Data Remote: ' + str(teid_remote_data)) 1730 | 1731 | if options.nodetype in ("SGW", "EPDG", "TWAN"): 1732 | teid_remote_control = struct.unpack("!L", create_session_response[(87,1)][1:5])[0] 1733 | else: 1734 | teid_remote_control = struct.unpack("!L", create_session_response[(87,0)][1:5])[0] 1735 | print (' => TEID Control Remote: ' + str(teid_remote_control)) 1736 | 1737 | dns_addresses = None 1738 | dns_addresses_ipv6 = None 1739 | if options.nodetype in ("SGSN", "MME", "SGW"): 1740 | if (78,0) in create_session_response: 1741 | dns_addresses = pco_dns(create_session_response[(78,0)]) 1742 | print (' => DNS Addresses IPv4: ' + str(dns_addresses)) 1743 | dns_addresses_ipv6 = pco_dns_ipv6(create_session_response[(78,0)]) 1744 | print (' => DNS Addresses IPv6: ' + str(dns_addresses_ipv6)) 1745 | pcscf_addresses = pco_pcscf(create_session_response[(78,0)]) 1746 | print (' => P-CSCF Addresses IPv4: ' + str(pcscf_addresses)) 1747 | pcscf_addresses_ipv6 = pco_pcscf_ipv6(create_session_response[(78,0)]) 1748 | print (' => P-CSCF Addresses IPv6: ' + str(pcscf_addresses_ipv6)) 1749 | else: 1750 | if (163,0) in create_session_response: 1751 | dns_addresses = pco_dns(create_session_response[(163,0)]) 1752 | print (' => DNS Addresses IPv4: ' + str(dns_addresses)) 1753 | dns_addresses_ipv6 = pco_dns_ipv6(create_session_response[(163,0)]) 1754 | print (' => DNS Addresses IPv6: ' + str(dns_addresses_ipv6)) 1755 | pcscf_addresses = pco_pcscf(create_session_response[(163,0)]) 1756 | print (' => P-CSCF Addresses IPv4: ' + str(pcscf_addresses)) 1757 | pcscf_addresses_ipv6 = pco_pcscf_ipv6(create_session_response[(163,0)]) 1758 | print (' => P-CSCF Addresses IPv6: ' + str(pcscf_addresses_ipv6)) 1759 | 1760 | if end_user_address == "" and end_user_address_ipv6 == "": 1761 | print (" 5. No End-User Address Received. Exiting.\n") 1762 | exit(1) 1763 | 1764 | ### MODIFY BEARER REQUEST for MME ### 1765 | if options.nodetype == "MME": 1766 | print (" 4.1. Sending Modify Bearer Request to SGW") 1767 | s_gtpc.sendto(modify_bearer_request(options.gtp_address, options.nodetype), (tunnel_dst_ip_gtpc, GTP_C_REMOTE_PORT)) 1768 | 1769 | # alarm triggering for timeout, in case there is no answer from SGW 1770 | signal.signal(signal.SIGALRM, signal_handler) 1771 | signal.alarm(int(options.timeout)) 1772 | try: 1773 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 1774 | signal.alarm(0) 1775 | 1776 | except Exception as msg: 1777 | print (' 4.2. No answer from SGW. Exiting. Message: ' + str(msg) + '\n') 1778 | if sys.platform == "linux" or sys.platform == "linux2": 1779 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1780 | exit(1) 1781 | 1782 | if gtp_address[0] != options.tunnel_dst_ip: 1783 | print (" 4.2. Answer received but not from the SGW. Deleting route to SGW created in step 1. Exiting\n") 1784 | if sys.platform == "linux" or sys.platform == "linux2": 1785 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1786 | exit(1) 1787 | 1788 | #decodes gtpc 1789 | modify_bearer_response = decode_gtpc_v2(bytearray(gtp_packet)) 1790 | if modify_bearer_response == None or modify_bearer_response == -1: 1791 | if modify_bearer_response == None: 1792 | print (" 4.2. Answer received but decode failed. Deleting route to SGW/PGW created in step 1. Exiting") 1793 | elif modify_bearer_response == -1: 1794 | print (" 4.2. Answer received. Request not Accepted. Exiting") 1795 | 1796 | if sys.platform == "linux" or sys.platform == "linux2": 1797 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1798 | 1799 | exit(1) 1800 | 1801 | ### QUIT OPTION ### 1802 | if options.quit == True: 1803 | if options.tunnel_type == "GTP": 1804 | # sends DeletePDPContext 1805 | print ("\n11. Exiting. Deleting PDP Context. Removing routes previously created.") 1806 | s_gtpc.sendto(dpc_request(teid_remote_control), (tunnel_dst_ip_gtpc, GTP_C_REMOTE_PORT)) 1807 | 1808 | elif options.tunnel_type == "GTPv2": 1809 | # sends DeleteSessionRequest 1810 | print ("\n11. Exiting. Deleting PDN Session. Removing routes previously created.") 1811 | s_gtpc.sendto(delete_session_request(options.gtp_address, options.nodetype), (tunnel_dst_ip_gtpc, GTP_C_REMOTE_PORT)) 1812 | 1813 | delete_routes(options.netns, remote_destinations, options.gtp_kernel, teid_local_data, end_user_address) 1814 | exit(1) 1815 | 1816 | ###################################################################### 1817 | ########################### User Plane ########################### 1818 | ###################################################################### 1819 | 1820 | if options.gtp_kernel == False: 1821 | # if control plane is ok, then start GTP-U Socket 1822 | print (" 5. Creating GTP-U Socket") 1823 | s_gtpu = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 1824 | 1825 | # Bind socket to local host and port 1826 | try: 1827 | if options.ip_source_address_gtpu is None: 1828 | s_gtpu.bind((GTP_LOCAL_HOST, GTP_U_LOCAL_PORT)) 1829 | else: 1830 | s_gtpu.bind((options.ip_source_address_gtpu, GTP_U_LOCAL_PORT)) 1831 | except socket.error as msg: 1832 | print (' 6. Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) 1833 | print (" 7. Deleting route to SGW/PGW/GGSN IP created in step 1. Exiting") 1834 | if sys.platform == "linux" or sys.platform == "linux2": 1835 | subprocess.call("route del " + options.tunnel_dst_ip + "/32", shell=True) 1836 | exit(1) 1837 | 1838 | # Creates tunnel interface 1839 | print (" 6. Creating Tunnel Interface") 1840 | dev = open_tun(options.dev_id) 1841 | 1842 | if dns_addresses != None or dns_addresses_ipv6 != None: 1843 | print (" 7. DNS: Backing up current /etc/resolv.conf. Creating a new one:") 1844 | if options.netns: 1845 | # create directory for namespace if it doesn't exist 1846 | add_dir(options.netns) 1847 | 1848 | with open("/etc/netns/%s/resolv.conf" % options.netns, "w") as file_obj: 1849 | if dns_addresses != None: 1850 | for i in dns_addresses: 1851 | print (' => Adding DNS IPv4 ' + str(i)) 1852 | file_obj.write("nameserver %s\n" % i) 1853 | if dns_addresses_ipv6 != None: 1854 | for i in dns_addresses_ipv6: 1855 | print (' => Adding DNS IPv6 ' + str(i)) 1856 | file_obj.write("nameserver %s\n" % i) 1857 | else: 1858 | subprocess.call("cp /etc/resolv.conf /etc/resolv.backup.conf", shell=True) 1859 | subprocess.call("echo > /etc/resolv.conf", shell=True) 1860 | if dns_addresses != None: 1861 | for i in dns_addresses: 1862 | print (' => Adding DNS IPv4 ' + str(i)) 1863 | subprocess.call("echo 'nameserver " + i +"' >> /etc/resolv.conf", shell=True) 1864 | if dns_addresses_ipv6 != None: 1865 | for i in dns_addresses_ipv6: 1866 | print (' => Adding DNS IPv6 ' + str(i)) 1867 | subprocess.call("echo 'nameserver " + i +"' >> /etc/resolv.conf", shell=True) 1868 | 1869 | print (" 8. Configuring End User Address in the Tunnel interface") 1870 | # add routes to possible different control or userplane IP addresses received in CreateSessionResponse or CreatePDPContextResponse 1871 | if len(remote_destinations) > 1: 1872 | for index, address in enumerate(remote_destinations): 1873 | if index !=0: 1874 | if sys.platform == "linux" or sys.platform == "linux2": 1875 | subprocess.call("route add " + address + "/32 gw " + options.gateway_ip_address, shell=True) 1876 | 1877 | 1878 | if end_user_address == "0.0.0.0": 1879 | 1880 | # alarm triggering for timeout for DHCP process 1881 | signal.signal(signal.SIGALRM, signal_handler) 1882 | signal.alarm(int(options.timeout)) # 2 seconds 1883 | 1884 | try: 1885 | # dhcp process over GTP-u (userplane) 1886 | mac = b'\x4e\xbb\x6d\x01\x00\x01' 1887 | # send dhcp_discovery 1888 | udp_payload = dhcp_request_packet(1,mac[0:2]+mac[4:6],mac,'') 1889 | dhcp_discovery_packet = ip_header_with_length("0.0.0.0","255.255.255.255", 17, 1, 8 + len(udp_payload)) + udp_header(68, 67, len(udp_payload)) + udp_payload 1890 | s_gtpu.sendto(gtp_u_header(teid_remote_data, len(dhcp_discovery_packet)) + dhcp_discovery_packet, (tunnel_dst_ip_gtpu, GTP_U_REMOTE_PORT)) 1891 | 1892 | flag = 0 1893 | while flag < 1: 1894 | gtp_packet, gtp_address = s_gtpu.recvfrom(2000) 1895 | dhcp_packet = gtp_packet[8+28:] 1896 | dhcp_param = dhcp_decode(dhcp_packet) 1897 | 1898 | if dhcp_param["op"] == b'\02' and dhcp_param["53"] == b'\x02': 1899 | udp_payload = dhcp_request_packet(3,mac[0:2]+mac[4:6],mac,dhcp_param["yiaddr"]) 1900 | dhcp_offer_packet = ip_header_with_length("0.0.0.0","255.255.255.255", 17, 1, 8 + len(udp_payload)) + udp_header(68, 67, len(udp_payload)) + udp_payload 1901 | s_gtpu.sendto(gtp_u_header(teid_remote_data, len(dhcp_offer_packet)) + dhcp_offer_packet, (tunnel_dst_ip_gtpu, GTP_U_REMOTE_PORT)) 1902 | 1903 | elif dhcp_param["op"] == b'\x02' and dhcp_param["53"] == b'\x05': 1904 | end_user_address = ip2str(dhcp_param["yiaddr"]) 1905 | flag = 1 1906 | signal.alarm(0) 1907 | 1908 | except Exception as msg: 1909 | print (' DHCP Process unsuccessful. Exiting. Message: ' + str(msg) + '\n') 1910 | if sys.platform == "linux" or sys.platform == "linux2": 1911 | delete_routes(options.netns, remote_destinations, options.gtp_kernel, teid_local_data, end_user_address) 1912 | exit(1) 1913 | 1914 | if options.netns: 1915 | # create netns and move the tun device into it 1916 | subprocess.call("ip netns add %s" % options.netns, shell=True) 1917 | if options.gtp_kernel == False: 1918 | subprocess.call("ip link set dev tun%s netns %s" % (str(options.dev_id), options.netns), shell=True) 1919 | # moving to netns brings device down again so we need to turn it up 1920 | exec_in_netns(options.netns, "ip link set dev tun%s up" % str(options.dev_id)) 1921 | 1922 | if options.gtp_kernel == True: 1923 | subprocess.call("modprobe gtp", shell=True) 1924 | 1925 | if end_user_address != "": 1926 | if sys.platform == "linux" or sys.platform == "linux2": 1927 | 1928 | if options.gtp_kernel == False: 1929 | exec_in_netns(options.netns, "ip addr add " + end_user_address + "/32 dev tun" + str(options.dev_id)) 1930 | else: 1931 | exec_in_netns(options.netns, "ip addr add " + end_user_address + "/32 dev lo") 1932 | if options.ip_source_address_gtpu is None and options.netns is not None: 1933 | exec_in_netns(False,"ip link add veth1 type veth peer name nsveth1") 1934 | exec_in_netns(False,"ip link set nsveth1 netns " + options.netns) 1935 | exec_in_netns(options.netns, "ifconfig nsveth1 " + options.ip_source_address_gtpu + '/' + options.ip_net_veth_gtpu.split("/")[1] + " up") 1936 | exec_in_netns(False, "ip link set veth1 up") 1937 | exec_in_netns(False, "ip addr add " + options.ip_net_veth_gtpu + " dev veth1") 1938 | 1939 | # add routes to possible different control or userplane IP addresses received in CreateSessionResponse or CreatePDPContextResponse in namespace 1940 | if options.netns is not None: 1941 | exec_in_netns(options.netns, "ip route add " + options.tunnel_dst_ip + "/32 via " + options.ip_net_veth_gtpu.split("/")[0] + " dev nsveth1") 1942 | if len(remote_destinations) > 1: 1943 | for index, address in enumerate(remote_destinations): 1944 | if index !=0: 1945 | if sys.platform == "linux" or sys.platform == "linux2": 1946 | exec_in_netns(options.netns, "ip route add " + address + "/32 via " + options.ip_net_veth_gtpu.split("/")[0] + " dev nsveth1") 1947 | 1948 | 1949 | if options.ip_source_address_gtpu is None: 1950 | exec_in_netns(options.netns, "gtp-link add gtp1 ip --sgsn > /tmp/log-gtp-link1 2>&1 &") 1951 | else: 1952 | exec_in_netns(options.netns, "gtp-link add gtp1 ip --sgsn " + options.ip_source_address_gtpu + " > /tmp/log-gtp-link1 2>&1 &") 1953 | 1954 | exec_in_netns(options.netns, "gtp-tunnel add gtp1 v1 " + str(teid_local_data) + " " + str(teid_remote_data) + " " + end_user_address + " " + tunnel_dst_ip_gtpu) 1955 | 1956 | if options.no_default == False: 1957 | if options.netns is not None: 1958 | if options.gtp_kernel == False: 1959 | print (" 9.1 Adding default route (0.0.0.0/0) pointing to the tunnel interface") 1960 | exec_in_netns(options.netns, "route add -net 0.0.0.0/0 gw " + end_user_address) 1961 | else: 1962 | print (" 9.1.Z Adding default route (0.0.0.0/0) pointing to the gtpu interface") 1963 | exec_in_netns(options.netns, "route add -net 0.0.0.0/0 dev gtp1") 1964 | else: 1965 | if options.gtp_kernel == False: 1966 | print (" 9.1 Adding default routes (0.0.0.0/1 and 128.0.0.0/1) pointing to the tunnel interface (to prevail over any current default route (0.0.0.0/0) already existing in the system)") 1967 | exec_in_netns(options.netns, "route add -net 0.0.0.0/1 gw " + end_user_address) 1968 | exec_in_netns(options.netns, "route add -net 128.0.0.0/1 gw " + end_user_address) 1969 | else: 1970 | print (" 9.1.Z Adding default routes (0.0.0.0/1 and 128.0.0.0/1) pointing to the gtpu interface (to prevail over any current default route (0.0.0.0/0) already existing in the system)") 1971 | exec_in_netns(options.netns, "route add -net 0.0.0.0/1 dev gtp1") 1972 | exec_in_netns(options.netns, "route add -net 128.0.0.0/1 dev gtp1") 1973 | 1974 | if end_user_address_ipv6 != "": 1975 | # Adds fe80 + identifier. OS processes RouterAdvertisement/RouterSolicitation 1976 | if sys.platform == "linux" or sys.platform == "linux2": 1977 | exec_in_netns(options.netns, "ip -6 addr add " + ipv6_identifier + "/64 dev tun" + str(options.dev_id)) 1978 | if options.no_default == False: 1979 | if options.netns is not None: 1980 | print (" 9.2 Adding default route (::/0) pointing to the tunnel interface") 1981 | exec_in_netns(options.netns, "route -A inet6 add ::/0 dev tun" + str(options.dev_id)) 1982 | else: 1983 | print (" 9.2 Adding default routes (::/1 and 8000::/1) pointing\ to the tunnel interface (to prevail over any current default route (::/0) already existing in the system)") 1984 | exec_in_netns(options.netns, "route -A inet6 add ::/1 dev tun" + str(options.dev_id)) 1985 | exec_in_netns(options.netns, "route -A inet6 add 8000::/1 dev tun" + str(options.dev_id)) 1986 | 1987 | if options.gtp_kernel == False: 1988 | print ("10. Starting threads: GTP-U encapsulation and GTP-U decapsulation.") 1989 | worker1 = Thread(target = encapsulate_gtp_u, args = ([dev, tunnel_dst_ip_gtpu, teid_remote_data],)) 1990 | worker2 = Thread(target = decapsulate_gtp_u, args = ([dev, tunnel_dst_ip_gtpu, teid_local_data],)) 1991 | worker1.setDaemon(True) 1992 | worker2.setDaemon(True) 1993 | worker1.start() 1994 | worker2.start() 1995 | 1996 | print ("\nPress q to quit\n") 1997 | 1998 | while True: 1999 | socket_list = [sys.stdin, s_gtpc] 2000 | # Get the list of sockets which are readable 2001 | read_sockets, write_sockets, error_sockets = select.select(socket_list , [], []) 2002 | 2003 | for sock in read_sockets: 2004 | 2005 | if sock == s_gtpc: 2006 | gtp_packet, gtp_address = s_gtpc.recvfrom(2000) 2007 | 2008 | # validates packet source 2009 | if gtp_address[0] == tunnel_dst_ip_gtpc: 2010 | 2011 | # gtp-c echo-request? 2012 | if gtp_packet[1:2] == b'\x01': 2013 | if options.tunnel_type == "GTP": 2014 | gtp_echo_response = bytearray(gtp_packet) + b'\x0e\x00' 2015 | gtp_echo_response[1] = 2 2016 | gtp_echo_response[3] += 2 2017 | else: 2018 | gtp_echo_response = bytearray(gtp_packet) 2019 | gtp_echo_response[1] = 2 2020 | s_gtpc.sendto(gtp_echo_response, gtp_address) 2021 | 2022 | elif options.tunnel_type == "GTP": 2023 | # delete pdp context? 2024 | if gtp_packet[1:2] == b'\x14' and gtp_packet[4:8] == struct.pack("!L", teid_local_control): 2025 | dpc_request_msg = decode_gtpc(bytearray(gtp_packet)) # decode to check if request_sequence_number 2026 | s_gtpc.sendto(dpc_response(teid_remote_control, request_sequence_number), gtp_address) 2027 | print ("\n11. Exiting. Deleting PDP Context (GGSN Initiated). Removing routes previously created.") 2028 | delete_routes(options.netns, remote_destinations, options.gtp_kernel, teid_local_data, end_user_address) 2029 | exit(1) 2030 | # update_pdp_context_request? 2031 | elif gtp_packet[1:2] == b'\x12' and gtp_packet[4:8] == struct.pack("!L", teid_local_control): 2032 | upc_request = decode_gtpc(bytearray(gtp_packet)) 2033 | # if upc_request has qos we need to include it in answer 2034 | if upc_request != None: 2035 | if 135 in upc_request: 2036 | s_gtpc.sendto(upc_response(teid_remote_control, request_sequence_number, upc_request[135]), gtp_address) 2037 | else: 2038 | s_gtpc.sendto(upc_response(teid_remote_control, request_sequence_number, None), gtp_address) 2039 | else: # is GTPv2 2040 | # delete bearer request? 2041 | if gtp_packet[1:2] == b'\x63' and gtp_packet[4:8] == struct.pack("!L", teid_local_control): 2042 | gtp_response = bytearray(gtp_packet) 2043 | gtp_response[4:8] = struct.pack("!L", teid_remote_control) 2044 | gtp_response[1:2] = b'\x64' 2045 | gtp_response[3] += 6 2046 | gtp_response += b'\x02\x00\x02\x00\x10\x00' 2047 | 2048 | s_gtpc.sendto(gtp_response, gtp_address) 2049 | print ("\n11. Exiting. Delete Bearer Request received (SGW/PGW Initiated). Removing routes previously created.") 2050 | delete_routes(options.netns, remote_destinations, options.gtp_kernel, teid_local_data, end_user_address) 2051 | exit(1) 2052 | # create bearer request? 2053 | elif gtp_packet[1:2] == b'\x5f' and gtp_packet[4:8] == struct.pack("!L", teid_local_control): 2054 | gtp_response = create_bearer_response(gtp_packet[8:11]) 2055 | s_gtpc.sendto(gtp_response, gtp_address) 2056 | print ("\n10.1. Create Bearer Request received. Rejecting Bearer activation.") 2057 | # update bearer request? 2058 | elif gtp_packet[1:2] == b'\x61' and gtp_packet[4:8] == struct.pack("!L", teid_local_control): 2059 | gtp_response = update_bearer_response(gtp_packet[8:11]) 2060 | s_gtpc.sendto(gtp_response, gtp_address) 2061 | print ("\n10.2. Update Bearer Request received. Sending Update Bearer Response.") 2062 | 2063 | else: 2064 | msg = sys.stdin.readline() 2065 | if msg == "q\n": 2066 | if options.tunnel_type == "GTP": 2067 | # sends DeletePDPContext 2068 | print ("\n11. Exiting. Deleting PDP Context. Removing routes previously created.") 2069 | s_gtpc.sendto(dpc_request(teid_remote_control), (tunnel_dst_ip_gtpc, GTP_C_REMOTE_PORT)) 2070 | 2071 | elif options.tunnel_type == "GTPv2": 2072 | # sends DeleteSessionRequest 2073 | print ("\n11. Exiting. Deleting PDN Session. Removing routes previously created.") 2074 | s_gtpc.sendto(delete_session_request(options.gtp_address, options.nodetype), (tunnel_dst_ip_gtpc, GTP_C_REMOTE_PORT)) 2075 | 2076 | delete_routes(options.netns, remote_destinations, options.gtp_kernel, teid_local_data, end_user_address) 2077 | exit(1) 2078 | 2079 | os.close(dev) 2080 | exit(1) 2081 | 2082 | if __name__ == "__main__": 2083 | main() 2084 | 2085 | 2086 | 2087 | --------------------------------------------------------------------------------