pax_global_header00006660000000000000000000000064151771161600014517gustar00rootroot0000000000000052 comment=6398321a055d64862fb74a13e8e4048909722234 sso-mib-0.9.0/000077500000000000000000000000001517711616000130765ustar00rootroot00000000000000sso-mib-0.9.0/.clang-format000066400000000000000000000062201517711616000154510ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-only # SPDX-FileCopyrightText: (C) 2024 Siemens AG # # clang-format configuration file. Intended for clang-format >= 11. # Based on Linux kernel coding style. --- AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: false AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeComma BreakAfterJavaFieldAnnotations: false BreakStringLiterals: false ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: false IncludeBlocks: Preserve IncludeCategories: - Regex: '.*' Priority: 1 IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false IndentGotoLabels: false IndentPPDirectives: None IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 4 ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: true # Taken from git's rules PenaltyBreakAssignment: 10 PenaltyBreakBeforeFirstCallParameter: 30 PenaltyBreakComment: 10 PenaltyBreakFirstLessLess: 0 PenaltyBreakString: 10 PenaltyExcessCharacter: 100 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: false SortIncludes: false SortUsingDeclarations: false SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatementsExceptForEachMacros SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp03 TabWidth: 4 UseTab: Always ... sso-mib-0.9.0/.editorconfig000066400000000000000000000002551517711616000155550ustar00rootroot00000000000000# SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: (C) 2025 Siemens AG [*] end_of_line = lf insert_final_newline = true [*.{c,h}] indent_style = tab indent_size = 4 sso-mib-0.9.0/.github/000077500000000000000000000000001517711616000144365ustar00rootroot00000000000000sso-mib-0.9.0/.github/workflows/000077500000000000000000000000001517711616000164735ustar00rootroot00000000000000sso-mib-0.9.0/.github/workflows/build.yml000066400000000000000000000065111517711616000203200ustar00rootroot00000000000000# SPDX-FileCopyrightText: Copyright 2025 Siemens AG # # SPDX-License-Identifier: MIT name: build sso-mib on: push: branches: - main pull_request: workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to checkout the repository permissions: contents: read env: LIBJWT3_VERSION: "3.2.3" LIBJWT3_SHA256: c6d8a4ead0321317937cc29d8ebc5be48d114d02e007711bb2d4cca5d2a6d713 jobs: reuse-and-codestyle: runs-on: ubuntu-24.04 steps: - name: checkout repository uses: actions/checkout@v6 with: fetch-depth: 0 - name: install dependencies run: | pip3 install --break-system-packages fsfe-reuse git clean -f -d - name: execute linters run: | reuse lint build: runs-on: ubuntu-24.04 steps: - name: checkout repository uses: actions/checkout@v6 with: fetch-depth: 0 - name: install dependencies run: | sudo apt-get update sudo apt-get install -y --no-install-recommends \ build-essential \ ninja-build \ meson \ doxygen \ graphviz \ libcurl4-openssl-dev \ libgio3.0-cil-dev \ libjson-glib-dev \ libdbus-1-dev \ uuid-dev \ libjwt-dev - name: build components run: | meson setup -Ddocumentation=True -Dexamples=True build cd build && ninja - name: upload API docs uses: actions/upload-pages-artifact@v5 id: deployment with: path: build/api/ build-with-libjwt-variants: runs-on: ubuntu-24.04 container: "debian:trixie" steps: - name: checkout repository uses: actions/checkout@v6 with: fetch-depth: 0 - name: install dependencies run: | apt-get update apt-get install -y --no-install-recommends \ build-essential meson cmake ninja-build curl ca-certificates \ libjansson-dev libssl-dev \ libgio-2.0-dev libjson-glib-dev libdbus-1-dev uuid-dev - name: build sso-mib-tool without libjwt run: | meson -Dlibjwt=disabled build-minimal ninja -C build-minimal sso-mib-tool - name: build libjwt3 run: | curl -L -q https://github.com/benmcollins/libjwt/releases/download/v${LIBJWT3_VERSION}/libjwt-${LIBJWT3_VERSION}.tar.xz \ > /tmp/libjwt-${LIBJWT3_VERSION}.tar.xz echo "$LIBJWT3_SHA256 /tmp/libjwt-${LIBJWT3_VERSION}.tar.xz" | sha256sum -c WORKDIR=$(pwd) cd /tmp tar -xf libjwt-${LIBJWT3_VERSION}.tar.xz cd libjwt-${LIBJWT3_VERSION} cmake -B build -GNinja cmake --build build cmake --install build cd $WORKDIR - name: build sso-mib-tool with libjwt3 run: | meson -Dlibjwt=enabled build cd build && ninja sso-mib-tool deploy: if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 needs: build permissions: pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Deploy API docs id: deployment uses: actions/deploy-pages@v5 sso-mib-0.9.0/.gitignore000066400000000000000000000001571517711616000150710ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2024 Siemens AG # SPDX-License-Identifier: GPL-2.0-only build/ install/ .vscode/ sso-mib-0.9.0/CONTRIBUTING.md000066400000000000000000000043751517711616000153400ustar00rootroot00000000000000 # Contributing to sso-mib Contributions are always welcome. This document explains the general requirements on contributions and the recommended preparation steps. ## Contribution Checklist - use git to manage your changes [*recommended*] - follow our C coding style (check with clang-format) [**required**] - add signed-off to all patches [**required**] - to certify the "Developer's Certificate of Origin", see below - check with your employer when not working on your own! - post follow-up version(s) if feedback requires this - send reminder if nothing happened after about a week - when adding new files, add a license header (see existing files) [**required**] Developer's Certificate of Origin 1.1 ------------------------------------- When signing-off a patch for this project like this Signed-off-by: Random J Developer using your real name (no pseudonyms or anonymous contributions), you declare the following: By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. sso-mib-0.9.0/LICENSES/000077500000000000000000000000001517711616000143035ustar00rootroot00000000000000sso-mib-0.9.0/LICENSES/GPL-2.0-only.txt000066400000000000000000000416711517711616000167530ustar00rootroot00000000000000GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice sso-mib-0.9.0/LICENSES/LGPL-2.1-only.txt000066400000000000000000000626211517711616000170660ustar00rootroot00000000000000GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it! sso-mib-0.9.0/LICENSES/MIT.txt000066400000000000000000000020501517711616000154720ustar00rootroot00000000000000MIT License Copyright (c) 2025 Siemens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. sso-mib-0.9.0/README.md000066400000000000000000000067651517711616000143730ustar00rootroot00000000000000[![API Docs](https://img.shields.io/badge/API-documented-blue)](https://siemens.github.io/sso-mib/) # Single-Sign-On using Microsoft Identity Broker (SSO-MIB) sso-mib is a lightweight C library and CLI tool for interacting with a Microsoft Identity Broker to obtain authentication tokens via DBus. By that, it implements support for the OIDC extension [MS-OAPXBC], sections [3.1.5.1.2 Request for Primary Refresh Token](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oapxbc/d32d5cd0-05d4-4ec2-8bcc-ac29ce711c23), [3.1.5.1.3 Exchange Primary Refresh Token for Access Token](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oapxbc/06e2bf0d-8cea-4b11-ad78-d212330ebda9) and can be used to obtain Proof-of-Possession tokens for RDP [[MS-RDPBCGR](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/e967ebeb-9e9f-443e-857a-5208802943c2)]. ## Dependencies - Gio2.0 - JSON-Glib - libdbus - libuuid - libjwt (only for sso-mib-tool) ## Interface The interface of the library is defined in ``. Only this file must be included. The semantics follow roughly the [MSAL Python](https://msal-python.readthedocs.io/en/latest/) library. ### Logging We integrate with the GLib message logging system and use the domain `ssomib`. To debug the input and output parameters of the DBus calls, set the environment variable `G_MESSAGES_DEBUG=ssomib`. We try to keep the interface both API and ABI compatible, however this is not guaranteed prior to version 1.0. ### How do I use this library Note: for simplicity, this code does not have error handling and cleanup logic. ```c #include const gchar *client_id = ""; const gchar *authority = MIB_AUTHORITY_COMMON; MIBClientApp *app = mib_public_client_app_new(client_id, authority, NULL, NULL); GSList *scopes = NULL; scopes = g_slist_append(scopes, g_strdup(MIB_SCOPE_GRAPH_DEFAULT)); /// get default / first known account MIBAccount *account = mib_client_app_get_account_by_upn(app, NULL); /// get a fresh token pair (access, refresh) MIBPrt *prt = mib_client_app_acquire_token_silent(app, account, scopes, NULL, NULL, NULL); /// get a PRT SSO Cookie MIBPrtSsoCookie *prt_cookie = mib_client_app_acquire_prt_sso_cookie(app, account, MIB_SSO_URL_DEFAULT, scopes); const char *name = mib_prt_sso_cookie_get_name(cookie); const char *value = mib_prt_sso_cookie_get_content(cookie); ``` Further examples are provided in `examples`. ## Frontend The `sso-mib-tool` provides a simple frontend to interact with the library. For example, the following can be used to obtain a token for sending mail via SMTP: ```bash $ sso-mib-tool acquireTokenInteractive -f json \ -s \ -r https://login.microsoftonline.com/common/oauth2/nativeclient \ -x \ -S offline_access -S 'https://outlook.office365.com/SMTP.Send' ``` ## Maintainers - Felix Moessbauer - Andreas Ziegler ## Code Integrity Since version `v0.5`, git release tags are signed with one of the following maintainer GPG keys: - `AF73F6EF5A53CFE304569F50E648A311F67A50FC` (Felix Moessbauer) Since version `v0.8`, the following keys are used: 3785ED68D0F83B7BD7D23D7FE1136CEB2754A0BD (Felix Moessbauer) ## License The library is licensed according to the terms of the GNU Lesser General Public License v2.1. The tooling is licensed according to the terms of the GNU Public License v2.0. The examples are licensed according to the terms of the MIT License. sso-mib-0.9.0/REUSE.toml000066400000000000000000000005601517711616000146570ustar00rootroot00000000000000version = 1 SPDX-PackageName = "sso-mib" SPDX-PackageSupplier = "Felix Moessbauer " SPDX-PackageDownloadLocation = "https://github.com/siemens/sso-mib" [[annotations]] path = ["README.md", "dbus/spec/com.microsoft.identity.broker1.xml"] precedence = "aggregate" SPDX-FileCopyrightText = "2025 Siemens AG" SPDX-License-Identifier = "MIT" sso-mib-0.9.0/dbus/000077500000000000000000000000001517711616000140335ustar00rootroot00000000000000sso-mib-0.9.0/dbus/spec/000077500000000000000000000000001517711616000147655ustar00rootroot00000000000000sso-mib-0.9.0/dbus/spec/com.microsoft.identity.broker1.xml000066400000000000000000000033511517711616000234670ustar00rootroot00000000000000 sso-mib-0.9.0/docs/000077500000000000000000000000001517711616000140265ustar00rootroot00000000000000sso-mib-0.9.0/docs/doxygen.in000066400000000000000000000022731517711616000160370ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2024 Siemens AG # SPDX-License-Identifier: LGPL-2.1-only PROJECT_NAME = @PACKAGE_NAME@ PROJECT_NUMBER = @PACKAGE_VERSION@ PROJECT_BRIEF = @PACKAGE_DESCRIPTION@ JAVADOC_AUTOBRIEF = YES TAB_SIZE = 4 OPTIMIZE_OUTPUT_FOR_C = YES EXTRACT_ALL = YES EXTRACT_STATIC = NO MAX_INITIALIZER_LINES = 0 WARNINGS = YES QUIET = YES INPUT = "@apisrcdir@" "@MAINPAGE@" IMAGE_PATH = "@builddir@" GENERATE_HTML = YES GENERATE_HTMLHELP = NO HTML_OUTPUT = api SEARCHENGINE = YES SERVER_BASED_SEARCH = NO GENERATE_LATEX = NO MACRO_EXPANSION = YES EXPAND_ONLY_PREDEF = YES DOTFILE_DIRS = "@builddir@" EXAMPLE_PATH = "@builddir@" SHOW_NAMESPACES = NO STRIP_FROM_INC_PATH = "@apisrcdir@" USE_MDFILE_AS_MAINPAGE = "@MAINPAGE@" PREDEFINED = PUBLIC_API= DOXYGEN=1 G_BEGIN_DECLS G_END_DECLS EXCLUDE_SYMBOLS = PUBLIC_API _SSO_MIB_INSIDE_ G_BEGIN_DECLS G_END_DECLS STRIP_FROM_PATH = "@apisrcdir@" ALIASES += dbuscall{1}="\note Synchronous DBus call to \c \1" sso-mib-0.9.0/docs/meson.build000066400000000000000000000022371517711616000161740ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2024 Siemens AG # SPDX-License-Identifier: LGPL-2.1-only doxygen = find_program('doxygen', required : false) if not doxygen.found() error('Program "doxygen" not found or not executable. Try building with -Ddocumentation=false') endif src_doxygen = [] foreach f : libsso_mib_hdrs + 'README.md' src_doxygen += join_paths(meson.project_source_root(), f) endforeach doc_config = configuration_data() doc_config.set('PACKAGE_NAME', meson.project_name()) doc_config.set('PACKAGE_VERSION', meson.project_version()) doc_config.set('PACKAGE_DESCRIPTION', project_description) doc_config.set('builddir', meson.current_build_dir()) doc_config.set('apisrcdir', join_paths(meson.project_source_root(), 'include')) doc_config.set('MAINPAGE', join_paths(meson.project_source_root(), 'README.md')) doxyfile = configure_file(input : 'doxygen.in', output : 'doxygen', configuration : doc_config, install : false) custom_target('doxygen', input : [ doxyfile ] + src_doxygen, output : [ '.' ], command : [ doxygen, doxyfile ], install : false, build_by_default : true) sso-mib-0.9.0/examples/000077500000000000000000000000001517711616000147145ustar00rootroot00000000000000sso-mib-0.9.0/examples/avatar/000077500000000000000000000000001517711616000161725ustar00rootroot00000000000000sso-mib-0.9.0/examples/avatar/main.c000066400000000000000000000051751517711616000172720ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: MIT * * This example demonstrates how to get an access token from the broker and use * that to get the avatar picture of the calling user from the MS Graph API. */ #include "sso-mib.h" #include #include #define EDGE_BROWSER_CLIENT_ID "d7b530a4-7680-4c23-a8bf-c52c121d2e87" #define AVATAR_URL "https://graph.microsoft.com/v1.0/me/photo/$value" static void fetch_avatar(const char *bearer, FILE *outfile) { struct curl_slist *headers = NULL; CURLcode ret; long http_code = 0L; curl_global_init(CURL_GLOBAL_DEFAULT); CURL *curl = curl_easy_init(); if (!curl) { g_printerr("could not initialize CURL\n"); curl_global_cleanup(); return; } headers = curl_slist_append(headers, "Accept: image/jpeg"); curl_easy_setopt(curl, CURLOPT_URL, AVATAR_URL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, bearer); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); g_print("Fetch avatar\n"); ret = curl_easy_perform(curl); if (ret != CURLE_OK) { g_printerr("error performing request\n"); } else { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); g_print("HTTP Response Code: %ld\n", http_code); } curl_slist_free_all(headers); curl_easy_cleanup(curl); curl_global_cleanup(); } int main() { const gchar *client_id = EDGE_BROWSER_CLIENT_ID; const gchar *authority = MIB_AUTHORITY_COMMON; int ret = 0; MIBClientApp *app = mib_public_client_app_new(client_id, authority, NULL, NULL); GSList *scopes = NULL; /* get all registered accounts, select first one */ GSList *accounts = mib_client_app_get_accounts(app); MIBAccount *account = g_slist_nth_data(accounts, 0); if (!account) { g_printerr("no account is registered\n"); g_object_unref(app); return -1; } FILE *f = fopen("avatar.jpg", "w"); if (!f) { g_printerr("could not open file\n"); ret = -1; goto cleanup; } printf("Acquire Bearer token\n"); scopes = g_slist_append(scopes, g_strdup("User.Read")); MIBPrt *prt = mib_client_app_acquire_token_silent(app, account, scopes, NULL, NULL, NULL); if (!prt) { printf("Failed to get Graph API token\n"); ret = -1; goto cleanup; } const char *token = mib_prt_get_access_token(prt); fetch_avatar(token, f); printf("Successfully stored avatar picture in 'avatar.jpg'\n"); cleanup: if (f) fclose(f); g_slist_free_full(scopes, (GDestroyNotify)g_free); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_clear_object(&prt); g_object_unref(app); return ret; } sso-mib-0.9.0/examples/meson.build000066400000000000000000000010511517711616000170530ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2025 Siemens AG # SPDX-License-Identifier: MIT curldep = dependency('libcurl') example_avatar = executable( 'mib-example-avatar', 'avatar/main.c', install : false, include_directories : public_headers, link_with : [libsso_mib], dependencies: [glibdep, giodep, uuiddep, curldep] ) example_onedrive = executable( 'mib-example-onedrive', 'onedrive/main.c', install : false, include_directories : public_headers, link_with : [libsso_mib], dependencies: [glibdep, giodep, uuiddep, curldep, jsondep] ) sso-mib-0.9.0/examples/onedrive/000077500000000000000000000000001517711616000165275ustar00rootroot00000000000000sso-mib-0.9.0/examples/onedrive/main.c000066400000000000000000000107671517711616000176320ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: MIT * * This example demonstrates how to get an access token from the broker and use * that to list the top-level files in the users OneDrive. */ #include "sso-mib.h" #include #include #include /* OneDrive Client for Linux */ #define CLIENT_ID "d50ca740-c83f-4d1b-b616-12c519384f0c" /* reduce the set of properties we fetch to "name" */ #define ONEDRIVE_LIST_FILES_URL \ "https://graph.microsoft.com/v1.0/me/drive/root/children?$select=name" /* the default application requires a non-broker redirect URI */ #define APP_REDIRECT_URI \ "https://login.microsoftonline.com/common/oauth2/nativeclient" struct memory { char *response; size_t size; }; /* It would be more efficient to directly stream into the parser, * but for that we would have to implement an adapter to a GInputStream. * Instead, we just write the data to a buffer and parse this. */ static size_t cb(char *data, size_t size, size_t nmemb, void *clientp) { size_t realsize; struct memory *mem = (struct memory *)clientp; if (size != 0 && nmemb > SIZE_MAX / size) return 0; realsize = size * nmemb; if (realsize > SIZE_MAX - mem->size - 1) return 0; char *ptr = realloc(mem->response, mem->size + realsize + 1); if (!ptr) return 0; mem->response = ptr; memcpy(&(mem->response[mem->size]), data, realsize); mem->size += realsize; mem->response[mem->size] = 0; return realsize; } /** * Print a list of top-level items in the users OneDrive */ static void parse_response(char *data, size_t size) { JsonParser *parser = NULL; JsonNode *root = NULL; GError *error = NULL; gboolean parse_ok = 0; JsonObject *rootobj = NULL, *entry = NULL; JsonArray *items = NULL; parser = json_parser_new(); parse_ok = json_parser_load_from_data(parser, data, size, &error); if (!parse_ok) { g_warning("could not parse JSON: %s", error->message); g_warning("data: %s", data); goto cleanup; } /* for simplicity reasons, we only parse expected data */ root = json_parser_get_root(parser); rootobj = json_node_get_object(root); items = json_object_get_array_member(rootobj, "value"); g_print("OneDrive elements\n"); for (guint i = 0; i < json_array_get_length(items); i++) { entry = json_array_get_object_element(items, i); const gchar *name = json_object_get_string_member(entry, "name"); g_print("\t%s\n", name); } cleanup: g_clear_error(&error); g_object_unref(parser); } static void list_top_level(const char *bearer) { struct curl_slist *headers = NULL; CURLcode ret; long http_code = 0L; struct memory chunk = { 0 }; curl_global_init(CURL_GLOBAL_DEFAULT); CURL *curl = curl_easy_init(); if (!curl) { g_printerr("could not initialize CURL\n"); curl_global_cleanup(); return; } headers = curl_slist_append(headers, "Accept: application/json"); curl_easy_setopt(curl, CURLOPT_URL, ONEDRIVE_LIST_FILES_URL); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, bearer); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); g_print("Fetch list of files\n"); ret = curl_easy_perform(curl); if (ret != CURLE_OK) { g_printerr("error performing request\n"); } else { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 200) { parse_response(chunk.response, chunk.size); } } free(chunk.response); curl_slist_free_all(headers); curl_easy_cleanup(curl); curl_global_cleanup(); } int main() { MIBClientApp *app = NULL; GSList *scopes = NULL; char *const *granted_scopes = NULL; /* if NULL, it is auto-resolved. Could also come from a config */ const gchar *upn_hint = NULL; MIBPrt *token = NULL; app = mib_public_client_app_new(CLIENT_ID, MIB_AUTHORITY_COMMON, NULL, NULL); if (!app) goto cleanup; mib_client_app_set_redirect_uri(app, APP_REDIRECT_URI); scopes = g_slist_append(scopes, "Files.Read"); token = mib_client_app_acquire_token_interactive( app, scopes, MIB_PROMPT_UNSET, upn_hint, NULL, NULL, NULL); if (!token) { g_printerr("could not get token\n"); goto cleanup; } /* check which scopes were granted */ g_print("granted scopes:\n"); granted_scopes = mib_prt_get_granted_scopes(token); while (*granted_scopes) { g_print("\t%s\n", *granted_scopes++); } list_top_level(mib_prt_get_access_token(token)); cleanup: g_clear_object(&token); g_slist_free(scopes); g_clear_object(&app); } sso-mib-0.9.0/examples/smtp-o365/000077500000000000000000000000001517711616000163715ustar00rootroot00000000000000sso-mib-0.9.0/examples/smtp-o365/main.c000066400000000000000000000062101517711616000174600ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: MIT * * This example showcases a fully-functional git credential helper to * authenticate git send-email on Office365 using tokens from the broker. * * The following data can also be set via environment variables: * - MIB_GCH_SMTP_AUTHORITY : authority to run OAUTH2 against * - MIB_GCH_SMTP_CLIENT_ID : client-id of the application * * Example entry in .gitconfig * [credential "smtp://"] * helper = !sso-mib-gch-smtp-o365 [] [] */ #include "sso-mib.h" #include #define MAX_LINE 512 #define MAX_VAL 256 #define MAX_CMD_LEN 16 #define APP_REDIRECT_URI \ "https://login.microsoftonline.com/common/oauth2/nativeclient" typedef struct { char username[MAX_VAL]; char protocol[MAX_VAL]; } GitCredInput; void parse_git_cred_input(GitCredInput *out) { char line[MAX_LINE]; while (fgets(line, sizeof(line), stdin)) { char *eq, *key, *val; line[strcspn(line, "\r\n")] = '\0'; if ((eq = strchr(line, '=')) == NULL) continue; *eq = '\0'; key = line; val = eq + 1; if (strcmp(key, "username") == 0) { strncpy(out->username, val, sizeof(out->username) - 1); out->username[sizeof(out->username) - 1] = '\0'; } else if (strcmp(key, "protocol") == 0) { strncpy(out->protocol, val, sizeof(out->protocol) - 1); out->protocol[sizeof(out->protocol) - 1] = '\0'; } } } int main(int argc, char **argv) { MIBClientApp *app = NULL; GSList *scopes = NULL; MIBPrt *token = NULL; MIBAccount *account = NULL; GitCredInput input = { .username = "", .protocol = "" }; const gchar *authority = getenv("MIB_GCH_SMTP_AUTHORITY"); const gchar *client_id = getenv("MIB_GCH_SMTP_CLIENT_ID"); const gchar *cmd = argv[argc - 1]; if (!strncmp(cmd, "approve", MAX_CMD_LEN) || !strncmp(cmd, "reject", MAX_CMD_LEN) || !strncmp(cmd, "capability", MAX_CMD_LEN)) { // no output expected return 0; } if (argc >= 3) { client_id = argv[1]; } if (argc >= 4) { authority = argv[2]; } if (!authority) { fprintf( stderr, "missing authority, set via CLI or env-var 'MIB_GCH_SMTP_AUTHORITY'\n"); return 1; } if (!client_id) { fprintf( stderr, "missing client-id, set via CLI or env-var 'MIB_GCH_SMTP_CLIENT_ID'\n"); return 1; } parse_git_cred_input(&input); // helper called for wrong protocol if (strcmp(input.protocol, "smtp") != 0) goto cleanup; app = mib_public_client_app_new(client_id, authority, NULL, NULL); if (!app) goto cleanup; mib_client_app_set_redirect_uri(app, APP_REDIRECT_URI); scopes = g_slist_append(scopes, "https://outlook.office365.com/SMTP.Send"); token = mib_client_app_acquire_token_interactive( app, scopes, MIB_PROMPT_UNSET, input.username, NULL, NULL, NULL); if (!token) { g_printerr("could not get token\n"); goto cleanup; } account = mib_prt_get_account(token); g_print("username=%s\n", mib_account_get_username(account)); g_print("password=%s\n", mib_prt_get_access_token(token)); g_print("password_expiry_utc=%jd\n", mib_prt_get_expires_on(token)); g_print("authtype=bearer\n"); cleanup: g_clear_object(&token); g_slist_free(scopes); g_clear_object(&app); return 0; } sso-mib-0.9.0/include/000077500000000000000000000000001517711616000145215ustar00rootroot00000000000000sso-mib-0.9.0/include/mib-account.h000066400000000000000000000025251517711616000170770ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #include #include #include "mib-exports.h" /** * \defgroup account Account * \brief Account object as returned by \ref mib_client_app_get_accounts * \addtogroup account * @{ */ G_BEGIN_DECLS #ifndef DOXYGEN #define MIB_TYPE_ACCOUNT mib_account_get_type() G_DECLARE_FINAL_TYPE(MIBAccount, mib_account, MIB, ACCOUNT, GObject) #else typedef void* MIBAccount; #endif PUBLIC_API const gchar *mib_account_get_client_info(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_environment(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_family_name(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_given_name(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_home_account_id(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_local_account_id(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_name(MIBAccount *self); PUBLIC_API const gchar *mib_account_get_username(MIBAccount *self); PUBLIC_API time_t mib_account_get_password_expiry(MIBAccount *self); PUBLIC_API void mib_account_get_realm(MIBAccount *self, uuid_t realm); G_END_DECLS /** @}*/ sso-mib-0.9.0/include/mib-client-app.h000066400000000000000000000202221517711616000174710ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #include #include "mib-client-app.h" #include "mib-account.h" #include "mib-exports.h" #include "mib-pop-params.h" #include "mib-prt-sso-cookie.h" #include "mib-prt.h" /** * \defgroup clientapp Client App * \brief OAuth2 Client Application * \addtogroup clientapp * @{ */ /** * \brief Common authority for all tenants */ #define MIB_AUTHORITY_COMMON "https://login.microsoftonline.com/common" /** * \brief Default SSO URL */ #define MIB_SSO_URL_DEFAULT "https://login.microsoftonline.com/" /** * \brief Default scope for graph API */ #define MIB_SCOPE_GRAPH_DEFAULT "https://graph.microsoft.com/.default" G_BEGIN_DECLS enum MIB_PROMPT { MIB_PROMPT_UNSET = 0, MIB_PROMPT_NONE = 1 << 0, MIB_PROMPT_SELECT_ACCOUNT = 1 << 1, MIB_PROMPT_CONSENT = 1 << 2, MIB_PROMPT_LOGIN = 1 << 3 }; #ifndef DOXYGEN #define MIB_TYPE_CLIENT_APP mib_client_app_get_type() G_DECLARE_FINAL_TYPE(MIBClientApp, mib_client_app, MIB, CLIENT_APP, GObject) #else typedef void *MIBClientApp; #endif /** * \brief Start a new session * \ingroup highlevel * * This function creates a new session for the given client_id. * The user is responsible for freeing the object with \c g_object_unref . * * \param client_id Azure client application ID * \param authority Azure authority URL (e.g. value from MIB_AUTHORITY_COMMON) * \param cancellable Cancellable object or NULL * \param error GError object or NULL * \return opaque client app object */ PUBLIC_API MIBClientApp *mib_public_client_app_new(const gchar *client_id, const gchar *authority, GCancellable *cancellable, GError **error); PUBLIC_API const gchar *mib_client_app_get_client_id(const MIBClientApp *self); PUBLIC_API const gchar * mib_client_app_get_correlation_id(const MIBClientApp *self); PUBLIC_API const gchar *mib_client_app_get_authority(const MIBClientApp *self); PUBLIC_API int mib_client_app_get_enforce_interactive(const MIBClientApp *self); /** * \brief do not try silent mode first on interactive * * When requesting a token via \ref mib_client_app_acquire_token_interactive, * internally a non-interactive token acquire is tried first. Only if that fails, * the interactive acquire is performed. If set to \c true, this non-interactive * part is skipped. */ PUBLIC_API void mib_client_app_set_enforce_interactive(MIBClientApp *self, int enforce); /** * Returns the client-id specific redirect URI for broker clients, according to * https://msal-python.readthedocs.io/en/latest/#publicclientapplication * * The caller is responsible for freeing the returned string. */ PUBLIC_API gchar * mib_client_app_get_broker_redirect_uri(const MIBClientApp *self); /** * \brief Override the address to return to upon receiving a response from the authority. * * If this method is not called, the broker redirect URI (returned by * \ref mib_client_app_get_broker_redirect_uri ) is used. * * \note The redirect URI must be in the list of allowed redirect URIs for * the target application. Otherwise, the token acquisition will not work. */ PUBLIC_API void mib_client_app_set_redirect_uri(MIBClientApp* self, const gchar* uri); /** * \brief Get the version of the Linux broker * * \dbuscall{getLinuxBrokerVersion} * * \param app client app object * \param msal_cpp_version MSAL CPP version (non-empty string, e.g. 1.28.0) * \return broker version (or null on error, must be freed with g_free()) */ PUBLIC_API gchar * mib_client_app_get_linux_broker_version(MIBClientApp *app, const gchar *msal_cpp_version); /** * \brief Get the accounts associated with the session * * Returns a list of \ref MIBAccount entries associated with the application. * Which accounts are returned depends on the apps client_id. * * The user is responsible for freeing the list, e.g. with * \c g_slist_free_full(accounts,(GDestroyNotify)g_object_unref) * * \dbuscall{getAccounts} * * \param app client app object * \return list of \ref MIBAccount* */ PUBLIC_API GSList *mib_client_app_get_accounts(MIBClientApp *app); /** * \brief Filter the registered accounts by UPN and return the first match * * Returns the first registered account that matches the provided * "User Principal Name" (upn). If \c upn is \c NULL , the first account * is returned. * * \dbuscall{getAccounts} * * \param app client app object * \param upn User Principal Name * \return first matching account */ PUBLIC_API MIBAccount *mib_client_app_get_account_by_upn(MIBClientApp *app, const gchar *upn); /** * \brief Acquire a token without user interaction * * This function acquires a token for the given account and requested scopes. * * The user is responsible for freeing the object with \c g_object_unref . * * \dbuscall{acquireTokenSilently} * * \param app client app object * \param account mib account reference * \param scopes list of scopes (\c gchar* entries) * \param claims_challenge string of a JSON object which contains lists of * claims being requested from these locations or NULL. * \param auth_scheme PoP parameters or NULL * \param id_token ID token (NULL to request a fresh one) \return PRT token * struct */ PUBLIC_API MIBPrt *mib_client_app_acquire_token_silent( MIBClientApp *app, MIBAccount *account, GSList *scopes, const gchar *claims_challenge, MIBPopParams *auth_scheme, const gchar *id_token); /** * \brief Acquire a token without with user interaction (if needed) * * This function acquires a token and asks the user for the needed data. * Note, that (similar to MSAL's implementation), internally a silent token acquire * is performed first. In case that fails, the interactive version is performed. * * The user is responsible for freeing the object with \c g_object_unref . * * \dbuscall{acquireTokenInteractively} * * \param app client app object * \param scopes list of scopes (\c gchar* entries) * \param prompt what the user should be asked * \param login_hint Identifier of the user. Generally a User Principal Name (UPN) (or NULL) * \param domain_hint Not Implemented (yet). Set to NULL * \param claims_challenge string of a JSON object which contains lists of * claims being requested from these locations or NULL. * \param auth_scheme PoP parameters or NULL */ PUBLIC_API MIBPrt *mib_client_app_acquire_token_interactive( MIBClientApp *app, GSList *scopes, enum MIB_PROMPT prompt, const gchar *login_hint, const gchar *domain_hint, const gchar *claims_challenge, MIBPopParams *auth_scheme); /** * \brief Acquire a PRT SSO cookie * * This function acquires a PRT SSO cookie for the given account, SSO URL and * requested scopes. * * The user is responsible for freeing the object with \c g_object_unref . * * \dbuscall{acquirePrtSsoCookie} * * \param app client app object * \param account mib account reference * \param sso_url SSO URL * \param scopes list of scopes * \return PRT SSO cookie struct */ PUBLIC_API MIBPrtSsoCookie * mib_client_app_acquire_prt_sso_cookie(MIBClientApp *app, MIBAccount *account, const gchar *sso_url, GSList *scopes); /** * \brief Generate a signed HTTP request * * This function implements the Acquiring Access Tokens Protected with * Proof-of-Possession (PoP) specification. * * The user is responsible for freeing the string with \c g_free . * * \dbuscall{generateSignedHttpRequest} * * \param app client app object * \param account mib account reference * \param pop_params PoP parameters * \return access token (must be freed with g_free()) */ PUBLIC_API gchar *mib_client_app_generate_signed_http_request( MIBClientApp *app, MIBAccount *account, MIBPopParams *pop_params); /** * \brief Signout the account and clear linked token cache * * \dbuscall{removeAccount} * * \param app client app object * \param account mib account reference * \return 0 on success, -1 on error */ PUBLIC_API int mib_client_app_remove_account(MIBClientApp *app, MIBAccount *account); G_END_DECLS /** @} */ sso-mib-0.9.0/include/mib-exports.h000066400000000000000000000005321517711616000171430ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #ifdef BUILDING_SSO_MIB #define PUBLIC_API __attribute__((visibility("default"))) #else #define PUBLIC_API #endif sso-mib-0.9.0/include/mib-pop-params.h000066400000000000000000000037611517711616000175250ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #include #include "mib-exports.h" /** * \defgroup popparams PoP Parameters * \brief Proof-of-Possession Parameters * \addtogroup popparams * @{ */ /** * \brief Authentication schemes */ enum MIB_AUTH_SCHEME { MIB_AUTH_SCHEME_BEARER = 1, MIB_AUTH_SCHEME_POP = 2 }; /** * \brief Request methods */ enum MIB_REQUEST_METHOD { MIB_REQUEST_METHOD_GET = 1, MIB_REQUEST_METHOD_POST = 2, MIB_REQUEST_METHOD_PUT = 3 }; #ifndef DOXYGEN #define MIB_TYPE_POP_PARAMS mib_pop_params_get_type() G_DECLARE_FINAL_TYPE(MIBPopParams, mib_pop_params, MIB, POP_PARAMS, GObject) #else typedef void* MIBPopParams; #endif /** * \brief Create new Proof-of-Possession parameters object * * The caller is responsible for freeing the returned object with \c g_object_unref . * * \param auth_scheme Indicates whether a bearer or pop token is requested * \param method The HTTP method of the request that will use the signed token * \param uri The URL of the protected resource for which the access token is being issued * \return The PoP parameters object */ PUBLIC_API MIBPopParams* mib_pop_params_new(enum MIB_AUTH_SCHEME auth_scheme, enum MIB_REQUEST_METHOD method, const gchar* uri); PUBLIC_API void mib_pop_params_set_shr_claims(MIBPopParams *self, const gchar *claims); PUBLIC_API void mib_pop_params_set_shr_nonce(MIBPopParams *self, const gchar* nonce); /** * \brief Set the decoded "kid" part from a "req_cnf" * * A RFC9201 \c req_cnf is an OAuth2 parameter allowing clients to request a * specific PoP key in an access token from a token endpoint. This value is * a base64 encoded string with key \c kid and a value. This value needs to * be provided here. */ PUBLIC_API void mib_pop_params_set_kid(MIBPopParams *self, const gchar* kid); /** @} */ sso-mib-0.9.0/include/mib-prt-sso-cookie.h000066400000000000000000000015061517711616000203170ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only * */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #include #include "mib-exports.h" /** * \defgroup prtssocookie PRT SSO Cookie * \brief PRT SSO Cookie (MX-OAPXBC OAuth2 extension) * \addtogroup prtssocookie * @{ */ G_BEGIN_DECLS #ifndef DOXYGEN #define MIB_TYPE_PRT_SSO_COOKIE mib_prt_sso_cookie_get_type() G_DECLARE_FINAL_TYPE(MIBPrtSsoCookie, mib_prt_sso_cookie, MIB, PRT_SSO_COOKIE, GObject) #else typedef void* MIBPrtSsoCookie; #endif PUBLIC_API const gchar *mib_prt_sso_cookie_get_name(MIBPrtSsoCookie *self); PUBLIC_API const gchar *mib_prt_sso_cookie_get_content(MIBPrtSsoCookie *self); G_END_DECLS /** @} */ sso-mib-0.9.0/include/mib-prt.h000066400000000000000000000020331517711616000162420ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if !defined(_SSO_MIB_INSIDE_) && !defined(SSO_MIB_COMPILATION) #error "Only can be included directly." #endif #include #include "mib-exports.h" #include "mib-pop-params.h" /** * \defgroup prt Primary Refresh Token * \brief Primary Refresh Token * \addtogroup prt * @{ */ G_BEGIN_DECLS #ifndef DOXYGEN #define MIB_TYPE_PRT mib_prt_get_type() G_DECLARE_FINAL_TYPE(MIBPrt, mib_prt, MIB, PRT, GObject) #else typedef void* MIBPrt; #endif PUBLIC_API const gchar *mib_prt_get_access_token(MIBPrt *self); PUBLIC_API enum MIB_AUTH_SCHEME mib_prt_get_access_token_type(MIBPrt *self); PUBLIC_API MIBAccount *mib_prt_get_account(MIBPrt *self); PUBLIC_API const gchar *mib_prt_get_client_info(MIBPrt *self); PUBLIC_API time_t mib_prt_get_expires_on(MIBPrt *self); PUBLIC_API gchar *const *mib_prt_get_granted_scopes(MIBPrt *self); PUBLIC_API const gchar *mib_prt_get_id_token(MIBPrt *self); G_END_DECLS /** @} */ sso-mib-0.9.0/include/sso-mib.h000066400000000000000000000004461517711616000162470ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #define _SSO_MIB_INSIDE_ #include "mib-exports.h" #include "mib-account.h" #include "mib-client-app.h" #include "mib-pop-params.h" #include "mib-prt-sso-cookie.h" #include "mib-prt.h" sso-mib-0.9.0/meson.build000066400000000000000000000065311517711616000152450ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2024 Siemens AG # SPDX-License-Identifier: LGPL-2.1-only project( 'sso-mib', 'c', version : '0.9.0', default_options : ['c_std=gnu11', 'warning_level=3'], license : 'GPL-2.0+ OR LGPL-2.1+ OR MIT', license_files : [ 'LICENSES/GPL-2.0-only.txt', 'LICENSES/LGPL-2.1-only.txt', 'LICENSES/MIT.txt' ] ) project_description = 'Library to interact with the Microsoft Device Broker for SSO' add_project_arguments('-Wno-unused-parameter', language : 'c') libsso_mib_hdrs = [ 'include/sso-mib.h', 'include/mib-account.h', 'include/mib-client-app.h', 'include/mib-exports.h', 'include/mib-prt-sso-cookie.h', 'include/mib-prt.h', 'include/mib-pop-params.h' ] libsso_mib_src = [ 'src/mib-utils.h', 'src/mib-utils.c', 'src/mib-account-impl.h', 'src/mib-account.c', 'src/mib-client-app.c', 'src/mib-client-app-impl.h', 'src/mib-pop-params.c', 'src/mib-pop-params-impl.h', 'src/mib-prt-sso-cookie-impl.h', 'src/mib-prt-sso-cookie.c', 'src/mib-prt.c', ] public_headers = include_directories('include') gnome = import('gnome') glibdep = dependency('glib-2.0') giodep = dependency('gio-2.0') jsondep = dependency('json-glib-1.0') uuiddep = dependency('uuid') jwtdep = dependency('libjwt', required: get_option('libjwt')) summary({'libjwt (sso-mib-tool)': jwtdep.found()}, bool_yn: true, section: 'Misc dependencies') identity_broker = gnome.gdbus_codegen('identity-broker', sources: 'dbus/spec/com.microsoft.identity.broker1.xml', interface_prefix : 'com.microsoft.', namespace : 'mib_dbus', ) identity_broker_obj = static_library( 'identity_broker_obj', identity_broker, c_args : ['-Wno-pedantic'], gnu_symbol_visibility : 'hidden', dependencies : [giodep], install : false) libsso_mib = shared_library( meson.project_name(), libsso_mib_src, identity_broker[1], install : true, c_args : ['-DBUILDING_SSO_MIB=1', '-DSSO_MIB_COMPILATION=1', '-DG_LOG_DOMAIN="ssomib"'], gnu_symbol_visibility : 'hidden', include_directories : public_headers, dependencies : [giodep, glibdep, jsondep, uuiddep], link_with : [identity_broker_obj], version : meson.project_version(), soversion : '0', ) install_headers(libsso_mib_hdrs, subdir : meson.project_name()) pkg_mod = import('pkgconfig') pkg_mod.generate( name : meson.project_name(), filebase : meson.project_name(), description : project_description, libraries : libsso_mib, requires: ['glib-2.0', 'gio-2.0', 'uuid'] ) sso_mib_tool_cargs_extra = [] if jwtdep.found() jwtdep_version = jwtdep.version().split('.') sso_mib_tool_cargs_extra += [ '-DWITH_LIBJWT', '-DLIBJWT_VERSION_MAJOR=' + jwtdep_version[0], '-DLIBJWT_VERSION_MINOR=' + jwtdep_version[1], ] endif sso_mib_tool = executable( 'sso-mib-tool', [ 'src/sso-mib-tool.c', ], install : true, include_directories : public_headers, link_with : [libsso_mib], c_args: sso_mib_tool_cargs_extra, dependencies: [glibdep, giodep, jsondep, uuiddep, jwtdep], install_tag : 'tool' ) gch_smtp_office365 = executable( 'sso-mib-gch-smtp-o365', 'examples/smtp-o365/main.c', install : true, include_directories : public_headers, link_with : [libsso_mib], dependencies: [glibdep, giodep], install_tag : 'git-cred-helper' ) if get_option('documentation') subdir('docs') endif if get_option('examples') subdir('examples') endif sso-mib-0.9.0/meson_options.txt000066400000000000000000000007161517711616000165370ustar00rootroot00000000000000# SPDX-FileCopyrightText: (C) 2025 Siemens AG # SPDX-License-Identifier: LGPL-2.1-only option('documentation', type: 'boolean', value: false, description: 'Build the documentation [default=false]') option('examples', type: 'boolean', value: false, description: 'Build the examples [default=false]') option('libjwt', description: 'Enable code that depends on libjwt', type: 'feature', value: 'auto') sso-mib-0.9.0/src/000077500000000000000000000000001517711616000136655ustar00rootroot00000000000000sso-mib-0.9.0/src/mib-account-impl.h000066400000000000000000000005271517711616000172020ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #include #include #include "mib-account.h" #include "mib-client-app.h" MIBAccount *mib_account_from_json(JsonObject *account_json); JsonObject *mib_account_to_json(const MIBAccount *account); sso-mib-0.9.0/src/mib-account.c000066400000000000000000000131131517711616000162310ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "mib-utils.h" #include "mib-account.h" struct _MIBAccount { GObject parent_instance; gchar *client_info; gchar *environment; gchar *family_name; gchar *given_name; gchar *home_account_id; gchar *local_account_id; gchar *name; time_t password_expiry; uuid_t realm; gchar *username; }; G_DEFINE_TYPE(MIBAccount, mib_account, G_TYPE_OBJECT) static void mib_account_finalize(GObject *gobject) { MIBAccount *self = MIB_ACCOUNT(gobject); g_clear_pointer(&self->client_info, g_free); g_clear_pointer(&self->environment, g_free); g_clear_pointer(&self->family_name, g_free); g_clear_pointer(&self->given_name, g_free); g_clear_pointer(&self->home_account_id, g_free); g_clear_pointer(&self->local_account_id, g_free); g_clear_pointer(&self->name, g_free); g_clear_pointer(&self->username, g_free); G_OBJECT_CLASS(mib_account_parent_class)->finalize(gobject); } static void mib_account_class_init(MIBAccountClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->finalize = mib_account_finalize; } static void mib_account_init(MIB_ARG_UNUSED MIBAccount *self) { } MIBAccount *mib_account_from_json(JsonObject *account_json) { const char *members[] = { "environment", "givenName", "homeAccountId", "localAccountId", "name", "passwordExpiry", "realm", "username" }; int ret = 0; for (size_t i = 0; i < sizeof(members) / sizeof(members[0]); i++) { if (!json_object_has_member(account_json, members[i])) return NULL; } MIBAccount *account = g_object_new(MIB_TYPE_ACCOUNT, NULL); account->environment = g_strdup(json_object_get_string_member(account_json, "environment")); account->given_name = g_strdup(json_object_get_string_member(account_json, "givenName")); account->home_account_id = g_strdup(json_object_get_string_member(account_json, "homeAccountId")); account->local_account_id = g_strdup(json_object_get_string_member(account_json, "localAccountId")); account->name = g_strdup(json_object_get_string_member(account_json, "name")); account->password_expiry = json_object_get_int_member(account_json, "passwordExpiry"); ret = uuid_parse(json_object_get_string_member(account_json, "realm"), account->realm); if (ret < 0) { g_object_unref(account); return NULL; } account->username = g_strdup(json_object_get_string_member(account_json, "username")); // optional fields if (json_object_has_member(account_json, "familyName")) { account->family_name = g_strdup(json_object_get_string_member(account_json, "familyName")); } if (json_object_has_member(account_json, "clientInfo")) { account->client_info = g_strdup(json_object_get_string_member(account_json, "clientInfo")); } return account; } JsonObject *mib_account_to_json(const MIBAccount *account) { JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); if (account->client_info) { json_builder_set_member_name(builder, "clientInfo"); json_builder_add_string_value(builder, account->client_info); } json_builder_set_member_name(builder, "environment"); json_builder_add_string_value(builder, account->environment); if (account->family_name) { json_builder_set_member_name(builder, "familyName"); json_builder_add_string_value(builder, account->family_name); } json_builder_set_member_name(builder, "givenName"); json_builder_add_string_value(builder, account->given_name); json_builder_set_member_name(builder, "homeAccountId"); json_builder_add_string_value(builder, account->home_account_id); json_builder_set_member_name(builder, "localAccountId"); json_builder_add_string_value(builder, account->local_account_id); json_builder_set_member_name(builder, "name"); json_builder_add_string_value(builder, account->name); json_builder_set_member_name(builder, "passwordExpiry"); json_builder_add_int_value(builder, account->password_expiry); gchar realm_str[UUID_STR_LEN]; uuid_unparse_lower(account->realm, realm_str); json_builder_set_member_name(builder, "realm"); json_builder_add_string_value(builder, realm_str); json_builder_set_member_name(builder, "username"); json_builder_add_string_value(builder, account->username); json_builder_end_object(builder); JsonNode *root = json_builder_get_root(builder); JsonObject *account_json = json_node_get_object(root); json_object_ref(account_json); json_node_unref(root); g_object_unref(builder); return account_json; } const gchar *mib_account_get_client_info(MIBAccount *account) { g_assert(account); return account->client_info; } const gchar *mib_account_get_environment(MIBAccount *account) { g_assert(account); return account->environment; } const gchar *mib_account_get_family_name(MIBAccount *account) { g_assert(account); return account->family_name; } const gchar *mib_account_get_given_name(MIBAccount *account) { g_assert(account); return account->given_name; } const gchar *mib_account_get_home_account_id(MIBAccount *account) { g_assert(account); return account->home_account_id; } const gchar *mib_account_get_local_account_id(MIBAccount *account) { g_assert(account); return account->local_account_id; } const gchar *mib_account_get_name(MIBAccount *account) { g_assert(account); return account->name; } const gchar *mib_account_get_username(MIBAccount *account) { g_assert(account); return account->username; } time_t mib_account_get_password_expiry(MIBAccount *account) { g_assert(account); return account->password_expiry; } void mib_account_get_realm(MIBAccount *account, uuid_t realm) { g_assert(account && realm); memcpy(realm, account->realm, sizeof(uuid_t)); } sso-mib-0.9.0/src/mib-client-app-impl.h000066400000000000000000000005121517711616000175740ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #include #include "identity-broker.h" #include "mib-client-app.h" GCancellable *mib_client_app_get_cancellable(MIBClientApp *self); mibdbusIdentityBroker1 *mib_client_app_get_broker(MIBClientApp *self); sso-mib-0.9.0/src/mib-client-app.c000066400000000000000000000625141517711616000166420ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "identity-broker.h" #include "mib-account-impl.h" #include "mib-client-app-impl.h" #include "mib-pop-params-impl.h" #include "mib-prt-impl.h" #include "mib-prt-sso-cookie-impl.h" #include "mib-utils.h" #define DBUS_BROKER_NAME "com.microsoft.identity.broker1" #define DBUS_BROKER_PATH "/com/microsoft/identity/broker1" // according to https://msal-python.readthedocs.io/en/latest/#publicclientapplication #define MIB_MS_BROKER_REDIRECT_URI \ "https://login.microsoftonline.com/common/oauth2/nativeclient" // MSAL does not define any lower-bound (yet) #define MIB_REQUIRED_BROKER_PROTOCOL_VERSION "0.0" /* * Values from MSAL runtime (internal interface) */ enum AuthorizationType { AT_NONE = 0, AT_CACHED_REFRESH_TOKEN = 1, AT_IMPORTED_REFRESH_TOKEN = 2, AT_USERNAME_PASSWORD = 3, AT_WINDOWS_INTEGRATED_AUTH = 4, AT_AUTH_CODE = 5, AT_INTERACTIVE = 6, AT_CERTIFICATE = 7, AT_PRT_SSO_COOKIE = 8, AT_COMPLETE_BROKER_RESULT = 9, AT_DEVICE_INFO_REQUEST = 10, AT_SIGN_OUT_INTERACTIVE = 11, AT_SIGN_OUT_SILENT = 12, AT_ACCOUNT_TRANSFER = 13 }; struct _MIBClientApp { GObject parent_instance; gchar client_id[UUID_STR_LEN]; gchar correlation_id[UUID_STR_LEN]; gchar *authority; gchar *redirect_uri; mibdbusIdentityBroker1 *broker; GCancellable *cancellable; int log_level; /* enforce an interactive login on acquireTokenInteractive */ char enforce_interactive; }; G_DEFINE_TYPE(MIBClientApp, mib_client_app, G_TYPE_OBJECT) static void mib_client_app_finalize(GObject *gobject) { MIBClientApp *priv = MIB_CLIENT_APP(gobject); g_clear_object(&priv->cancellable); g_clear_object(&priv->broker); g_clear_pointer(&priv->authority, g_free); g_clear_pointer(&priv->redirect_uri, g_free); G_OBJECT_CLASS(mib_client_app_parent_class)->finalize(gobject); } static void mib_client_app_class_init(MIBClientAppClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->finalize = mib_client_app_finalize; } static void mib_client_app_init(MIBClientApp *self) { const gchar *loglevel = g_getenv("MIB_LOG_LEVEL"); if (loglevel) { self->log_level = atoi(loglevel); } } MIBClientApp *mib_public_client_app_new(const gchar *client_id, const gchar *authority, GCancellable *cancellable, GError **error) { uuid_t correlation_id; g_assert(client_id); g_assert(authority); uuid_t client_uuid; if (uuid_parse(client_id, client_uuid) != 0) { g_warning("client id is not a UUID\n"); return NULL; } MIBClientApp *self = g_object_new(MIB_TYPE_CLIENT_APP, NULL); uuid_unparse_lower(client_uuid, self->client_id); uuid_generate_random(correlation_id); uuid_unparse_lower(correlation_id, self->correlation_id); self->authority = g_strdup(authority); self->redirect_uri = mib_client_app_get_broker_redirect_uri(self); if (cancellable) { self->cancellable = g_object_ref(cancellable); } self->broker = mib_dbus_identity_broker1_proxy_new_for_bus_sync( G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, DBUS_BROKER_NAME, DBUS_BROKER_PATH, self->cancellable, error); if (!self->broker) { if (error && *error) g_dbus_error_strip_remote_error(*error); g_prefix_error(error, "Failed to create broker proxy: "); g_clear_object(&self); } return self; } static gchar *mib_prompt_to_str(enum MIB_PROMPT prompt) { /* todo: return space separated list of enabled entries */ if (prompt & MIB_PROMPT_SELECT_ACCOUNT) { return g_strdup("select_account"); } else if (prompt & MIB_PROMPT_CONSENT) { return g_strdup("consent"); } else if (prompt & MIB_PROMPT_LOGIN) { return g_strdup("login"); } else if (prompt & MIB_PROMPT_NONE) { return g_strdup("none"); } else { return g_strdup(""); } } static JsonObject *mib_client_app_get_accounts_raw(MIBClientApp *app) { GError *error = NULL; gchar *response = NULL; JsonBuilder *builder; JsonNode *root; gboolean ok; builder = json_builder_new(); json_builder_begin_object(builder); json_builder_set_member_name(builder, "clientId"); json_builder_add_string_value(builder, mib_client_app_get_client_id(app)); json_builder_set_member_name(builder, "redirectUri"); json_builder_add_string_value(builder, app->redirect_uri); json_builder_end_object(builder); root = json_builder_get_root(builder); g_object_unref(builder); JsonObject *params = json_node_get_object(root); debug_print_json_object("mib_client_app_get_accounts_raw", "request", params); gchar *data = json_object_to_string(params); json_node_unref(root); ok = mib_dbus_identity_broker1_call_get_accounts_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), data, &response, mib_client_app_get_cancellable(app), &error); g_free(data); if (!ok) { g_warning("could not get accounts: %s", error->message); g_error_free(error); return NULL; } JsonObject *accounts = json_object_from_string(response); g_free(response); if (!accounts) { g_warning("could not parse accounts response"); return NULL; } debug_print_json_object("mib_client_app_get_accounts_raw", "response", accounts); return accounts; } /** * If no upn is provided, return the first account. * On error or when the no account has a matching upn return null. */ static JsonObject *mib_client_app_get_account_by_upn_raw(MIBClientApp *app, const gchar *upn) { JsonObject *accounts = mib_client_app_get_accounts_raw(app); JsonObject *account = NULL; if (!accounts) { return NULL; } JsonArray *accounts_array = json_object_get_array_member(accounts, "accounts"); if (!accounts_array) { goto err; } for (guint i = 0; i < json_array_get_length(accounts_array); i++) { JsonObject *_account = json_array_get_object_element(accounts_array, i); if (!upn) { g_debug("no upn provided"); account = _account; break; } if (!json_object_has_member(_account, "username")) continue; const gchar *username = json_object_get_string_member(_account, "username"); if (g_strcmp0(username, upn) == 0) { g_debug("account matching UPN found"); account = _account; break; } } if (account) json_object_ref(account); err: json_object_unref(accounts); return account; } GSList *mib_client_app_get_accounts(MIBClientApp *self) { g_assert(self); JsonObject *accounts = mib_client_app_get_accounts_raw(self); if (!accounts) { return NULL; } if (!json_object_has_member(accounts, "accounts")) { json_object_unref(accounts); return NULL; } JsonArray *accounts_array = json_object_get_array_member(accounts, "accounts"); GSList *accounts_list = NULL; MIBAccount *mib_account = NULL; for (guint i = 0; i < json_array_get_length(accounts_array); i++) { JsonObject *account = json_array_get_object_element(accounts_array, i); mib_account = mib_account_from_json(account); if (!mib_account) { g_warning("error parsing account data"); break; } accounts_list = g_slist_prepend(accounts_list, mib_account); } json_object_unref(accounts); return g_slist_reverse(accounts_list); } MIBAccount *mib_client_app_get_account_by_upn(MIBClientApp *app, const gchar *upn) { g_assert(app); MIBAccount *mib_account = NULL; JsonObject *account = mib_client_app_get_account_by_upn_raw(app, upn); if (!account) { return NULL; } mib_account = mib_account_from_json(account); json_object_unref(account); return mib_account; } mibdbusIdentityBroker1 *mib_client_app_get_broker(MIBClientApp *self) { g_assert(self); return self->broker; } const gchar *mib_client_app_get_client_id(const MIBClientApp *self) { g_assert(self); return self->client_id; } const gchar *mib_client_app_get_correlation_id(const MIBClientApp *self) { g_assert(self); return self->correlation_id; } const gchar *mib_client_app_get_authority(const MIBClientApp *self) { g_assert(self); return self->authority; } GCancellable *mib_client_app_get_cancellable(MIBClientApp *self) { g_assert(self); return self->cancellable; } gchar *mib_client_app_get_broker_redirect_uri(const MIBClientApp *self) { g_assert(self); return g_strdup(MIB_MS_BROKER_REDIRECT_URI); } void mib_client_app_set_redirect_uri(MIBClientApp *self, const gchar *uri) { g_assert(self); g_assert(uri); g_free(self->redirect_uri); self->redirect_uri = g_strdup(uri); } int mib_client_app_get_enforce_interactive(const MIBClientApp *self) { g_assert(self); return (int)self->enforce_interactive; } void mib_client_app_set_enforce_interactive(MIBClientApp *self, int enforce) { g_assert(self); self->enforce_interactive = (char)enforce; } static JsonObject * mib_get_linux_broker_version_raw(MIBClientApp *app, const gchar *msal_cpp_version) { GError *error = NULL; JsonObject *params; gchar *params_data; gchar *response; gboolean ok; params = json_object_new(); json_object_set_string_member(params, "msalCppVersion", msal_cpp_version); debug_print_json_object("mib_get_linux_broker_version_raw", "request", params); params_data = json_object_to_string(params); json_object_unref(params); if (!params_data) { return NULL; } ok = mib_dbus_identity_broker1_call_get_linux_broker_version_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), params_data, &response, mib_client_app_get_cancellable(app), &error); g_free(params_data); if (!ok) { g_warning("could not get Linux broker version: %s", error->message); g_error_free(error); return NULL; } JsonObject *version = json_object_from_string(response); if (!version) goto err; debug_print_json_object("mib_get_linux_broker_version_raw", "response", version); err: g_free(response); return version; } gchar *mib_client_app_get_linux_broker_version(MIBClientApp *app, const gchar *msal_cpp_version) { g_assert(app); g_assert(msal_cpp_version); JsonObject *version_json = NULL; gchar *version = NULL; version_json = mib_get_linux_broker_version_raw(app, msal_cpp_version); if (!version_json || !json_object_has_member(version_json, "linuxBrokerVersion")) { goto err; } version = g_strdup( json_object_get_string_member(version_json, "linuxBrokerVersion")); err: if (version_json) json_object_unref(version_json); return version; } static JsonObject * prepare_prt_auth_params(MIBClientApp *app, JsonObject *account, JsonArray *scopes, const gchar *claims_challenge, JsonObject *auth_scheme, const gchar *renew_token, JsonObject *extra_params, const gchar *sso_url, enum AuthorizationType auth_type) { // { // 'accessTokenToRenew': renew_token, // 'account': account, // 'authority': context['authority'] // 'authorizationType': 8 (cookie with sso_url), 1 otherwise // 'clientId': client_id, // 'redirectUri': // '/oauth2/nativeclient', // 'requestedScopes': ["https://graph.microsoft.com/.default"], // 'username': account['username'], // 'ssoUrl': sso_url, // } JsonNode *account_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(account_node, account); JsonNode *scopes_node = json_node_new(JSON_NODE_ARRAY); json_node_set_array(scopes_node, scopes); const gchar *username = json_object_get_string_member(account, "username"); JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); if (renew_token) { json_builder_set_member_name(builder, "accessTokenToRenew"); json_builder_add_string_value(builder, renew_token); } json_builder_set_member_name(builder, "account"); json_builder_add_value(builder, account_node); json_builder_set_member_name(builder, "authority"); json_builder_add_string_value(builder, mib_client_app_get_authority(app)); json_builder_set_member_name(builder, "authorizationType"); json_builder_add_int_value(builder, auth_type); json_builder_set_member_name(builder, "clientId"); json_builder_add_string_value(builder, mib_client_app_get_client_id(app)); if (claims_challenge) { json_builder_set_member_name(builder, "decodedClaims"); json_builder_add_string_value(builder, claims_challenge); } if (auth_scheme) { JsonNode *auth_scheme_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(auth_scheme_node, auth_scheme); json_builder_set_member_name(builder, "popParams"); json_builder_add_value(builder, auth_scheme_node); } if (extra_params) { JsonNode *extra_params_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(extra_params_node, extra_params); json_builder_set_member_name( builder, "additionalQueryParametersForAuthorization"); json_builder_add_value(builder, extra_params_node); } json_builder_set_member_name(builder, "redirectUri"); json_builder_add_string_value(builder, app->redirect_uri); json_builder_set_member_name(builder, "requestedScopes"); json_builder_add_value(builder, scopes_node); json_builder_set_member_name(builder, "username"); json_builder_add_string_value(builder, username); if (sso_url) { json_builder_set_member_name(builder, "ssoUrl"); json_builder_add_string_value(builder, sso_url); } json_builder_end_object(builder); JsonNode *root = json_builder_get_root(builder); JsonObject *auth_params = json_node_get_object(root); json_object_ref(auth_params); g_object_unref(builder); json_node_unref(root); return auth_params; } static JsonObject * mib_acquire_token_silent_raw(MIBClientApp *app, JsonObject *account, JsonArray *scopes, const gchar *claims_challenge, JsonObject *auth_scheme, const gchar *renew_token) { GError *error = NULL; gchar *response; gboolean ok; JsonObject *token; JsonObject *auth_params = prepare_prt_auth_params( app, account, scopes, claims_challenge, auth_scheme, renew_token, NULL, NULL, AT_CACHED_REFRESH_TOKEN); JsonNode *auth_params_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(auth_params_node, auth_params); json_object_unref(auth_params); JsonObject *params_obj = json_object_new(); json_object_set_member(params_obj, "authParameters", auth_params_node); debug_print_json_object("mib_acquire_token_silent_raw", "request", params_obj); gchar *data = json_object_to_string(params_obj); json_object_unref(params_obj); ok = mib_dbus_identity_broker1_call_acquire_token_silently_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), data, &response, mib_client_app_get_cancellable(app), &error); g_free(data); if (!ok) { g_warning("could not acquire token: %s", error->message); g_error_free(error); return NULL; } token = json_object_from_string(response); g_free(response); if (!token) { g_warning("could not parse token response"); return NULL; } debug_print_json_object("mib_acquire_token_silent_raw", "response", token); return token; } MIBPrt *mib_client_app_acquire_token_silent(MIBClientApp *app, MIBAccount *account, GSList *scopes, const gchar *claims_challenge, MIBPopParams *auth_scheme, const gchar *id_token) { g_assert(app); g_assert(account); g_assert(scopes); JsonObject *account_json = mib_account_to_json(account); JsonArray *scopes_array = mib_scopes_to_json(scopes); JsonObject *pop_params = auth_scheme ? mib_pop_params_to_json(auth_scheme) : NULL; JsonObject *token_json = mib_acquire_token_silent_raw(app, account_json, scopes_array, claims_challenge, pop_params, id_token); json_object_unref(account_json); json_array_unref(scopes_array); if (pop_params) { json_object_unref(pop_params); } if (!token_json) { return NULL; } MIBPrt *token = mib_prt_from_json(token_json, account); json_object_unref(token_json); return token; } static JsonObject *mib_acquire_token_interactive_raw( MIBClientApp *app, JsonArray *scopes, enum MIB_PROMPT prompt, JsonObject *account, MIB_ARG_UNUSED const gchar *domain_hint, const gchar *claims_challenge, JsonObject *auth_scheme, JsonObject *extra_params) { GError *error = NULL; gchar *response; gboolean ok; JsonObject *token; JsonObject *auth_params = prepare_prt_auth_params( app, account, scopes, claims_challenge, auth_scheme, NULL, extra_params, NULL, AT_INTERACTIVE); /* TODO: check if this is the correct key */ if (prompt != MIB_PROMPT_UNSET) { gchar *prompt_str = mib_prompt_to_str(prompt); json_object_set_string_member(auth_params, "prompt", prompt_str); g_free(prompt_str); } JsonNode *auth_params_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(auth_params_node, auth_params); JsonObject *params_obj = json_object_new(); /* if a re-auth is requested, clear the account */ if (prompt & MIB_PROMPT_SELECT_ACCOUNT) { json_object_remove_member(auth_params, "account"); json_object_remove_member(auth_params, "username"); } json_object_unref(auth_params); json_object_set_member(params_obj, "authParameters", auth_params_node); debug_print_json_object("mib_acquire_token_interactive_raw", "request", params_obj); gchar *data = json_object_to_string(params_obj); json_object_unref(params_obj); /* disable dbus timeout before call and restore after as user input is needed */ mibdbusIdentityBroker1 *gd_proxy = mib_client_app_get_broker(app); g_dbus_proxy_set_default_timeout((GDBusProxy *)gd_proxy, G_MAXINT); ok = mib_dbus_identity_broker1_call_acquire_token_interactively_sync( gd_proxy, MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), data, &response, mib_client_app_get_cancellable(app), &error); g_dbus_proxy_set_default_timeout((GDBusProxy *)gd_proxy, -1); g_free(data); if (!ok) { g_warning("could not acquire token: %s", error->message); g_error_free(error); return NULL; } token = json_object_from_string(response); g_free(response); if (!token) { g_warning("could not parse token response"); return NULL; } debug_print_json_object("mib_acquire_token_interactive_raw", "response", token); return token; } MIBPrt *mib_client_app_acquire_token_interactive( MIBClientApp *app, GSList *scopes, enum MIB_PROMPT prompt, const gchar *login_hint, const gchar *domain_hint, const gchar *claims_challenge, MIBPopParams *auth_scheme) { g_assert(app); g_assert(scopes); MIBPrt *token = NULL; JsonObject *token_json = NULL; JsonObject *account_json = mib_client_app_get_account_by_upn_raw(app, login_hint); if (!account_json) { return NULL; } MIBAccount *fallback_account = mib_account_from_json(account_json); JsonArray *scopes_array = mib_scopes_to_json(scopes); JsonObject *pop_params = auth_scheme ? mib_pop_params_to_json(auth_scheme) : NULL; /* first try silent, on error try interactive */ if (!mib_client_app_get_enforce_interactive(app)) { token_json = mib_acquire_token_silent_raw(app, account_json, scopes_array, claims_challenge, pop_params, NULL); } if (token_json) { token = mib_prt_from_json(token_json, fallback_account); json_object_unref(token_json); } if (!token) { token_json = mib_acquire_token_interactive_raw( app, scopes_array, prompt, account_json, domain_hint, claims_challenge, pop_params, NULL); if (token_json) { token = mib_prt_from_json(token_json, fallback_account); json_object_unref(token_json); } } json_object_unref(account_json); json_array_unref(scopes_array); if (pop_params) { json_object_unref(pop_params); } g_clear_object(&fallback_account); return token; } static JsonObject *prepare_prt_sso_request_data(JsonObject *account, JsonObject *auth_params, const gchar *sso_url) { // { // 'account': account, // 'authParameters': params, // 'ssoUrl': sso_url // } JsonObject *params_obj = json_object_new(); JsonNode *account_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(account_node, account); JsonNode *auth_params_node = json_node_new(JSON_NODE_OBJECT); json_node_set_object(auth_params_node, auth_params); JsonNode *sso_url_node = json_node_new(JSON_NODE_VALUE); json_node_set_string(sso_url_node, sso_url); json_object_set_member(params_obj, "account", account_node); json_object_set_member(params_obj, "authParameters", auth_params_node); json_object_set_member(params_obj, "ssoUrl", sso_url_node); return params_obj; } static JsonObject *mib_acquire_prt_sso_cookie_raw(MIBClientApp *app, JsonObject *account, const gchar *sso_url, JsonArray *scopes) { JsonObject *cookie; gchar *data; GError *error = NULL; gchar *response; gboolean ok; JsonObject *auth_params = prepare_prt_auth_params(app, account, scopes, NULL, NULL, NULL, NULL, sso_url, AT_PRT_SSO_COOKIE); JsonObject *params = prepare_prt_sso_request_data(account, auth_params, sso_url); debug_print_json_object("mib_acquire_prt_sso_cookie_raw", "request", params); data = json_object_to_string(params); json_object_unref(params); json_object_unref(auth_params); ok = mib_dbus_identity_broker1_call_acquire_prt_sso_cookie_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), data, &response, mib_client_app_get_cancellable(app), &error); g_free(data); if (!ok) { g_warning("could not acquire PRT SSO cookie: %s", error->message); g_error_free(error); return NULL; } cookie = json_object_from_string(response); g_free(response); if (!cookie) { g_warning("could not parse PRT SSO cookie response"); return NULL; } debug_print_json_object("mib_acquire_prt_sso_cookie_raw", "response", cookie); return cookie; } MIBPrtSsoCookie *mib_client_app_acquire_prt_sso_cookie(MIBClientApp *app, MIBAccount *account, const gchar *sso_url, GSList *scopes) { g_assert(app); g_assert(account); g_assert(sso_url); g_assert(scopes); JsonObject *account_json = mib_account_to_json(account); JsonArray *scopes_array = mib_scopes_to_json(scopes); JsonObject *cookie_json = mib_acquire_prt_sso_cookie_raw( app, account_json, sso_url, scopes_array); json_object_unref(account_json); json_array_unref(scopes_array); if (!cookie_json) { return NULL; } MIBPrtSsoCookie *cookie = mib_prt_sso_cookie_from_json(cookie_json); json_object_unref(cookie_json); return cookie; } static JsonObject *mib_generate_signed_http_request_raw(MIBClientApp *app, JsonObject *pop_params) { GError *error = NULL; gboolean ok; gchar *response; JsonObject *params = json_object_new(); json_object_set_string_member(params, "clientId", mib_client_app_get_client_id(app)); json_object_ref(pop_params); json_object_set_object_member(params, "popParams", pop_params); debug_print_json_object("mib_generate_signed_http_request_raw", "request", params); gchar *params_data = json_object_to_string(params); json_object_unref(params); ok = mib_dbus_identity_broker1_call_generate_signed_http_request_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), params_data, &response, mib_client_app_get_cancellable(app), &error); g_free(params_data); if (!ok) { g_warning("could not generate signed HTTP request: %s", error->message); g_error_free(error); return NULL; } JsonObject *token = json_object_from_string(response); g_free(response); if (!token) { g_warning("could not parse signed HTTP request response"); return NULL; } debug_print_json_object("mib_generate_signed_http_request_raw", "response", token); return token; } gchar *mib_client_app_generate_signed_http_request(MIBClientApp *app, MIBAccount *account, MIBPopParams *pop_params) { JsonObject *params_json; gchar *access_token = NULL; const gchar *account_id = NULL; g_assert(app); g_assert(account); if (pop_params) { params_json = mib_pop_params_to_json(pop_params); } else { params_json = json_object_new(); } account_id = mib_account_get_home_account_id(account); json_object_set_string_member(params_json, "homeAccountId", account_id); JsonObject *token = mib_generate_signed_http_request_raw(app, params_json); json_object_unref(params_json); if (!token) { return NULL; } if (!json_object_has_member(token, "signedHttpRequest")) { g_warning("response json is missing 'signedHttpRequest'"); goto err; } access_token = g_strdup(json_object_get_string_member(token, "signedHttpRequest")); err: json_object_unref(token); return access_token; } static int mib_remove_account_raw(MIBClientApp *app, JsonObject *account) { GError *error = NULL; gboolean ok; gchar *response = NULL; JsonObject *params = json_object_new(); json_object_set_string_member(params, "clientId", app->client_id); json_object_set_object_member(params, "account", json_object_ref(account)); debug_print_json_object("mib_remove_account_raw", "request", params); gchar *data = json_object_to_string(params); json_object_unref(params); ok = mib_dbus_identity_broker1_call_remove_account_sync( mib_client_app_get_broker(app), MIB_REQUIRED_BROKER_PROTOCOL_VERSION, mib_client_app_get_correlation_id(app), data, &response, mib_client_app_get_cancellable(app), &error); g_free(data); if (!ok) { g_warning("could not remove account: %s", error->message); g_error_free(error); return -1; } JsonObject *resp_json = json_object_from_string(response); g_free(response); debug_print_json_object("mib_remove_account_raw", "response", resp_json); if (resp_json) json_object_unref(resp_json); return 0; } int mib_client_app_remove_account(MIBClientApp *app, MIBAccount *account) { g_assert(app); g_assert(account); int ret = 0; JsonObject *account_json = mib_account_to_json(account); ret = mib_remove_account_raw(app, account_json); json_object_unref(account_json); return ret; } sso-mib-0.9.0/src/mib-pop-params-impl.h000066400000000000000000000003421517711616000176200ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #include #include "mib-pop-params.h" JsonObject *mib_pop_params_to_json(MIBPopParams *self); sso-mib-0.9.0/src/mib-pop-params.c000066400000000000000000000060651517711616000166640ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "mib-utils.h" #include "mib-pop-params.h" struct _MIBPopParams { GObject parent_instance; enum MIB_AUTH_SCHEME auth_scheme; enum MIB_REQUEST_METHOD resource_req_method; gchar *resource_req_uri; gchar *shr_claims; gchar *shr_nonce; gchar *kid; }; G_DEFINE_TYPE(MIBPopParams, mib_pop_params, G_TYPE_OBJECT) static void mib_pop_params_finalize(GObject *gobject) { MIBPopParams *priv = MIB_POP_PARAMS(gobject); g_clear_pointer(&priv->resource_req_uri, g_free); g_clear_pointer(&priv->shr_claims, g_free); g_clear_pointer(&priv->shr_nonce, g_free); g_clear_pointer(&priv->kid, g_free); G_OBJECT_CLASS(mib_pop_params_parent_class)->finalize(gobject); } static void mib_pop_params_class_init(MIBPopParamsClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->finalize = mib_pop_params_finalize; } static void mib_pop_params_init(MIBPopParams *self) { self->auth_scheme = MIB_AUTH_SCHEME_BEARER; self->resource_req_method = MIB_REQUEST_METHOD_POST; } MIBPopParams *mib_pop_params_new(enum MIB_AUTH_SCHEME auth_scheme, enum MIB_REQUEST_METHOD method, const gchar *uri) { g_assert(uri); MIBPopParams *self = g_object_new(MIB_TYPE_POP_PARAMS, NULL); self->auth_scheme = auth_scheme; self->resource_req_method = method; self->resource_req_uri = g_strdup(uri); return self; } JsonObject *mib_pop_params_to_json(MIBPopParams *self) { const char *auth_scheme_str; const char *req_method_str; if (self->auth_scheme == MIB_AUTH_SCHEME_POP) { auth_scheme_str = "pop"; } else { auth_scheme_str = "bearer"; } if (self->resource_req_method == MIB_REQUEST_METHOD_GET) { req_method_str = "GET"; } else if (self->resource_req_method == MIB_REQUEST_METHOD_PUT) { req_method_str = "PUT"; } else { req_method_str = "POST"; } JsonObject *params_json = json_object_new(); json_object_set_string_member(params_json, "authenticationScheme", auth_scheme_str); /* TODO: to clarify how to split URI into host an path */ json_object_set_string_member(params_json, "uriHost", self->resource_req_uri); json_object_set_string_member(params_json, "httpMethod", req_method_str); /* optional parameters */ if (self->shr_claims) { json_object_set_string_member(params_json, "clientClaims", self->shr_claims); } if (self->shr_nonce) { json_object_set_string_member(params_json, "nonce", self->shr_nonce); } if (self->kid) { json_object_set_string_member(params_json, "kid", self->kid); } return params_json; } void mib_pop_params_set_shr_claims(MIBPopParams *self, const gchar *claims) { g_assert(self); g_assert(claims); g_free(self->shr_claims); self->shr_claims = g_strdup(claims); } void mib_pop_params_set_shr_nonce(MIBPopParams *self, const gchar *nonce) { g_assert(self); g_assert(nonce); g_free(self->shr_nonce); self->shr_nonce = g_strdup(nonce); } void mib_pop_params_set_kid(MIBPopParams *self, const gchar *kid) { g_assert(self); g_assert(kid); g_free(self->kid); self->kid = g_strdup(kid); } sso-mib-0.9.0/src/mib-prt-impl.h000066400000000000000000000004151517711616000163470ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #include #include "mib-prt.h" #include "mib-account.h" MIBPrt *mib_prt_from_json(JsonObject *token_json, MIBAccount *fallback_account); sso-mib-0.9.0/src/mib-prt-sso-cookie-impl.h000066400000000000000000000003661517711616000204250ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #include #include "mib-prt-sso-cookie.h" MIBPrtSsoCookie *mib_prt_sso_cookie_from_json(JsonObject *cookie_json); sso-mib-0.9.0/src/mib-prt-sso-cookie.c000066400000000000000000000037651517711616000174670ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "mib-utils.h" #include "mib-prt-sso-cookie-impl.h" /** * \brief Parsed PRT SSO cookie */ struct _MIBPrtSsoCookie { GObject parent_instance; gchar *name; gchar *content; }; G_DEFINE_TYPE(MIBPrtSsoCookie, mib_prt_sso_cookie, G_TYPE_OBJECT) static void mib_prt_sso_cookie_finalize(GObject *gobject) { MIBPrtSsoCookie *priv = MIB_PRT_SSO_COOKIE(gobject); g_clear_pointer(&priv->name, g_free); g_clear_pointer(&priv->content, g_free); G_OBJECT_CLASS(mib_prt_sso_cookie_parent_class)->finalize(gobject); } static void mib_prt_sso_cookie_class_init(MIBPrtSsoCookieClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->finalize = mib_prt_sso_cookie_finalize; } static void mib_prt_sso_cookie_init(MIB_ARG_UNUSED MIBPrtSsoCookie *self) { } MIBPrtSsoCookie *mib_prt_sso_cookie_from_json(JsonObject *cookie_json) { MIBPrtSsoCookie *cookie; /* microsoft-identity-broker > 2.0.1 */ if (json_object_has_member(cookie_json, "cookieItems")) { JsonArray *cookie_items = json_object_get_array_member(cookie_json, "cookieItems"); if (!cookie_items || !json_array_get_length(cookie_items)) { return NULL; } JsonObject *cookie_json_inner = json_array_get_object_element(cookie_items, 0); return mib_prt_sso_cookie_from_json(cookie_json_inner); } if (!json_object_has_member(cookie_json, "cookieName") || !json_object_has_member(cookie_json, "cookieContent")) { g_warning("invalid cookie data"); return NULL; } cookie = g_object_new(MIB_TYPE_PRT_SSO_COOKIE, NULL); cookie->name = g_strdup(json_object_get_string_member(cookie_json, "cookieName")); cookie->content = g_strdup(json_object_get_string_member(cookie_json, "cookieContent")); return cookie; } const gchar *mib_prt_sso_cookie_get_name(MIBPrtSsoCookie *self) { g_assert(self); return self->name; } const gchar *mib_prt_sso_cookie_get_content(MIBPrtSsoCookie *self) { g_assert(self); return self->content; } sso-mib-0.9.0/src/mib-prt.c000066400000000000000000000073631517711616000154140ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "mib-utils.h" #include "mib-account.h" #include "mib-account-impl.h" struct _MIBPrt { GObject parent_instance; gchar *access_token; enum MIB_AUTH_SCHEME access_token_type; MIBAccount *account; gchar *client_info; /// Expiry time in seconds since epoch time_t expires_on; /// Allocated array of strings, null terminated gchar **granted_scopes; gchar *id_token; }; G_DEFINE_TYPE(MIBPrt, mib_prt, G_TYPE_OBJECT) static void mib_prt_finalize(GObject *gobject) { MIBPrt *self = MIB_PRT(gobject); g_clear_pointer(&self->access_token, g_free); g_clear_object(&self->account); g_clear_pointer(&self->client_info, g_free); g_clear_pointer(&self->granted_scopes, g_strfreev); g_clear_pointer(&self->id_token, g_free); G_OBJECT_CLASS(mib_prt_parent_class)->finalize(gobject); } static void mib_prt_class_init(MIBPrtClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS(klass); object_class->finalize = mib_prt_finalize; } static void mib_prt_init(MIB_ARG_UNUSED MIBPrt *self) { } /* Convert undocumented external token number to our types */ static int mib_prt_token_type_from_ext(int ext_token_type) { switch (ext_token_type) { case 0: return MIB_AUTH_SCHEME_BEARER; case 1: return MIB_AUTH_SCHEME_POP; default: g_warning("unknown token type %d\n", ext_token_type); } return MIB_AUTH_SCHEME_BEARER; } MIBPrt *mib_prt_from_json(JsonObject *token_json, MIBAccount *fallback_account) { MIBAccount *account = NULL; MIBPrt *token = NULL; const char *members[] = { "accessToken", "accessTokenType", "clientInfo", "expiresOn", "idToken", "grantedScopes" }; if (!json_object_has_member(token_json, "brokerTokenResponse")) return NULL; JsonObject *broker_resp = json_object_get_object_member(token_json, "brokerTokenResponse"); for (size_t i = 0; i < sizeof(members) / sizeof(members[0]); i++) { if (!json_object_has_member(broker_resp, members[i])) return NULL; } token = g_object_new(MIB_TYPE_PRT, NULL); token->access_token = g_strdup(json_object_get_string_member(broker_resp, "accessToken")); token->access_token_type = mib_prt_token_type_from_ext( json_object_get_int_member(broker_resp, "accessTokenType")); if (json_object_has_member(broker_resp, "account")) { JsonObject *account_json = json_object_get_object_member(broker_resp, "account"); account = mib_account_from_json(account_json); } if (!account && fallback_account) account = g_object_ref(fallback_account); if (!account) { g_warning("account data is not valid"); g_object_unref(token); return NULL; } token->account = account; token->client_info = g_strdup(json_object_get_string_member(broker_resp, "clientInfo")); token->expires_on = json_object_get_int_member(broker_resp, "expiresOn") / 1000; token->id_token = g_strdup(json_object_get_string_member(broker_resp, "idToken")); const gchar *granted_scopes = json_object_get_string_member(broker_resp, "grantedScopes"); token->granted_scopes = g_strsplit(granted_scopes, " ", -1); return token; } const gchar *mib_prt_get_access_token(MIBPrt *self) { g_assert(self); return self->access_token; } enum MIB_AUTH_SCHEME mib_prt_get_access_token_type(MIBPrt *self) { g_assert(self); return self->access_token_type; } MIBAccount *mib_prt_get_account(MIBPrt *self) { g_assert(self); return self->account; } const gchar *mib_prt_get_client_info(MIBPrt *self) { g_assert(self); return self->client_info; } time_t mib_prt_get_expires_on(MIBPrt *self) { g_assert(self); return self->expires_on; } gchar *const *mib_prt_get_granted_scopes(MIBPrt *self) { g_assert(self); return self->granted_scopes; } const gchar *mib_prt_get_id_token(MIBPrt *self) { g_assert(self); return self->id_token; } sso-mib-0.9.0/src/mib-utils.c000066400000000000000000000037611517711616000157450ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #include "mib-utils.h" gchar *json_object_to_string(JsonObject *object) { JsonGenerator *gen = json_generator_new(); JsonNode *root = json_node_new(JSON_NODE_OBJECT); json_node_set_object(root, object); json_generator_set_root(gen, root); gchar *buffer = json_generator_to_data(gen, NULL); json_node_unref(root); g_object_unref(gen); return buffer; } static void print_json_object(JsonObject *object) { JsonGenerator *gen = json_generator_new(); JsonNode *root = json_node_new(JSON_NODE_OBJECT); json_node_set_object(root, object); json_generator_set_root(gen, root); json_generator_set_pretty(gen, TRUE); gchar *buffer = json_generator_to_data(gen, NULL); g_debug("%s", buffer); g_free(buffer); json_node_unref(root); g_object_unref(gen); } void debug_print_json_object(const gchar *func, const gchar *scope, JsonObject *object) { g_debug("json-object from %s,%s", func, scope); if (!object) { g_debug("(null)"); return; } print_json_object(object); } JsonObject *json_object_from_string(const gchar *data) { JsonParser *parser = json_parser_new(); JsonNode *root; GError *error = NULL; gboolean parse_ok = json_parser_load_from_data(parser, data, -1, &error); if (!parse_ok) { g_warning("could not parse JSON: %s", error->message); g_debug("data: %s", data); g_error_free(error); g_object_unref(parser); return NULL; } root = json_parser_get_root(parser); if (json_node_get_value_type(root) != JSON_TYPE_OBJECT) { g_warning("could not parse JSON: root is not an object"); g_object_unref(parser); return NULL; } JsonObject *object = json_node_get_object(root); json_object_ref(object); g_object_unref(parser); return object; } JsonArray *mib_scopes_to_json(GSList *scopes) { JsonArray *scopes_array = json_array_new(); for (GSList *iter = scopes; iter; iter = g_slist_next(iter)) { json_array_add_string_element(scopes_array, iter->data); } return scopes_array; } sso-mib-0.9.0/src/mib-utils.h000066400000000000000000000010671517711616000157470ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens * SPDX-License-Identifier: LGPL-2.1-only */ #pragma once #if (__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ > 4) #define MIB_ARG_UNUSED __attribute__((__unused__)) #else #define MIB_ARG_UNUSED #endif #include #include gchar *json_object_to_string(JsonObject *object); JsonObject *json_object_from_string(const gchar *data); void debug_print_json_object(const gchar *func, const gchar *scope, JsonObject *object); JsonArray *mib_scopes_to_json(GSList *scopes); sso-mib-0.9.0/src/sso-mib-tool.c000066400000000000000000000636171517711616000163720ustar00rootroot00000000000000/* * SPDX-FileCopyrightText: (C) 2025 Siemens AG * SPDX-License-Identifier: GPL-2.0-only */ #include #include #include #include #include #ifdef WITH_LIBJWT #include #endif #include "sso-mib.h" // Microsoft Edge on Linux ID #define CLIENT_ID_DEFAULT "d7b530a4-7680-4c23-a8bf-c52c121d2e87" // Fake MSAL CPP version #define MSAL_CPP_VERSION "1.28.0" #define FORMAT_JSON "json" #define FORMAT_TEXT "text" static GCancellable *cancellable = NULL; static void sig_handler(int signo) { if (signo == SIGINT) { if (cancellable) { const char msg[] = "Interrupted. Cancel in-flight operations.\n"; // use a dummy conditional to denote we don't care about the result if (write(STDERR_FILENO, msg, sizeof(msg) - 1)) { } g_cancellable_cancel(cancellable); } } } #ifdef WITH_LIBJWT #if LIBJWT_VERSION_MAJOR == 1 || LIBJWT_VERSION_MAJOR == 2 static int decode_headers_and_claims(const gchar *token, char **grants, char **hdrs) { jwt_t *jwt = NULL; int ret = jwt_decode(&jwt, token, NULL, 0); if (ret != 0) return ret; *hdrs = jwt_get_headers_json(jwt, NULL); *grants = jwt_get_grants_json(jwt, NULL); jwt_free(jwt); return 0; } #else struct jwt_cb_ctx { char **grants; char **hdrs; }; static int on_check_cb(jwt_t *jwt, jwt_config_t *config) { jwt_value_t header_val; jwt_value_t claims_val; struct jwt_cb_ctx *ctx = config->ctx; jwt_set_GET_JSON(&header_val, NULL); if (jwt_header_get(jwt, &header_val) == JWT_VALUE_ERR_NONE) { *ctx->hdrs = header_val.json_val; } jwt_set_GET_JSON(&claims_val, NULL); if (jwt_claim_get(jwt, &claims_val) == JWT_VALUE_ERR_NONE) *ctx->grants = claims_val.json_val; return 0; } static int decode_headers_and_claims(const gchar *token, char **grants, char **hdrs) { struct jwt_cb_ctx ctx = { .grants = grants, .hdrs = hdrs }; jwt_checker_t *checker = jwt_checker_new(); jwt_checker_setcb(checker, on_check_cb, &ctx); jwt_checker_verify(checker, token); jwt_checker_free(checker); return 0; } #endif static void print_decoded_jwt(const gchar *token) { char *grants = NULL; char *hdrs = NULL; if (decode_headers_and_claims(token, &grants, &hdrs) != 0) { g_print("Error: Failed to decode JWT\n"); return; } g_print("%s\n", hdrs); g_print("%s\n", grants); free(hdrs); free(grants); } static void json_builder_add_jwt_token(JsonBuilder *builder, const gchar *token) { char *grants = NULL; char *hdrs = NULL; if (decode_headers_and_claims(token, &grants, &hdrs) != 0) { g_print("Error: Failed to decode JWT\n"); return; } json_builder_begin_object(builder); GError *error = NULL; JsonParser *parser = json_parser_new(); if (json_parser_load_from_data(parser, hdrs, -1, &error)) { JsonNode *node = json_parser_get_root(parser); json_builder_set_member_name(builder, "headers"); JsonNode *copied = json_node_copy(node); json_builder_add_value(builder, copied); } else { g_printerr("Error parsing JSON string: %s\n", error->message); } g_clear_error(&error); if (json_parser_load_from_data(parser, grants, -1, &error)) { JsonNode *node = json_parser_get_root(parser); json_builder_set_member_name(builder, "grants"); JsonNode *copied = json_node_copy(node); json_builder_add_value(builder, copied); } else { g_printerr("Error parsing JSON string: %s\n", error->message); } g_clear_error(&error); g_object_unref(parser); free(hdrs); free(grants); json_builder_end_object(builder); } #else static void print_decoded_jwt(const gchar *token) { g_printerr("token decoding requires libjwt (dependency missing)\n"); } static void json_builder_add_jwt_token(JsonBuilder *builder, const gchar *token) { g_printerr("token decoding requires libjwt (dependency missing)\n"); } #endif static void print_json_builder(JsonBuilder *builder) { JsonGenerator *generator = json_generator_new(); JsonNode *root = json_builder_get_root(builder); json_generator_set_root(generator, root); gchar *buf = json_generator_to_data(generator, NULL); g_print("%s\n", buf); g_free(buf); json_node_free(root); g_object_unref(generator); } static void print_prt_sso_cookie(MIBPrtSsoCookie *cookie, int decode) { const gchar *name = mib_prt_sso_cookie_get_name(cookie); const gchar *content = mib_prt_sso_cookie_get_content(cookie); if (decode) { g_print("# cookie-name: %s\n", name); g_print("# cookie-content\n"); print_decoded_jwt(content); } else { g_print("cookie-name: %s\n", name); g_print("cookie-content: %s\n", content); } } static void json_print_prt_sso_cookie(MIBPrtSsoCookie *cookie, int decode) { JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); json_builder_set_member_name(builder, "cookie_name"); json_builder_add_string_value(builder, mib_prt_sso_cookie_get_name(cookie)); json_builder_set_member_name(builder, "cookie_content"); const gchar *content = mib_prt_sso_cookie_get_content(cookie); if (decode) { json_builder_add_jwt_token(builder, content); } else { json_builder_add_string_value(builder, content); } json_builder_end_object(builder); print_json_builder(builder); g_object_unref(builder); } static void print_account(MIBAccount *account, gchar *prefix) { char realm_str[UUID_STR_LEN]; uuid_t realm; mib_account_get_realm(account, realm); uuid_unparse(realm, realm_str); const gchar *client_info = mib_account_get_client_info(account); const gchar *family_name = mib_account_get_family_name(account); if (client_info) g_print("%sclient-info: %s\n", prefix, client_info); g_print("%senvironment: %s\n", prefix, mib_account_get_environment(account)); if (family_name) g_print("%sfamily-name: %s\n", prefix, family_name); g_print("%sgiven-name: %s\n", prefix, mib_account_get_given_name(account)); g_print("%shome-account-id: %s\n", prefix, mib_account_get_home_account_id(account)); g_print("%slocal-account-id: %s\n", prefix, mib_account_get_local_account_id(account)); g_print("%sname: %s\n", prefix, mib_account_get_name(account)); g_print("%spassword-expiry: %ld\n", prefix, mib_account_get_password_expiry(account)); g_print("%srealm: %s\n", prefix, realm_str); g_print("%susername: %s\n", prefix, mib_account_get_username(account)); } static void print_account_list(GSList *accounts, gchar *prefix) { int i = 0; for (GSList *iter = accounts; iter; iter = g_slist_next(iter)) { g_print("# Account %d\n", i++); MIBAccount *account = (MIBAccount *)iter->data; print_account(account, " "); } } static void json_builder_add_account(JsonBuilder *builder, MIBAccount *account) { char realm_str[UUID_STR_LEN]; uuid_t realm; mib_account_get_realm(account, realm); uuid_unparse(realm, realm_str); if (mib_account_get_client_info(account)) { json_builder_set_member_name(builder, "client_info"); json_builder_add_string_value(builder, mib_account_get_client_info(account)); } json_builder_set_member_name(builder, "environment"); json_builder_add_string_value(builder, mib_account_get_environment(account)); if (mib_account_get_family_name(account)) { json_builder_set_member_name(builder, "family_name"); json_builder_add_string_value(builder, mib_account_get_family_name(account)); } json_builder_set_member_name(builder, "given_name"); json_builder_add_string_value(builder, mib_account_get_given_name(account)); json_builder_set_member_name(builder, "home_account_id"); json_builder_add_string_value(builder, mib_account_get_home_account_id(account)); json_builder_set_member_name(builder, "local_account_id"); json_builder_add_string_value(builder, mib_account_get_local_account_id(account)); json_builder_set_member_name(builder, "name"); json_builder_add_string_value(builder, mib_account_get_name(account)); json_builder_set_member_name(builder, "password_expiry"); json_builder_add_int_value(builder, mib_account_get_password_expiry(account)); json_builder_set_member_name(builder, "realm"); json_builder_add_string_value(builder, realm_str); json_builder_set_member_name(builder, "username"); json_builder_add_string_value(builder, mib_account_get_username(account)); } static void json_print_account(MIBAccount *account) { JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); json_builder_add_account(builder, account); json_builder_end_object(builder); print_json_builder(builder); g_object_unref(builder); } static void json_print_account_list(GSList *accounts) { JsonBuilder *builder = json_builder_new(); json_builder_begin_array(builder); for (GSList *iter = accounts; iter; iter = g_slist_next(iter)) { json_builder_begin_object(builder); json_builder_add_account(builder, (MIBAccount *)iter->data); json_builder_end_object(builder); } json_builder_end_array(builder); print_json_builder(builder); g_object_unref(builder); } static const char *auth_scheme_to_str(enum MIB_AUTH_SCHEME scheme) { if (scheme == MIB_AUTH_SCHEME_POP) { return "pop"; } else { return "bearer"; } } static void print_prt_token(MIBPrt *token, int decode) { char buffer[32]; struct tm tm_info; struct timeval tv; const char *token_type = auth_scheme_to_str(mib_prt_get_access_token_type(token)); if (decode) { g_print("# access token\n"); print_decoded_jwt(mib_prt_get_access_token(token)); g_print("# id token\n"); print_decoded_jwt(mib_prt_get_id_token(token)); } else { g_print("access-token: %s\n", mib_prt_get_access_token(token)); g_print("id-token: %s\n", mib_prt_get_id_token(token)); } const gchar *p = decode ? "# " : ""; g_print("%saccess-token type: %s\n", p, token_type); g_print("%sclient-info: %s\n", p, mib_prt_get_client_info(token)); g_print("%sgranted-scopes:", p); gchar *const *scopes = mib_prt_get_granted_scopes(token); for (int i = 0; scopes[i]; i++) { g_print(" %s", scopes[i]); } g_print("\n"); tv.tv_sec = mib_prt_get_expires_on(token); localtime_r(&tv.tv_sec, &tm_info); strftime(buffer, sizeof(buffer) - 1, "%Y-%m-%d %H:%M:%S", &tm_info); g_print("%sexpires-on: %s\n", p, buffer); g_print("%saccount:\n", p); print_account(mib_prt_get_account(token), "# "); } static void json_print_prt_token(MIBPrt *token, int decode) { JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); if (decode) { json_builder_set_member_name(builder, "access_token"); json_builder_add_jwt_token(builder, mib_prt_get_access_token(token)); json_builder_set_member_name(builder, "id_token"); json_builder_add_jwt_token(builder, mib_prt_get_id_token(token)); } else { json_builder_set_member_name(builder, "access_token"); json_builder_add_string_value(builder, mib_prt_get_access_token(token)); json_builder_set_member_name(builder, "id_token"); json_builder_add_string_value(builder, mib_prt_get_id_token(token)); } json_builder_set_member_name(builder, "access_token_type"); json_builder_add_string_value( builder, auth_scheme_to_str(mib_prt_get_access_token_type(token))); json_builder_set_member_name(builder, "client_info"); json_builder_add_string_value(builder, mib_prt_get_client_info(token)); json_builder_set_member_name(builder, "granted_scopes"); gchar *const *scopes = mib_prt_get_granted_scopes(token); json_builder_begin_array(builder); for (int i = 0; scopes[i]; i++) { json_builder_add_string_value(builder, scopes[i]); } json_builder_end_array(builder); struct timeval tv; tv.tv_sec = mib_prt_get_expires_on(token); struct tm tm_info; localtime_r(&tv.tv_sec, &tm_info); char buffer[32]; strftime(buffer, sizeof(buffer) - 1, "%Y-%m-%d %H:%M:%S", &tm_info); json_builder_set_member_name(builder, "expires_on"); json_builder_add_string_value(builder, buffer); json_builder_set_member_name(builder, "account"); json_builder_begin_object(builder); json_builder_add_account(builder, mib_prt_get_account(token)); json_builder_end_object(builder); // finish builder json_builder_end_object(builder); print_json_builder(builder); g_object_unref(builder); } static JsonObject *parse_to_json_object(const gchar *data) { JsonParser *parser = json_parser_new(); gboolean ok = json_parser_load_from_data(parser, data, -1, NULL); if (!ok) { g_object_unref(parser); return NULL; } JsonObject *object = json_node_get_object(json_parser_get_root(parser)); json_object_ref(object); g_object_unref(parser); return object; } /** * We use the documented keys from msal-js / access-token-proof-of-possession.md * which are different from the ones that are communicated to the broker. */ static MIBPopParams *mib_pop_params_from_json(JsonObject *params_json) { if (!json_object_has_member(params_json, "authenticationScheme") || !json_object_has_member(params_json, "resourceRequestMethod") || !json_object_has_member(params_json, "resourceRequestUri")) { return NULL; } MIBPopParams *params = NULL; enum MIB_AUTH_SCHEME auth_scheme; enum MIB_REQUEST_METHOD req_method; const char *auth_scheme_str = json_object_get_string_member(params_json, "authenticationScheme"); if (g_strcmp0(auth_scheme_str, "PoP") == 0) { auth_scheme = MIB_AUTH_SCHEME_POP; } else if (g_strcmp0(auth_scheme_str, "Bearer") == 0) { auth_scheme = MIB_AUTH_SCHEME_BEARER; } else { g_printerr("invalid authentication scheme: %s", auth_scheme_str); goto err; } const char *req_method_str = json_object_get_string_member(params_json, "resourceRequestMethod"); if (g_strcmp0(req_method_str, "GET") == 0) { req_method = MIB_REQUEST_METHOD_GET; } else if (g_strcmp0(req_method_str, "POST") == 0) { req_method = MIB_REQUEST_METHOD_POST; } else if (g_strcmp0(req_method_str, "PUT") == 0) { req_method = MIB_REQUEST_METHOD_PUT; } else { g_printerr("invalid request method: %s", req_method_str); goto err; } const gchar *req_uri = json_object_get_string_member(params_json, "resourceRequestUri"); params = mib_pop_params_new(auth_scheme, req_method, req_uri); if (!params) { goto err; } if (json_object_has_member(params_json, "shrClaims")) { mib_pop_params_set_shr_claims( params, json_object_get_string_member(params_json, "shrClaims")); } if (json_object_has_member(params_json, "shrNonce")) { mib_pop_params_set_shr_nonce( params, json_object_get_string_member(params_json, "shrNonce")); } return params; err: if (params) g_object_unref(params); return NULL; } GSList *default_scope_if_empty(GSList *scopes) { if (!scopes) { scopes = g_slist_append(scopes, g_strdup(MIB_SCOPE_GRAPH_DEFAULT)); } return scopes; } static void print_help(char *name) { g_print("Usage: %s COMMAND [OPTION]...\n", basename(name)); g_print("Commands:\n"); g_print( " getAccounts, removeAccount, acquirePrtSsoCookie, acquireTokenSilent,\n" " acquireTokenInteractive, getLinuxBrokerVersion, generateSignedHttpRequest\n"); g_print("Options:\n"); g_print(" -a Account index (default: 0)\n"); g_print(" -A Select account by User Principal Name\n"); g_print(" -d Decode JWT\n"); g_print(" -f Set output format: %s, %s (default: %s)\n", FORMAT_TEXT, FORMAT_JSON, FORMAT_TEXT); g_print(" -h Print this help message\n"); g_print(" -I Enforce interactive token acquire\n"); g_print(" -P Proof-of-Possession parameters\n"); g_print(" -r OIDC redirect URI\n"); g_print(" -s Azure client application ID (default: %s)\n", CLIENT_ID_DEFAULT); g_print(" -S OIDC scope (repeatable)\n"); g_print(" -t Renew token\n"); g_print(" -x Entra ID authority (default: %s)\n", MIB_AUTHORITY_COMMON); } int main(int argc, char **argv) { int account_idx = 0; char *account_hint = NULL; const gchar *authority = MIB_AUTHORITY_COMMON; char *command = NULL; gchar *client_id = CLIENT_ID_DEFAULT; gchar *pop_params = NULL; JsonObject *pop_params_json = NULL; MIBPopParams *auth_params = NULL; gchar *redirect_uri = NULL; GSList *scopes = NULL; char *renew_token = NULL; int decode = 0; int enforce_interactive = 0; gchar *format = FORMAT_TEXT; int c; if (argc < 2) { print_help(argv[0]); return 1; } command = argv[1]; if (strcmp(command, "-h") == 0) { print_help(argv[0]); return 0; } while ((c = getopt(argc - 1, argv + 1, "a:A:df:hIP:r:s:S:t:x:")) != -1) switch (c) { case 'a': account_idx = atoi(optarg); break; case 'A': g_clear_pointer(&account_hint, g_free); account_hint = g_strdup(optarg); break; case 'd': decode = 1; break; case 'f': format = optarg; break; case 'h': print_help(argv[0]); return 0; case 'I': enforce_interactive = 1; break; case 'P': pop_params = optarg; break; case 'r': g_clear_pointer(&redirect_uri, g_free); redirect_uri = g_strdup(optarg); break; case 's': client_id = optarg; break; case 'S': scopes = g_slist_append(scopes, g_strdup(optarg)); break; case 't': renew_token = optarg; break; case 'x': authority = optarg; break; case '?': print_help(argv[0]); return 1; default: abort(); } if (!command) { g_print("Error: -c is required\n"); return 1; } if (account_idx < 0) { g_print("Error: -a cannot be negative\n"); return 1; } if (scopes && (strncmp(command, "acquire", strlen("acquire")) != 0)) { g_slist_free_full(scopes, g_free); g_printerr( "Warning: scopes must only be provided on acquire* commands. Ignoring\n"); } cancellable = g_cancellable_new(); MIBClientApp *app = mib_public_client_app_new(client_id, authority, cancellable, NULL); if (!app) { g_print("Error: Failed to start app\n"); return 1; } mib_client_app_set_enforce_interactive(app, enforce_interactive); if (redirect_uri) { mib_client_app_set_redirect_uri(app, redirect_uri); g_clear_pointer(&redirect_uri, g_free); } // register cancellation handler signal(SIGINT, sig_handler); if (pop_params) { pop_params_json = parse_to_json_object(pop_params); if (!pop_params_json) { g_print("Error: Failed to parse PoP parameters\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } auth_params = mib_pop_params_from_json(pop_params_json); json_object_unref(pop_params_json); } if (strcmp(command, "getAccounts") == 0 && account_hint) { MIBAccount *account = NULL; account = mib_client_app_get_account_by_upn(app, account_hint); g_free(account_hint); if (!account) { g_print("Error[getAccounts]: No accounts found\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { print_account(account, " "); } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { json_print_account(account); } else { g_print("Error[getAccounts]: Unsupported output format: %s\n", format); } g_object_unref(account); } else if (strcmp(command, "getAccounts") == 0) { GSList *accounts = mib_client_app_get_accounts(app); if (!accounts) { g_print("Error[getAccounts]: No accounts found\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { print_account_list(accounts, " "); } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { json_print_account_list(accounts); } else { g_print("Error[getAccounts]: Unsupported output format: %s\n", format); } g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); } else if (strcmp(command, "removeAccount") == 0) { GSList *accounts = mib_client_app_get_accounts(app); if (!accounts || (unsigned)account_idx >= g_slist_length(accounts)) { if (!accounts) g_print("No accounts registered\n"); else g_print("Invalid account index\n"); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_object_unref(app); g_object_unref(cancellable); return 1; } MIBAccount *account = g_slist_nth_data(accounts, account_idx); g_print("Selected account: %s\n", mib_account_get_username(account)); int ret = mib_client_app_remove_account(app, account); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); if (ret == 0) { g_print("removed account\n"); } else { g_print("failed to remove account\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } } else if (strcmp(command, "acquirePrtSsoCookie") == 0) { scopes = default_scope_if_empty(scopes); GSList *accounts = mib_client_app_get_accounts(app); if (!accounts || (unsigned)account_idx >= g_slist_length(accounts)) { g_print("Error[acquirePrtSsoCookie]: %s\n", !accounts ? "No accounts found" : "Invalid account index"); g_slist_free_full(scopes, g_free); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_object_unref(app); g_object_unref(cancellable); return 1; } MIBAccount *account = g_slist_nth_data(accounts, account_idx); MIBPrtSsoCookie *prt_cookie = mib_client_app_acquire_prt_sso_cookie( app, account, MIB_SSO_URL_DEFAULT, scopes); g_slist_free_full(scopes, g_free); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); if (!prt_cookie) { g_print( "Error[acquirePrtSsoCookie]: Failed to acquire PRT SSO cookie\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { print_prt_sso_cookie(prt_cookie, decode); } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { json_print_prt_sso_cookie(prt_cookie, decode); } else { g_print( "Error[acquirePrtSsoCookie]: Unsupported output format: %s\n", format); } g_object_unref(prt_cookie); } else if (strcmp(command, "acquireTokenSilent") == 0) { scopes = default_scope_if_empty(scopes); GSList *accounts = mib_client_app_get_accounts(app); if (!accounts || (unsigned)account_idx >= g_slist_length(accounts)) { g_print("Error[acquireTokenSilent]: %s\n", !accounts ? "No accounts found" : "Invalid account index"); g_slist_free_full(scopes, g_free); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_object_unref(app); g_object_unref(cancellable); return 1; } MIBAccount *account = g_slist_nth_data(accounts, account_idx); MIBPrt *prt_token = mib_client_app_acquire_token_silent( app, account, scopes, NULL, auth_params, renew_token); g_slist_free_full(scopes, g_free); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); if (auth_params) g_object_unref(auth_params); if (!prt_token) { g_print("Error[acquireTokenSilent]: Failed to acquire token\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { print_prt_token(prt_token, decode); } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { json_print_prt_token(prt_token, decode); } else { g_print( "Error[acquireTokenSilent]: Unsupported output format: %s\n", format); } g_object_unref(prt_token); } else if (strcmp(command, "acquireTokenInteractive") == 0) { scopes = default_scope_if_empty(scopes); MIBPrt *prt_token = mib_client_app_acquire_token_interactive( app, scopes, MIB_PROMPT_CONSENT, NULL, NULL, NULL, auth_params); g_slist_free_full(scopes, g_free); if (auth_params) g_object_unref(auth_params); if (!prt_token) { g_print( "Error[acquireTokenInteractive]: Failed to acquire token\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { print_prt_token(prt_token, decode); } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { json_print_prt_token(prt_token, decode); } else { g_print( "Error[acquireTokenInteractive]: Unsupported output format: %s\n", format); } g_object_unref(prt_token); } else if (strcmp(command, "getLinuxBrokerVersion") == 0) { gchar *version = mib_client_app_get_linux_broker_version(app, MSAL_CPP_VERSION); if (version) { g_print("Linux broker version: %s\n", version); g_free(version); } else { g_print("Error[getLinuxBrokerVersion]: Failed to get version\n"); return 1; } } else if (strcmp(command, "generateSignedHttpRequest") == 0) { GSList *accounts = mib_client_app_get_accounts(app); if (!accounts || (unsigned)account_idx >= g_slist_length(accounts)) { g_print("Error[generateSignedHttpRequest]: %s\n", !accounts ? "No accounts found" : "Invalid account index"); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_object_unref(app); g_object_unref(cancellable); return 1; } if (!auth_params) { g_print( "Error[generateSignedHttpRequest]: PoP parameters are required\n"); g_print( "Example: -P " "'{\"authenticationScheme\":\"PoP\",\"resourceRequestMethod\":" "\"POST\",\"resourceRequestUri\":\"https://example.com/\"}'\n"); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); g_object_unref(app); g_object_unref(cancellable); return 1; } MIBAccount *account = g_slist_nth_data(accounts, account_idx); gchar *token = mib_client_app_generate_signed_http_request(app, account, auth_params); g_object_unref(auth_params); g_slist_free_full(accounts, (GDestroyNotify)g_object_unref); if (token) { if (g_ascii_strcasecmp(format, FORMAT_TEXT) == 0) { if (decode) { print_decoded_jwt(token); } else { g_print("HTTP request token: %s\n", token); } } else if (g_ascii_strcasecmp(format, FORMAT_JSON) == 0) { JsonBuilder *builder = json_builder_new(); json_builder_begin_object(builder); json_builder_set_member_name(builder, "token"); if (decode) { json_builder_add_jwt_token(builder, token); } else { json_builder_add_string_value(builder, token); } json_builder_end_object(builder); print_json_builder(builder); g_object_unref(builder); } else { g_print( "Error[generateSignedHttpRequest]: Unsupported output format: %s\n", format); } g_free(token); } else { g_print( "Error[generateSignedHttpRequest]: Failed to generate signed " "HTTP request\n"); g_object_unref(app); g_object_unref(cancellable); return 1; } } else { g_print("Unknown command: %s\n", command); g_object_unref(app); g_object_unref(cancellable); return 1; } g_object_unref(app); g_object_unref(cancellable); return 0; }