├── .gitignore ├── LICENSE ├── README.md ├── assets ├── OpenSDP-detailed.png └── OpenSDP-intro.png ├── cmd ├── opensdp-client │ ├── cmd │ │ ├── access.go │ │ ├── exitStatus.go │ │ ├── root.go │ │ └── services.go │ └── main.go └── opensdp-server │ ├── cmd │ ├── exitStatus.go │ ├── root.go │ └── server.go │ └── main.go ├── config ├── client │ └── config.yaml └── server │ ├── clients.yaml │ ├── config.yaml │ └── services.yaml ├── docs └── OpenSDP Setup Tutorial.md └── internal ├── client ├── access.go ├── client.go └── discover.go ├── clients └── clients.go ├── configsyaml ├── clients.go └── services.go ├── openspa └── client.go ├── server ├── discover.go └── server.go └── services └── service.go /.gitignore: -------------------------------------------------------------------------------- 1 | ### GO 2 | # Binaries for programs and plugins 3 | *.exe 4 | *.exe~ 5 | *.dll 6 | *.so 7 | *.dylib 8 | 9 | # Test binary, build with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | ### IDEA 16 | ## Source: https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 17 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 18 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 19 | 20 | # User-specific stuff 21 | .idea/**/workspace.xml 22 | .idea/**/tasks.xml 23 | .idea/**/usage.statistics.xml 24 | .idea/**/dictionaries 25 | .idea/**/shelf 26 | 27 | # Sensitive or high-churn files 28 | .idea/**/dataSources/ 29 | .idea/**/dataSources.ids 30 | .idea/**/dataSources.local.xml 31 | .idea/**/sqlDataSources.xml 32 | .idea/**/dynamic.xml 33 | .idea/**/uiDesigner.xml 34 | .idea/**/dbnavigator.xml 35 | 36 | # Gradle 37 | .idea/**/gradle.xml 38 | .idea/**/libraries 39 | 40 | # Gradle and Maven with auto-import 41 | # When using Gradle or Maven with auto-import, you should exclude module files, 42 | # since they will be recreated, and may cause churn. Uncomment if using 43 | # auto-import. 44 | # .idea/modules.xml 45 | # .idea/*.iml 46 | # .idea/modules 47 | 48 | # CMake 49 | cmake-build-*/ 50 | 51 | # Mongo Explorer plugin 52 | .idea/**/mongoSettings.xml 53 | 54 | # File-based project format 55 | *.iws 56 | 57 | # IntelliJ 58 | out/ 59 | 60 | # mpeltonen/sbt-idea plugin 61 | .idea_modules/ 62 | 63 | # JIRA plugin 64 | atlassian-ide-plugin.xml 65 | 66 | # Cursive Clojure plugin 67 | .idea/replstate.xml 68 | 69 | # Crashlytics plugin (for Android Studio and IntelliJ) 70 | com_crashlytics_export_strings.xml 71 | crashlytics.properties 72 | crashlytics-build.properties 73 | fabric.properties 74 | 75 | # Editor-based Rest Client 76 | .idea/httpRequests 77 | 78 | 79 | ### CUSTOMG 80 | .idea/ 81 | .DS_Store 82 | ignore/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenSDP 2 | A proof of concept [Software Defined Perimeter (SDP)](https://en.wikipedia.org/wiki/Software_Defined_Perimeter) implementation using OpenSPA for service hiding. 3 | 4 | ![opensdp](assets/OpenSDP-intro.png) 5 | 6 | ## How It Works 7 | Currently being a PoC, OpenSDP supports only service discovery for [OpenSPA](https://github.com/greenstatic/openspa) protected services. 8 | 9 | * Each service is protected by an OpenSPA server 10 | * Clients not knowing where OpenSPA hidden services are contact the OpenSDP server for service discovery over mutual TLS 11 | * Clients are then free to perform the OpenSPA handshake with all services that they are authorized 12 | 13 | ![opensdp-detailed](assets/OpenSDP-detailed.png) 14 | 15 | Currently it's only possible to define services and the clients ACL using a series of YAML files. 16 | This is planned to change in the coming releases. 17 | 18 | ## Client Usage 19 | Currently there are two commands: services and access. 20 | 21 | ### Services 22 | Returns a list of authorized services. 23 | 24 | ### Access 25 | This command is used to acquire access to a service. 26 | You can use it by specifying the service name, eg. `./openspa-client access example-www`. 27 | It is also possible to acquire access to all authorized services (returned using the `services` command) using the command line flag `-a`. 28 | 29 | ## Setup 30 | A tutorial how to setup OpenSDP with a working OpenSPA installation is available [here](docs/OpenSDP%20Setup%20Tutorial.md). 31 | 32 | ## TODO 33 | - [ ] Add logging to server 34 | - [ ] Add timeout if HTTP request is taking too long 35 | 36 | ## License 37 | This software is licensed under: [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html). 38 | -------------------------------------------------------------------------------- /assets/OpenSDP-detailed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greenstatic/opensdp/e8671bd9020b6390248e865a616acd201fdd04d0/assets/OpenSDP-detailed.png -------------------------------------------------------------------------------- /assets/OpenSDP-intro.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greenstatic/opensdp/e8671bd9020b6390248e865a616acd201fdd04d0/assets/OpenSDP-intro.png -------------------------------------------------------------------------------- /cmd/opensdp-client/cmd/access.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/greenstatic/opensdp/internal/client" 5 | "github.com/greenstatic/opensdp/internal/services" 6 | log "github.com/sirupsen/logrus" 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | "os" 10 | "strings" 11 | ) 12 | 13 | var ( 14 | all bool 15 | ) 16 | 17 | var accessCmd = &cobra.Command{ 18 | Use: "access", 19 | Short: "Performs access handshake for authorized service", 20 | Long: "Performs access handshake for authorized service", 21 | Args: cobra.RangeArgs(0, 1), 22 | Run: func(cmd *cobra.Command, args []string) { 23 | 24 | if len(args) == 0 && !all { 25 | log.Error("Missing service name (or use -a for all services)") 26 | os.Exit(badInput) 27 | return 28 | } 29 | 30 | openspaD := client.OpenSPADetails{ 31 | viper.GetString("openspa-path"), 32 | viper.GetString("openspa-ospa"), 33 | } 34 | 35 | c := client.Client{ 36 | viper.GetString("server"), 37 | viper.GetString("ca-cert"), 38 | viper.GetString("certificate"), 39 | viper.GetString("key"), 40 | openspaD, 41 | } 42 | 43 | // Unlock the OpenSDP service using OpenSPA 44 | openSdpUnlockUsingOpenSpa(c) 45 | // OpenSDP server should be available now 46 | 47 | srvs, err := c.Discover() 48 | if err != nil { 49 | log.Error("Failed to perform discover exchange") 50 | log.Error(err) 51 | os.Exit(unexpectedError) 52 | } 53 | 54 | if all { 55 | log.WithField("count", len(srvs)).Info("Gaining access to all authorized services") 56 | client.ConcurrentAccessServiceContinuous(c, srvs) 57 | } else { 58 | srv := findService(srvs, args[0]) 59 | client.ConcurrentAccessServiceContinuous(c, []services.Service{srv}) 60 | } 61 | }, 62 | } 63 | 64 | func init() { 65 | accessCmd.Flags().BoolVarP(&all, "all", "a", false, "Access all services you have access to") 66 | 67 | rootCmd.AddCommand(accessCmd) 68 | } 69 | 70 | // Finds the service by name from the slice of all services 71 | func findService(srvs []services.Service, name string) services.Service { 72 | var serv services.Service 73 | found := false 74 | for _, s := range srvs { 75 | if s.Name == name { 76 | serv = s 77 | found = true 78 | break 79 | } 80 | } 81 | 82 | if !found { 83 | log.WithField("service", name).Warning("Unknown service") 84 | 85 | srvsName := make([]string, 0, len(srvs)) 86 | for _, s := range srvs { 87 | srvsName = append(srvsName, s.Name) 88 | } 89 | 90 | log.WithField("services", strings.Join(srvsName, ", ")).Info("You have access to these services") 91 | os.Exit(unknownService) 92 | } 93 | 94 | return serv 95 | } 96 | -------------------------------------------------------------------------------- /cmd/opensdp-client/cmd/exitStatus.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | const ( 4 | _ = iota // exit status 0 is success, skip it 5 | unexpectedError 6 | badInput 7 | unknownService 8 | ) 9 | -------------------------------------------------------------------------------- /cmd/opensdp-client/cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | log "github.com/sirupsen/logrus" 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | "os" 10 | "path/filepath" 11 | ) 12 | 13 | const defaultConfigFile = "config.yaml" 14 | 15 | var ( 16 | Version = "0.1.2" 17 | Verbose = false 18 | VerboseSplit = false 19 | ver = false 20 | 21 | serverUrl string 22 | caPath string 23 | clientCertPath string 24 | clientKeyPath string 25 | cfgFile string 26 | 27 | openspaPath string 28 | openspaOSPA string 29 | ) 30 | 31 | var rootCmd = &cobra.Command{ 32 | Use: "opensdp-client", 33 | Short: "OpenSDP client to gain access to authorized services", 34 | Long: `OpenSDP client will authenticate with your OpenSDP server and give you access 35 | to your authorized services.`, 36 | Run: func(cmd *cobra.Command, args []string) { 37 | if ver { 38 | fmt.Printf("OpenSDP client version: %s\n", Version) 39 | return 40 | } 41 | cmd.Help() 42 | }, 43 | } 44 | 45 | func init() { 46 | cobra.OnInitialize(initConfig) 47 | rootCmd.PersistentFlags().StringVarP(&serverUrl, "server", "s", "", 48 | "OpenSDP server") 49 | rootCmd.PersistentFlags().StringVar(&caPath, "ca-cert", "", "certificate of the CA") 50 | rootCmd.PersistentFlags().StringVarP(&clientCertPath, "certificate", "c", "client.crt", 51 | "client's certificate") 52 | rootCmd.PersistentFlags().StringVarP(&clientKeyPath, "key", "k", "client.key", 53 | "client's key") 54 | 55 | rootCmd.PersistentFlags().StringVar(&openspaPath, "openspa-path", "openspa", 56 | "OpenSPA path") 57 | rootCmd.PersistentFlags().StringVar(&openspaOSPA, "openspa-ospa", "client.ospa", 58 | "OpenSPA client OSPA file") 59 | 60 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", 61 | fmt.Sprintf("config file (default: ./%s)", defaultConfigFile)) 62 | rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") 63 | rootCmd.PersistentFlags().BoolVar(&VerboseSplit, "verbose-split", false, 64 | "split output to stdout (until but not including error level) and stderr (error level)") 65 | rootCmd.Flags().BoolVar(&ver, "version", false, "version of the client") 66 | 67 | viper.BindPFlag("ca-cert", rootCmd.PersistentFlags().Lookup("ca-cert")) 68 | viper.BindPFlag("certificate", rootCmd.PersistentFlags().Lookup("certificate")) 69 | viper.BindPFlag("key", rootCmd.PersistentFlags().Lookup("key")) 70 | viper.BindPFlag("server", rootCmd.PersistentFlags().Lookup("server")) 71 | viper.BindPFlag("openspa-path", rootCmd.PersistentFlags().Lookup("openspa-path")) 72 | viper.BindPFlag("openspa-ospa", rootCmd.PersistentFlags().Lookup("openspa-ospa")) 73 | 74 | log.SetOutput(os.Stdout) 75 | cobra.OnInitialize(verboseSplit) 76 | cobra.OnInitialize(verboseLog) 77 | 78 | rootCmd.MarkFlagRequired("ca-cert") 79 | rootCmd.MarkFlagRequired("certificates") 80 | rootCmd.MarkFlagRequired("key") 81 | rootCmd.MarkFlagRequired("server") 82 | } 83 | 84 | // Read config values 85 | func initConfig() { 86 | if cfgFile != "" { 87 | // Use config file path provided by the flag 88 | viper.SetConfigFile(cfgFile) 89 | } else { 90 | // User default config file located inside the same dir as the executable 91 | exePath, err := os.Executable() 92 | if err != nil { 93 | panic(err) 94 | } 95 | 96 | viper.AddConfigPath(filepath.Dir(exePath)) 97 | viper.SetConfigFile(defaultConfigFile) 98 | } 99 | 100 | if err := viper.ReadInConfig(); err != nil { 101 | log.Error("failed to read config") 102 | log.Error(err) 103 | os.Exit(unexpectedError) 104 | } 105 | } 106 | 107 | // Used to route error level logs to stderr and the rest to stdout. 108 | // Credits: https://github.com/sirupsen/logrus/issues/403#issuecomment-346437512 109 | // This disables the feature of color output in case it's ran from a TTY. 110 | type OutputSplitter struct{} 111 | 112 | func (splitter *OutputSplitter) Write(p []byte) (n int, err error) { 113 | if bytes.Contains(p, []byte("level=error")) { 114 | return os.Stderr.Write(p) 115 | } 116 | return os.Stdout.Write(p) 117 | } 118 | 119 | // Enables verbose split - until error level to stdout, while error goes to stderr. 120 | // This is to be used on cobra.OnInitialize() to enable globally for all commands 121 | // if the verbose-split flag is present. 122 | func verboseSplit() { 123 | if VerboseSplit { 124 | log.SetOutput(&OutputSplitter{}) 125 | } 126 | } 127 | 128 | // Enables verbose logging (debug level logs). This is to be used on cobra.OnInitialize() 129 | // to enable globally for all commands if the verbose flag is present. 130 | func verboseLog() { 131 | if Verbose { 132 | log.SetLevel(log.DebugLevel) 133 | } 134 | } 135 | 136 | func Execute() { 137 | if err := rootCmd.Execute(); err != nil { 138 | fmt.Println(err) 139 | os.Exit(unexpectedError) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /cmd/opensdp-client/cmd/services.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/greenstatic/opensdp/internal/client" 6 | "github.com/greenstatic/opensdp/internal/services" 7 | log "github.com/sirupsen/logrus" 8 | "github.com/spf13/cobra" 9 | "github.com/spf13/viper" 10 | "net" 11 | "os" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | var servicesCmd = &cobra.Command{ 17 | Use: "services", 18 | Short: "Returns the client's authorized services", 19 | Long: "Returns the client's authorized services", 20 | 21 | Run: func(cmd *cobra.Command, args []string) { 22 | 23 | openspaD := client.OpenSPADetails{ 24 | viper.GetString("openspa-path"), 25 | viper.GetString("openspa-ospa"), 26 | } 27 | 28 | c := client.Client{ 29 | viper.GetString("server"), 30 | viper.GetString("ca-cert"), 31 | viper.GetString("certificate"), 32 | viper.GetString("key"), 33 | openspaD, 34 | } 35 | 36 | // Unlock the OpenSDP service using OpenSPA 37 | openSdpUnlockUsingOpenSpa(c) 38 | // OpenSDP server should be available now 39 | 40 | // Perform the services lookup 41 | srvs, err := c.Discover() 42 | if err != nil { 43 | log.Error("Failed to perform discover exchange") 44 | log.Error(err) 45 | os.Exit(unexpectedError) 46 | } 47 | 48 | if len(srvs) == 0 { 49 | fmt.Println("You do not have access to any services") 50 | return 51 | } 52 | 53 | fmt.Println("You have access to the following services:") 54 | fmt.Printf("|%-26s|%-26s|%-18s|%-12s|%-20s|\n", "Name", "IP", "Port(s)", "Access Type", "Tag(s)") 55 | 56 | const dashLen = 108 57 | for i := 0; i < dashLen; i++ { 58 | fmt.Printf("-") 59 | } 60 | fmt.Printf("\n") 61 | 62 | for _, s := range srvs { 63 | ports := strings.Join(s.ProtoPortToString(), ", ") 64 | accessTypes := strings.Join(s.AccessTypeToString(), ", ") 65 | tags := strings.Join(s.Tags, ", ") 66 | fmt.Printf("|%-26s|%-26s|%-18s|%-12s|%-20s|\n", s.Name, s.IP.String(), ports, accessTypes, tags) 67 | } 68 | 69 | }, 70 | } 71 | 72 | func init() { 73 | rootCmd.AddCommand(servicesCmd) 74 | } 75 | 76 | func openSdpUnlockUsingOpenSpa(c client.Client) { 77 | // Parse the OpenSDP server IP and port 78 | opensdpIp, opensdpPortStr, err := net.SplitHostPort(c.Server) 79 | if err != nil { 80 | log.Error("Failed to parse the server field into host and port") 81 | log.Error(err) 82 | os.Exit(badInput) 83 | } 84 | 85 | opensdpPortInt, err := strconv.Atoi(opensdpPortStr) 86 | if err != nil { 87 | log.Error("Failed to parse the server port field into an integer") 88 | log.Error(err) 89 | os.Exit(badInput) 90 | } 91 | 92 | // Create pseudo OpenSDP service 93 | opensdpService := services.Service{ 94 | IP: net.ParseIP(opensdpIp), 95 | ProtoPort: []services.ProtoPort{{Protocol: services.ProtocolTCP, Port: uint16(opensdpPortInt)}}, 96 | } 97 | 98 | // Using OpenSPA request access to the OpenSDP server 99 | err = client.AccessOpenSPAService(opensdpService, false, c.OpenSPA.Path, c.OpenSPA.OSPA) 100 | if err != nil { 101 | log.Error("Failed to unlock the OpenSDP service port using OpenSPA") 102 | log.Error(err) 103 | os.Exit(unexpectedError) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /cmd/opensdp-client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/greenstatic/opensdp/cmd/opensdp-client/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /cmd/opensdp-server/cmd/exitStatus.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | const ( 4 | _ = iota // exit status 0 is success, skip it 5 | unexpectedError 6 | badInput 7 | ) 8 | -------------------------------------------------------------------------------- /cmd/opensdp-server/cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | log "github.com/sirupsen/logrus" 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | "os" 10 | "path/filepath" 11 | ) 12 | 13 | var ( 14 | Version = "0.1.0" 15 | Verbose = false 16 | VerboseSplit = false 17 | ver = false 18 | cfgFile string 19 | servicesPath string 20 | clientsPath string 21 | 22 | caPath string 23 | serverCertPath string 24 | serverKeyPath string 25 | bind string 26 | port uint16 27 | ) 28 | 29 | var rootCmd = &cobra.Command{ 30 | Use: "opensdp-server", 31 | Short: "OpenSDP server allows clients to access authorized services", 32 | Long: `OpenSDP server tells clients the necessary information to authenticate with 33 | hidden services they are authorized to use.`, 34 | Run: func(cmd *cobra.Command, args []string) { 35 | if ver { 36 | fmt.Printf("OpenSDP server version: %s\n", Version) 37 | return 38 | } 39 | 40 | ifEmptyReturnError(viper.GetString("ca-cert"), "missing ca certificate") 41 | ifEmptyReturnError(viper.GetString("certificate"), "missing server certificate") 42 | ifEmptyReturnError(viper.GetString("key"), "missing server key") 43 | 44 | startServer() 45 | }, 46 | } 47 | 48 | func ifEmptyReturnError(variable, err string) { 49 | if variable == "" { 50 | log.Fatalf(err) 51 | os.Exit(badInput) 52 | } 53 | } 54 | 55 | func init() { 56 | cobra.OnInitialize(initConfig) 57 | cobra.OnInitialize(initFlags) 58 | rootCmd.Flags().StringVar(&caPath, "ca-cert", "", "certificate of the CA") 59 | rootCmd.Flags().StringVarP(&serverCertPath, "certificate", "c", "", 60 | "certificate of the server") 61 | rootCmd.Flags().StringVarP(&serverKeyPath, "key", "k", "", 62 | "private key of the server") 63 | rootCmd.Flags().StringVarP(&bind, "bind", "b", "0.0.0.0", 64 | "bind server to IP") 65 | rootCmd.Flags().Uint16VarP(&port, "port", "p", 8443, "port to listen to") 66 | 67 | rootCmd.Flags().StringVar(&cfgFile, "config", "", "config file (default: ./config.yaml)") 68 | rootCmd.Flags().StringVar(&servicesPath, "services", "", "services file (default: ./services.yaml)") 69 | rootCmd.Flags().StringVar(&clientsPath, "clients", "", "clients file (default: ./clients.yaml)") 70 | 71 | rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, 72 | "verbose output") 73 | rootCmd.PersistentFlags().BoolVar(&VerboseSplit, "verbose-split", false, 74 | "split output to stdout (until but not including error level) and stderr (error level)") 75 | rootCmd.Flags().BoolVar(&ver, "version", false, "version of the server") 76 | 77 | viper.BindPFlag("ca-cert", rootCmd.Flags().Lookup("ca-cert")) 78 | viper.BindPFlag("certificate", rootCmd.Flags().Lookup("certificate")) 79 | viper.BindPFlag("key", rootCmd.Flags().Lookup("key")) 80 | viper.BindPFlag("bind", rootCmd.Flags().Lookup("bind")) 81 | viper.BindPFlag("port", rootCmd.Flags().Lookup("port")) 82 | viper.BindPFlag("clients", rootCmd.Flags().Lookup("clients")) 83 | viper.BindPFlag("services", rootCmd.Flags().Lookup("services")) 84 | 85 | log.SetOutput(os.Stdout) 86 | cobra.OnInitialize(verboseSplit) 87 | cobra.OnInitialize(verboseLog) 88 | } 89 | 90 | // Read config values 91 | func initConfig() { 92 | if cfgFile != "" { 93 | // Use config file path provided by the flag 94 | viper.SetConfigFile(cfgFile) 95 | } else { 96 | // User default 97 | dir, err := os.Executable() 98 | if err != nil { 99 | panic(err) 100 | } 101 | 102 | viper.AddConfigPath(dir) 103 | viper.SetConfigName("config.yaml") 104 | } 105 | 106 | if err := viper.ReadInConfig(); err != nil { 107 | log.Error("failed to read config") 108 | log.Error(err) 109 | os.Exit(unexpectedError) 110 | } 111 | } 112 | 113 | func initFlags() { 114 | dir, err := os.Executable() 115 | if err != nil { 116 | panic(err) 117 | } 118 | 119 | defaultServices := filepath.Join(dir, "services.yaml") 120 | if viper.GetString("services") == "" { 121 | viper.Set("services", defaultServices) 122 | } 123 | 124 | defaultClients := filepath.Join(dir, "clients.yaml") 125 | if viper.GetString("clients") == "" { 126 | viper.Set("clients", defaultClients) 127 | } 128 | } 129 | 130 | // Used to route error level logs to stderr and the rest to stdout. 131 | // Credits: https://github.com/sirupsen/logrus/issues/403#issuecomment-346437512 132 | // This disables the feature of color output in case it's ran from a TTY. 133 | type OutputSplitter struct{} 134 | 135 | func (splitter *OutputSplitter) Write(p []byte) (n int, err error) { 136 | if bytes.Contains(p, []byte("level=error")) { 137 | return os.Stderr.Write(p) 138 | } 139 | return os.Stdout.Write(p) 140 | } 141 | 142 | // Enables verbose split - until error level to stdout, while error goes to stderr. 143 | // This is to be used on cobra.OnInitialize() to enable globally for all commands 144 | // if the verbose-split flag is present. 145 | func verboseSplit() { 146 | if VerboseSplit { 147 | log.SetOutput(&OutputSplitter{}) 148 | } 149 | } 150 | 151 | // Enables verbose logging (debug level logs). This is to be used on cobra.OnInitialize() 152 | // to enable globally for all commands if the verbose flag is present. 153 | func verboseLog() { 154 | if Verbose { 155 | log.SetLevel(log.DebugLevel) 156 | } 157 | } 158 | 159 | func Execute() { 160 | if err := rootCmd.Execute(); err != nil { 161 | fmt.Println(err) 162 | os.Exit(unexpectedError) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /cmd/opensdp-server/cmd/server.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/greenstatic/opensdp/internal/configsyaml" 5 | "github.com/greenstatic/opensdp/internal/server" 6 | log "github.com/sirupsen/logrus" 7 | "github.com/spf13/viper" 8 | "os" 9 | "strconv" 10 | ) 11 | 12 | func startServer() { 13 | portStr := strconv.Itoa(int(viper.GetInt("port"))) 14 | 15 | servicesPath := viper.GetString("services") 16 | srvs, err := configsyaml.ServicesRead(servicesPath) 17 | if err != nil { 18 | log.WithField("services", servicesPath).Error("Failed to read services") 19 | log.Error(err) 20 | os.Exit(unexpectedError) 21 | } 22 | 23 | clientsPath := viper.GetString("clients") 24 | clnts, err := configsyaml.ClientsRead(clientsPath, srvs) 25 | if err != nil { 26 | log.WithField("clients", clientsPath).Error("Failed to read clients") 27 | log.Error(err) 28 | os.Exit(unexpectedError) 29 | } 30 | 31 | s := server.Server{ 32 | viper.GetString("ca-cert"), 33 | viper.GetString("certificate"), 34 | viper.GetString("key"), 35 | viper.GetString("bind"), 36 | portStr, 37 | srvs, 38 | clnts, 39 | } 40 | 41 | s.Start() 42 | } 43 | -------------------------------------------------------------------------------- /cmd/opensdp-server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/greenstatic/opensdp/cmd/opensdp-server/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /config/client/config.yaml: -------------------------------------------------------------------------------- 1 | # OpenSDP server (ip+port) 2 | server: 192.168.1.1:33311 3 | ca-cert: "./ca.crt" 4 | certificate: "./client.crt" 5 | key: "./client.key" 6 | openspa-path: "path/to/openspa-client" 7 | openspa-ospa: "path/to/client.ospa" -------------------------------------------------------------------------------- /config/server/clients.yaml: -------------------------------------------------------------------------------- 1 | version: 0.1.0 2 | kind: clients 3 | clients: 4 | - deviceId: 9f84fbb8-10e8-4b8a-abd2-bb91cbf484df 5 | label: alice 6 | services: 7 | # All these services need to exist in the services.yaml file 8 | - name: example-www 9 | - name: example-ssh 10 | - name: example-icmp 11 | -------------------------------------------------------------------------------- /config/server/config.yaml: -------------------------------------------------------------------------------- 1 | bind: 0.0.0.0 2 | port: 33311 3 | ca-cert: "./ca.crt" 4 | certificate: "./server.crt" 5 | key: "./server.key" 6 | clients: "./clients.yaml" 7 | services: "./services.yaml" -------------------------------------------------------------------------------- /config/server/services.yaml: -------------------------------------------------------------------------------- 1 | version: 0.1.0 2 | kind: services 3 | services: 4 | - name: example-www 5 | # Must be IP and not domain! 6 | ip: 192.168.1.1 7 | # udp is supported as well 8 | ports: 9 | - [tcp, 80] 10 | - [tcp, 443] 11 | tags: 12 | - www 13 | - internal 14 | accessType: 15 | # Currently we only support OpenSPA 16 | - OpenSPA 17 | 18 | - name: example-ssh 19 | ip: 192.168.1.1 20 | ports: 21 | - [tcp, 22] 22 | tags: 23 | - admin 24 | - internal 25 | accessType: 26 | - OpenSPA 27 | 28 | - name: example-icmp 29 | ip: 192.168.1.1 30 | ports: 31 | - [icmp] 32 | tags: 33 | - admin 34 | - internal 35 | accessType: 36 | - OpenSPA -------------------------------------------------------------------------------- /docs/OpenSDP Setup Tutorial.md: -------------------------------------------------------------------------------- 1 | # OpenSDP Setup Tutorial 2 | Being a PoC, we currently do not provide binary releases. 3 | This means you will need to compile the software yourself. 4 | But don't worry it's easy, it's [Go](https://golang.org/)! 5 | 6 | ## Requirements 7 | * OpenSPA server setup (with a test client) 8 | * Debian/Ubuntu based system 9 | 10 | ## RSA Keys 11 | Clients authenticate with the server via mutual TLS. 12 | This means that the servers and clients will need a signed certificate by a commonly trusted CA. 13 | 14 | ### Creating Our Own (Self Signed) CA 15 | ```bash 16 | mkdir -p ~/opensdp/keys 17 | cd ~/opensdp/keys 18 | 19 | openssl genrsa -out ./ca.key 2048 20 | 21 | # Fill out the certificate info as you like 22 | openssl req -new -x509 -key ./ca.key -out ./ca.crt 23 | ``` 24 | 25 | ### Creating the Server and Client(s) Keys 26 | Let's create our server keypair 27 | ```bash 28 | openssl genrsa -out server.key 2048 29 | 30 | # Fill out the certificate info as you like EXCEPT the common name (CN)! 31 | # The CN should be "OpenSDP-server" 32 | openssl req -new -key server.key -out server.csr 33 | 34 | # Sign the CSR with our CA to create a 365 day valid cert 35 | openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -out server.crt -days 365 -CAcreateserial 36 | 37 | # We don't need the CSR anymore 38 | rm server.csr 39 | ``` 40 | 41 | Next, let's create a client's keypair (this step is identical for all clients). 42 | For this step you need to have generated an OpenSPA client OSPA file for EACH client you wish to create a keypair here. 43 | ```bash 44 | openssl genrsa -out client.key 2048 45 | 46 | # Fill out the certificate info as you like EXCEPT the common name (CN)! 47 | # The CN should be the client's device ID (UUID), eg; 9f84fbb8-10e8-4b8a-abd2-bb91cbf484df. 48 | openssl req -new -key client.key -out client.csr 49 | 50 | openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -out client.crt -days 365 -CAcreateserial 51 | rm client.csr 52 | ``` 53 | 54 | ### Build the Software 55 | Let's build the server. 56 | First get the source code. 57 | ````bash 58 | go get github.com/greenstatic/opensdp 59 | ```` 60 | Don't worry if you get a *package github.com/greenstatic/opensdp: no Go files in /home/ubuntu/go/src/github.com/greenstatic/opensdp* error message. 61 | 62 | Now let's build it. 63 | ```bash 64 | cd ~/go/src/github.com/greenstatic/opensdp/cmd/opensdp-server 65 | go get -u ./... # this may take some time 66 | 67 | go build -o ~/opensdp/opensdp-server 68 | ``` 69 | 70 | Great, we have our executable now. 71 | Let's build the client now. 72 | 73 | ```bash 74 | cd ~/go/src/github.com/greenstatic/opensdp/cmd/opensdp-client 75 | go get -u ./... # this may take some time 76 | 77 | go build -o ~/opensdp/opensdp-client 78 | ``` 79 | 80 | Next copy the example config files. 81 | ```bash 82 | cd ~/go/src/github.com/greenstatic/opensdp/config 83 | mkdir ~/opensdp/clients 84 | 85 | cp client/config.yaml ~/opensdp/clients/config.yaml 86 | cp server/*.yaml ~/opensdp/ 87 | ``` 88 | 89 | ### Configure the Server & Client 90 | First the server. 91 | ```bash 92 | cd ~/opensdp 93 | # Update the ca-cert, certificate and key fields to reflect the 94 | # ~/openspa/keys dir (we recommend using absolute paths to avoid errors) 95 | nano config.yaml 96 | 97 | # Configure this to your liking 98 | nano services.yaml 99 | 100 | # Configure this to your liking, 101 | # Please only use services that you defined earlier otherwise 102 | # the server will reject the file. 103 | nano clients.yaml 104 | ``` 105 | 106 | Next the client. 107 | ```bash 108 | # Move the previously generated keys to the clients dir 109 | mv keys/client.* clients/ 110 | 111 | # For now just update the server field (the default port is 33311) 112 | nano clients/config.yaml 113 | ``` 114 | 115 | You have successfully created the necessary client files. 116 | Copy the following to your client: 117 | * `~/opensdp/clients/client.crt` 118 | * `~/opensdp/clients/client.key` 119 | * `~/opensdp/clients/config.yaml` 120 | * `~/opensdp/keys/ca.crt` 121 | 122 | And of course the `opensdp-client`. 123 | 124 | ### Starting the Server 125 | Since it's only a PoC we'll run the OpenSDP-server using screen. 126 | ```bash 127 | cd ~/opensdp 128 | screen -d -m ~/opensdp/opensdp-server 129 | ``` 130 | 131 | ### Starting the Clients 132 | If you had a working OpenSPA installation before and the required client OSPA file, edit your client's `config.yaml` file. 133 | The path of the OpenSPA-client should be specified (absolute path) and the path of the OSPA file. 134 | Make sure your keypairs and ca cert are specified as well. 135 | Once you have everything setup, run: 136 | ````bash 137 | opensdp services --config ./config.yaml --verbose 138 | ```` 139 | This should print out a list of available services. 140 | If there is absolutely no response from the OpenSDP server, then you probably have an OpenSPA related configuration issue. 141 | In case OpenSPA is not the issue, check all the OpenSDP yaml files. -------------------------------------------------------------------------------- /internal/client/access.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "errors" 5 | "github.com/greenstatic/opensdp/internal/openspa" 6 | "github.com/greenstatic/opensdp/internal/services" 7 | log "github.com/sirupsen/logrus" 8 | "time" 9 | ) 10 | 11 | func (c *Client) Access(serv services.Service) error { 12 | 13 | for _, at := range serv.AccessType { 14 | switch at { 15 | case services.AccessTypeOpenSPA: 16 | return AccessOpenSPAService(serv, true, c.OpenSPA.Path, c.OpenSPA.OSPA) 17 | } 18 | } 19 | 20 | return errors.New("unsupported access type") 21 | } 22 | 23 | func AccessOpenSPAService(serv services.Service, continuous bool, openspaPath, ospa string) error { 24 | 25 | var defaultOpenSPAPort uint16 = 22211 26 | client := openspa.Client{ 27 | openspaPath, 28 | ospa, 29 | serv.IP, 30 | defaultOpenSPAPort, 31 | } 32 | 33 | for _, port := range serv.ProtoPort { 34 | req := openspa.Request{ 35 | port.Protocol.String(), 36 | port.Port, 37 | port.Port, 38 | } 39 | 40 | err := client.Send(req, continuous) 41 | if err != nil { 42 | return err 43 | } 44 | } 45 | 46 | return nil 47 | } 48 | 49 | func ConcurrentAccessServiceContinuous(c Client, srvs []services.Service) { 50 | 51 | failed := make(chan services.Service, 1) 52 | 53 | for _, srv := range srvs { 54 | serviceToAccess := srv 55 | go func() { 56 | err := c.Access(serviceToAccess) 57 | if err != nil { 58 | log.Error(err) 59 | failed <- serviceToAccess 60 | return 61 | } 62 | }() 63 | 64 | time.Sleep(200) // small delay 65 | } 66 | 67 | for { 68 | select { 69 | case srv := <-failed: 70 | log.WithField("serviceName", srv.Name).Error("Failed to access service") 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /internal/client/client.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | log "github.com/sirupsen/logrus" 7 | "io/ioutil" 8 | "net/http" 9 | netUrl "net/url" 10 | ) 11 | 12 | type Client struct { 13 | Server string 14 | CAPath string 15 | ClientCertPath string 16 | ClientKeyPath string 17 | OpenSPA OpenSPADetails 18 | } 19 | 20 | type OpenSPADetails struct { 21 | Path string 22 | OSPA string 23 | } 24 | 25 | // Perform a GET request on the urlpath of the client server. Return the 26 | // response as a byte slice. 27 | func (c *Client) Request(urlpath string) ([]byte, error) { 28 | 29 | // Build url 30 | urlRawStr := "https://" + c.Server 31 | urlParsed, err := netUrl.Parse(urlRawStr) 32 | if err != nil { 33 | log.WithField("url", urlRawStr).Error("Failed to build server url") 34 | return nil, err 35 | } 36 | 37 | url := urlParsed.String() 38 | if url[len(url)-1:] != "/" { 39 | url += "/" 40 | } 41 | url += urlpath 42 | 43 | log.WithFields(log.Fields{ 44 | "url": url, 45 | "ca": c.CAPath, 46 | "clientCert": c.ClientCertPath, 47 | "clientKey": c.ClientKeyPath}).Debug("Issuing services request") 48 | 49 | // Adapted from: https://github.com/levigross/go-mutual-tls 50 | 51 | cert, err := tls.LoadX509KeyPair(c.ClientCertPath, c.ClientKeyPath) 52 | if err != nil { 53 | log.Error("Unable to load client keypair") 54 | return nil, err 55 | } 56 | 57 | clientCACert, err := ioutil.ReadFile(c.CAPath) 58 | if err != nil { 59 | log.Error("Unable to open ca certificate") 60 | return nil, err 61 | } 62 | 63 | // Trust only the CA certificate 64 | clientCertPool := x509.NewCertPool() 65 | clientCertPool.AppendCertsFromPEM(clientCACert) 66 | 67 | tlsConfig := &tls.Config{ 68 | Certificates: []tls.Certificate{cert}, 69 | RootCAs: clientCertPool, 70 | ServerName: "OpenSDP-server", 71 | } 72 | 73 | tlsConfig.BuildNameToCertificate() 74 | 75 | client := http.Client{ 76 | Transport: &http.Transport{TLSClientConfig: tlsConfig}, 77 | } 78 | 79 | resp, err := client.Get(url) 80 | if err != nil { 81 | log.Error("Failed to connect to the server") 82 | return nil, err 83 | } 84 | 85 | defer resp.Body.Close() 86 | body, err := ioutil.ReadAll(resp.Body) 87 | if err != nil { 88 | log.Error("Failed to read response from server") 89 | return nil, err 90 | } 91 | 92 | log.WithFields(log.Fields{ 93 | "url": url, 94 | "responseLength": len(body), 95 | }).Debug("Successfully connected to the server") 96 | 97 | return body, nil 98 | } 99 | -------------------------------------------------------------------------------- /internal/client/discover.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/greenstatic/opensdp/internal/server" 6 | "github.com/greenstatic/opensdp/internal/services" 7 | ) 8 | 9 | // Performs the discover request and returns a slice of services the 10 | // client is authorized to access. 11 | func (c *Client) Discover() ([]services.Service, error) { 12 | // Send request 13 | data, err := c.Request("discover") 14 | if err != nil { 15 | return nil, err 16 | } 17 | 18 | // Parse response 19 | dr := server.DiscoverResponse{} 20 | err = json.Unmarshal(data, &dr) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | // Convert to a services.Service slice 26 | srvs := make([]services.Service, 0, len(dr.Services)) 27 | for _, drs := range dr.Services { 28 | srv, err := drs.ToService() 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | srvs = append(srvs, srv) 34 | } 35 | 36 | return srvs, nil 37 | } 38 | -------------------------------------------------------------------------------- /internal/clients/clients.go: -------------------------------------------------------------------------------- 1 | package clients 2 | 3 | import "github.com/greenstatic/opensdp/internal/services" 4 | 5 | type ServicePolicy struct { 6 | Service services.Service 7 | } 8 | 9 | type Client struct { 10 | DeviceId string 11 | Label string 12 | Services []ServicePolicy 13 | } 14 | -------------------------------------------------------------------------------- /internal/configsyaml/clients.go: -------------------------------------------------------------------------------- 1 | package configsyaml 2 | 3 | import ( 4 | "errors" 5 | "github.com/greenstatic/opensdp/internal/clients" 6 | "github.com/greenstatic/opensdp/internal/services" 7 | "github.com/satori/go.uuid" 8 | "gopkg.in/yaml.v2" 9 | "io/ioutil" 10 | ) 11 | 12 | type clientFileServicePolicy struct { 13 | Name string 14 | } 15 | 16 | type clientFile struct { 17 | DeviceId string `yaml:"deviceId"` 18 | Label string 19 | Services []clientFileServicePolicy 20 | } 21 | 22 | type clientsFile struct { 23 | Version string 24 | Kind string 25 | Clients []clientFile 26 | } 27 | 28 | func ClientsRead(path string, serv []services.Service) (map[string]clients.Client, error) { 29 | m := make(map[string]clients.Client) 30 | 31 | // Read file 32 | data, err := ioutil.ReadFile(path) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | // Parse file 38 | cf := clientsFile{} 39 | err = yaml.Unmarshal(data, &cf) 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | // Check if correct kind 45 | if cf.Kind != "clients" { 46 | return nil, errors.New("file not kind clients") 47 | } 48 | 49 | // Parse clients 50 | for _, c := range cf.Clients { 51 | clnt, err := parseClient(c, serv) 52 | if err != nil { 53 | return nil, err 54 | } 55 | m[clnt.DeviceId] = clnt 56 | } 57 | 58 | return m, nil 59 | } 60 | 61 | // Parses a clientFile struct into a clients.Client with resolved services 62 | func parseClient(c clientFile, serv []services.Service) (clients.Client, error) { 63 | clnt := clients.Client{} 64 | 65 | // Parse deviceId 66 | if c.DeviceId == "" { 67 | return clients.Client{}, errors.New("clients missing deviceId") 68 | } 69 | 70 | _, err := uuid.FromString(c.DeviceId) 71 | if err != nil { 72 | return clients.Client{}, err 73 | } 74 | clnt.DeviceId = c.DeviceId 75 | 76 | // Parse label 77 | clnt.Label = clnt.Label 78 | 79 | // Parse client's service policy 80 | for _, csp := range c.Services { 81 | sp, err := resolveClientsFileServicePolicy(csp, serv) 82 | if err != nil { 83 | return clients.Client{}, err 84 | } 85 | clnt.Services = append(clnt.Services, sp) 86 | } 87 | 88 | return clnt, nil 89 | } 90 | 91 | // Resolves a clientFileServicePolicy into a clients.ServicePolicy struct 92 | func resolveClientsFileServicePolicy(csp clientFileServicePolicy, serv []services.Service) ( 93 | clients.ServicePolicy, error) { 94 | 95 | sp := clients.ServicePolicy{} 96 | 97 | found := false 98 | for _, s := range serv { 99 | if s.Name == csp.Name { 100 | sp.Service = s 101 | found = true 102 | break 103 | } 104 | } 105 | 106 | if !found { 107 | return clients.ServicePolicy{}, errors.New("non-existing service") 108 | } 109 | 110 | return sp, nil 111 | } 112 | -------------------------------------------------------------------------------- /internal/configsyaml/services.go: -------------------------------------------------------------------------------- 1 | package configsyaml 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/greenstatic/opensdp/internal/services" 7 | log "github.com/sirupsen/logrus" 8 | "gopkg.in/yaml.v2" 9 | "io/ioutil" 10 | "net" 11 | "strconv" 12 | "strings" 13 | ) 14 | 15 | type ports []string 16 | 17 | type serviceFile struct { 18 | Name string 19 | IP string 20 | Ports []ports 21 | Tags []string 22 | AccessType []string `yaml:"accessType"` 23 | } 24 | 25 | type servicesFile struct { 26 | Version string 27 | Kind string 28 | Services []serviceFile 29 | } 30 | 31 | func ServicesRead(path string) ([]services.Service, error) { 32 | 33 | // Read file 34 | data, err := ioutil.ReadFile(path) 35 | if err != nil { 36 | return nil, err 37 | } 38 | 39 | // Parse file 40 | sf := servicesFile{} 41 | err = yaml.Unmarshal(data, &sf) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | // Check if correct kind 47 | if sf.Kind != "services" { 48 | return nil, errors.New("file not kind services") 49 | } 50 | 51 | // Parse service 52 | allServices := make([]services.Service, 0, len(sf.Services)) 53 | for _, s := range sf.Services { 54 | serv, err := parseService(s) 55 | if err != nil { 56 | return nil, errors.New(fmt.Sprintf("failed parsing service: %s", err)) 57 | } 58 | 59 | log.WithField("name", serv.Name).Debug("Loaded service configuration") 60 | 61 | allServices = append(allServices, serv) 62 | } 63 | 64 | return allServices, nil 65 | } 66 | 67 | func parseService(s serviceFile) (services.Service, error) { 68 | serv := services.Service{} 69 | 70 | if s.Name == "" { 71 | return services.Service{}, errors.New("service missing field name") 72 | } 73 | serv.Name = s.Name 74 | 75 | var err error 76 | 77 | // Parse IPs 78 | serv.IP = net.ParseIP(s.IP) 79 | if serv.IP == nil { 80 | return services.Service{}, errors.New("failed to parse ip") 81 | } 82 | 83 | // Parse protocols & ports 84 | if len(s.Ports) == 0 { 85 | return services.Service{}, errors.New("missing field ports") 86 | } 87 | serv.ProtoPort, err = parseProtocolAndPort(s.Ports) 88 | if err != nil { 89 | return services.Service{}, errors.New(fmt.Sprintf("bad field ports: %s", err)) 90 | } 91 | 92 | // Parse tags 93 | serv.Tags = s.Tags 94 | 95 | // Parse access types 96 | if len(s.AccessType) == 0 { 97 | return services.Service{}, errors.New("missing field access types") 98 | } 99 | serv.AccessType, err = parseAccessTypes(s.AccessType) 100 | if err != nil { 101 | return services.Service{}, errors.New(fmt.Sprintf("failed to parse access type: %s", err)) 102 | } 103 | 104 | return serv, nil 105 | } 106 | 107 | // Parses a list of strings into a slice of net.IP's 108 | func parseIps(ipsStr []string) ([]net.IP, error) { 109 | ips := make([]net.IP, 0, len(ipsStr)) 110 | for _, ipStr := range ipsStr { 111 | ip := net.ParseIP(ipStr) 112 | if ip == nil { 113 | return nil, errors.New("bad ip") 114 | } 115 | ips = append(ips, ip) 116 | } 117 | 118 | return ips, nil 119 | } 120 | 121 | // Parses a ProtocolPort filed 122 | func parseProtocolAndPort(protoPortStrngs []ports) ([]services.ProtoPort, error) { 123 | 124 | protoPorts := make([]services.ProtoPort, 0, len(protoPortStrngs)) 125 | 126 | for _, ppStr := range protoPortStrngs { 127 | pp := services.ProtoPort{} 128 | 129 | if len(ppStr) != 1 && len(ppStr) != 2 { 130 | return nil, errors.New("bad protocol port combo") 131 | } 132 | 133 | var protocol services.Protocol 134 | switch strings.ToUpper(ppStr[0]) { 135 | case "TCP": 136 | protocol = services.ProtocolTCP 137 | case "UDP": 138 | protocol = services.ProtocolUDP 139 | case "ICMP": 140 | protocol = services.ProtocolICMP 141 | default: 142 | return nil, errors.New("unknown protocol") 143 | } 144 | 145 | pp.Protocol = protocol 146 | 147 | if protocol == services.ProtocolICMP && len(ppStr) != 1 { 148 | return nil, errors.New("icmp has no ports") 149 | } 150 | 151 | if protocol != services.ProtocolICMP && len(ppStr) != 2 { 152 | return nil, errors.New("missing port field in ports entry") 153 | } 154 | 155 | // Parse port, but not for ICMP 156 | if protocol != services.ProtocolICMP { 157 | port, err := strconv.Atoi(ppStr[1]) 158 | if err != nil { 159 | return nil, errors.New("bad port value") 160 | } 161 | pp.Port = uint16(port) 162 | } 163 | 164 | protoPorts = append(protoPorts, pp) 165 | } 166 | 167 | return protoPorts, nil 168 | } 169 | 170 | // Parses a list of access types into a services.AccessType slice 171 | func parseAccessTypes(atStr []string) ([]services.AccessType, error) { 172 | aTypes := make([]services.AccessType, 0, len(atStr)) 173 | 174 | for _, aType := range atStr { 175 | switch aType { 176 | case "OpenSPA": 177 | aTypes = append(aTypes, services.AccessTypeOpenSPA) 178 | default: 179 | return nil, errors.New("unknown access type") 180 | } 181 | } 182 | 183 | return aTypes, nil 184 | } 185 | -------------------------------------------------------------------------------- /internal/openspa/client.go: -------------------------------------------------------------------------------- 1 | package openspa 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | "io" 6 | "net" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | type Client struct { 14 | Cmd string 15 | OSPA string 16 | Server net.IP 17 | Port uint16 18 | } 19 | 20 | type Request struct { 21 | Protocol string 22 | StartPort uint16 23 | EndPort uint16 24 | } 25 | 26 | func (c *Client) Send(req Request, continuous bool) error { 27 | 28 | sPort := strconv.Itoa(int(req.StartPort)) 29 | ePort := strconv.Itoa(int(req.EndPort)) 30 | serverPort := strconv.Itoa(int(c.Port)) 31 | 32 | cmdStr := []string{c.Cmd, "request", c.OSPA, "--protocol", req.Protocol, "-p", sPort, "--end-port", ePort, 33 | "--server-ip", c.Server.String(), "--server-port", serverPort} 34 | 35 | if continuous { 36 | cmdStr = append(cmdStr, "-a") 37 | } 38 | 39 | log.WithField("command", strings.Join(cmdStr, " ")).Debug("OpenSPA command") 40 | 41 | cmd := exec.Command(cmdStr[0], cmdStr[1:]...) 42 | 43 | // Get stdout and stderr 44 | stdout, err := cmd.StdoutPipe() 45 | if err != nil { 46 | return err 47 | } 48 | 49 | stderr, err := cmd.StderrPipe() 50 | if err != nil { 51 | return err 52 | } 53 | 54 | // Start the command 55 | err = cmd.Start() 56 | if err != nil { 57 | return err 58 | } 59 | 60 | defer cmd.Wait() 61 | go io.Copy(os.Stdout, stdout) 62 | go io.Copy(os.Stderr, stderr) 63 | 64 | return nil 65 | } 66 | -------------------------------------------------------------------------------- /internal/server/discover.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/greenstatic/opensdp/internal/services" 6 | "net" 7 | "net/http" 8 | ) 9 | 10 | type DiscoverResponseService struct { 11 | Name string `json:"name"` 12 | IP string `json:"ip"` 13 | Ports [][]string `json:"ports"` 14 | Tags []string `json:"tags"` 15 | AccessType []string `json:"accessType"` 16 | } 17 | 18 | type DiscoverResponse struct { 19 | Success bool `json:"success"` 20 | DeviceId string `json:"deviceId"` 21 | Services []DiscoverResponseService `json:"services"` 22 | } 23 | 24 | // Fills a DiscoverResponseService struct from a services.Service struct. 25 | func (drs *DiscoverResponseService) Create(service services.Service) error { 26 | // Name field 27 | drs.Name = service.Name 28 | 29 | // IP field 30 | drs.IP = service.IP.String() 31 | 32 | // Ports field 33 | ports := make([][]string, 0, len(service.ProtoPort)) 34 | for _, portCombo := range service.ProtoPort { 35 | ports = append(ports, portCombo.StringSlice()) 36 | } 37 | drs.Ports = ports 38 | 39 | // Tags field 40 | drs.Tags = service.Tags 41 | 42 | // Access Type field 43 | accessTypes := make([]string, 0, len(service.AccessType)) 44 | for _, at := range service.AccessType { 45 | accessTypes = append(accessTypes, at.String()) 46 | } 47 | drs.AccessType = accessTypes 48 | 49 | return nil 50 | } 51 | 52 | // Returns a services.Service struct from that data in the DiscoverResponseServices. 53 | func (drs *DiscoverResponseService) ToService() (services.Service, error) { 54 | s := services.Service{} 55 | // Name field 56 | s.Name = drs.Name 57 | 58 | // IP field 59 | s.IP = net.ParseIP(drs.IP) 60 | 61 | // Ports field 62 | ports := make([]services.ProtoPort, 0, len(drs.Ports)) 63 | for _, portCombo := range drs.Ports { 64 | pp := services.ProtoPort{} 65 | err := pp.FromStringSlice(portCombo) 66 | if err != nil { 67 | return services.Service{}, err 68 | } 69 | 70 | ports = append(ports, pp) 71 | } 72 | s.ProtoPort = ports 73 | 74 | // Tags field 75 | s.Tags = drs.Tags 76 | 77 | // Access Type field 78 | accessTypes := make([]services.AccessType, 0, len(drs.AccessType)) 79 | for _, at := range drs.AccessType { 80 | var a services.AccessType 81 | err := a.FromString(at) 82 | 83 | if err != nil { 84 | return services.Service{}, err 85 | } 86 | accessTypes = append(accessTypes, a) 87 | } 88 | s.AccessType = accessTypes 89 | 90 | return s, nil 91 | } 92 | 93 | // Wrapper handler for the discover endpoint. The wrapper allows us to 94 | // inject the clients slice into the handler function. 95 | func (s *Server) discoverResponseWrapper() func(w http.ResponseWriter, req *http.Request) { 96 | 97 | return func(w http.ResponseWriter, req *http.Request) { 98 | cn := req.TLS.PeerCertificates[0].Subject.CommonName 99 | 100 | client, ok := s.Clients[cn] 101 | 102 | if !ok { 103 | w.WriteHeader(http.StatusUnauthorized) 104 | json.NewEncoder(w).Encode(struct { 105 | Successful bool `json:"success"` 106 | Error string `json:"error"` 107 | }{ 108 | false, 109 | "not authorized for any services", 110 | }) 111 | return 112 | } 113 | 114 | cServices := make([]DiscoverResponseService, 0, len(client.Services)) 115 | for _, srv := range client.Services { 116 | drs := DiscoverResponseService{} 117 | drs.Create(srv.Service) 118 | cServices = append(cServices, drs) 119 | } 120 | 121 | json.NewEncoder(w).Encode(DiscoverResponse{true, cn, cServices}) 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /internal/server/server.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "encoding/json" 7 | "github.com/greenstatic/opensdp/internal/clients" 8 | "github.com/greenstatic/opensdp/internal/services" 9 | log "github.com/sirupsen/logrus" 10 | "io/ioutil" 11 | "net" 12 | "net/http" 13 | "time" 14 | ) 15 | 16 | var ( 17 | Version = "0.1.0" 18 | ) 19 | 20 | type Server struct { 21 | CAPath string 22 | ServerCertPath string 23 | ServerKeyPath string 24 | Bind string 25 | Port string 26 | Services []services.Service 27 | Clients map[string]clients.Client 28 | } 29 | 30 | func rootResponse(w http.ResponseWriter, req *http.Request) { 31 | cn := req.TLS.PeerCertificates[0].Subject.CommonName 32 | 33 | json.NewEncoder(w).Encode(struct { 34 | Success bool `json:"success"` 35 | Msg string `json:"msg"` 36 | DeviceId string `json:"deviceId"` 37 | Datetime string `json:"datetime"` 38 | Version string `json:"version"` 39 | }{ 40 | true, 41 | "OpenSDP Server", 42 | cn, 43 | time.Now().Format(time.RFC3339), 44 | Version, 45 | }) 46 | 47 | } 48 | 49 | func (s *Server) Start() { 50 | // Adapted from: https://github.com/levigross/go-mutual-tls 51 | 52 | certBytes, err := ioutil.ReadFile(s.CAPath) 53 | if err != nil { 54 | log.WithField("caCert", s.CAPath).Error("Failed to read CA cert") 55 | log.Error(err) 56 | return 57 | } 58 | 59 | clientCertPool := x509.NewCertPool() 60 | if ok := clientCertPool.AppendCertsFromPEM(certBytes); !ok { 61 | log.Error("Failed to add CA cert to our cert pool") 62 | log.Error(err) 63 | } 64 | 65 | tlsConfig := &tls.Config{ 66 | ClientAuth: tls.RequireAndVerifyClientCert, 67 | ClientCAs: clientCertPool, 68 | CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, 69 | PreferServerCipherSuites: true, 70 | MinVersion: tls.VersionTLS12, 71 | } 72 | 73 | tlsConfig.BuildNameToCertificate() 74 | 75 | http.HandleFunc("/discover", s.discoverResponseWrapper()) 76 | http.HandleFunc("/", rootResponse) 77 | 78 | httpServer := &http.Server{ 79 | Addr: net.JoinHostPort(s.Bind, s.Port), 80 | TLSConfig: tlsConfig, 81 | } 82 | 83 | // Disable HTTP/2 support due to cipher suite error 84 | httpServer.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} 85 | 86 | log.WithFields(log.Fields{ 87 | "bind": s.Bind, 88 | "port": s.Port, 89 | }).Info("Starting server") 90 | 91 | log.Fatalln(httpServer.ListenAndServeTLS(s.ServerCertPath, s.ServerKeyPath)) 92 | } 93 | -------------------------------------------------------------------------------- /internal/services/service.go: -------------------------------------------------------------------------------- 1 | package services 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | type Protocol int 12 | 13 | const ( 14 | // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml 15 | ProtocolICMP Protocol = 1 16 | ProtocolTCP Protocol = 6 17 | ProtocolUDP Protocol = 17 18 | ) 19 | 20 | func (p *Protocol) String() string { 21 | switch *p { 22 | case ProtocolICMP: 23 | return "icmp" 24 | case ProtocolTCP: 25 | return "tcp" 26 | case ProtocolUDP: 27 | return "udp" 28 | default: 29 | return "" 30 | } 31 | } 32 | 33 | func (p *Protocol) FromString(s string) (Protocol, error) { 34 | switch strings.ToLower(s) { 35 | case "icmp": 36 | return ProtocolICMP, nil 37 | case "tcp": 38 | return ProtocolTCP, nil 39 | case "udp": 40 | return ProtocolUDP, nil 41 | default: 42 | return 0, errors.New("unknown protocol") 43 | } 44 | } 45 | 46 | type AccessType int 47 | 48 | const ( 49 | AccessTypeOpenSPA AccessType = iota 50 | ) 51 | 52 | func (at *AccessType) String() string { 53 | switch *at { 54 | case AccessTypeOpenSPA: 55 | return "OpenSPA" 56 | default: 57 | return "" 58 | } 59 | } 60 | 61 | func (at *AccessType) FromString(s string) error { 62 | switch s { 63 | case "OpenSPA": 64 | *at = AccessTypeOpenSPA 65 | default: 66 | return errors.New("unknown access type") 67 | } 68 | return nil 69 | } 70 | 71 | type ProtoPort struct { 72 | Protocol Protocol 73 | Port uint16 74 | } 75 | 76 | // Returns a string slice that contains the [proto, port]. In case the protocol 77 | // does not use ports (eg. icmp) then just return the protocol, [proto]. 78 | func (pp *ProtoPort) StringSlice() []string { 79 | proto := pp.Protocol.String() 80 | p := strconv.Itoa(int(pp.Port)) 81 | 82 | if proto == "icmp" { 83 | return []string{proto} 84 | } 85 | 86 | return []string{proto, p} 87 | } 88 | 89 | // Reverts a string slice into a ProtoPort (opposite of StringSlice). 90 | func (pp *ProtoPort) FromStringSlice(s []string) error { 91 | if len(s) != 1 && len(s) != 2 { 92 | return errors.New("unknown ProtoPort string slice") 93 | } 94 | 95 | var proto Protocol 96 | proto, err := proto.FromString(s[0]) 97 | if err != nil { 98 | return err 99 | } 100 | pp.Protocol = proto 101 | 102 | if len(s) == 1 { 103 | return nil 104 | } 105 | 106 | port, err := strconv.Atoi(s[1]) 107 | if err != nil { 108 | return err 109 | } 110 | pp.Port = uint16(port) 111 | 112 | return nil 113 | } 114 | 115 | // Stringify the ProtoPort like so: 22/tcp 116 | func (pp *ProtoPort) String() string { 117 | p := pp.StringSlice() 118 | 119 | if len(p) == 1 { 120 | // No port definition 121 | return p[0] 122 | } else if len(p) == 2 { 123 | // Port and proto split with slash 124 | // eg. 22/tcp 125 | return fmt.Sprintf("%s/%s", p[1], p[0]) 126 | } 127 | 128 | // StringSlice should not return a slice that is not of length 1 or 2. 129 | return "" 130 | 131 | } 132 | 133 | type Service struct { 134 | Name string 135 | IP net.IP 136 | ProtoPort []ProtoPort 137 | Tags []string 138 | AccessType []AccessType 139 | } 140 | 141 | // Interface that implements function to gain access to a service 142 | type ServiceAccess interface { 143 | Access(Service) error 144 | } 145 | 146 | // Returns slice of the services ports as strings 147 | func (s *Service) ProtoPortToString() []string { 148 | pp := make([]string, 0, len(s.ProtoPort)) 149 | for _, p := range s.ProtoPort { 150 | pp = append(pp, p.String()) 151 | } 152 | return pp 153 | } 154 | 155 | // Returns slice of services access type as strings 156 | func (s *Service) AccessTypeToString() []string { 157 | at := make([]string, 0, len(s.AccessType)) 158 | for _, a := range s.AccessType { 159 | at = append(at, a.String()) 160 | } 161 | return at 162 | } 163 | --------------------------------------------------------------------------------