├── .gitignore ├── CONTRIBUTING.md ├── FAQ.md ├── LICENSE ├── Makefile ├── README.md ├── VERIFYING.md ├── pam_signal_authenticator.c ├── share ├── org.asamk.Signal.conf ├── org.asamk.Signal.service ├── sample_pam_signal-authenticator ├── sample_pam_sshd ├── sample_sshd_config └── signal-authenticator.service ├── signal-auth-link ├── signal-auth-opt-in └── signal-auth-setup /.gitignore: -------------------------------------------------------------------------------- 1 | *.so 2 | *.py 3 | *.pyc 4 | *.swp 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Looking to contribute? Great! 4 | Remember to rebase to my master branch before submitting any pull requests. 5 | Here are some low-hanging fruit: 6 | 7 | - Test on a variety of different machines, architectures, etc. 8 | - Stress test. 9 | - Find and fix typos or otherwise improve clarity in the README. 10 | - Improve the signal-auth-setup shell script for clarity and robustness. 11 | - Write a man page. 12 | - Create unit tests. 13 | - Contribute to OpenSSH to resolve 14 | [bug #2246](https://bugzilla.mindrot.org/show_bug.cgi?id=2246) 15 | so that we can finally have (Public key AND Signal) OR (Password AND Signal) 16 | authentication. 17 | - Contribute to signal-cli. 18 | - Begin process of packaging for your distro. 19 | 20 | ## Hacking 21 | 22 | The `pam_syslog` function is useful for testing, 23 | 24 | ``` 25 | pam_syslog(pamh, LOG_INFO, "%s %d", "printf like formatting", 7); 26 | ``` 27 | 28 | and results appear in your syslog. 29 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions 2 | 3 | ## Can I test without messing up my already installed Signal app? 4 | 5 | Yes. The authenticator requires one phone number to SEND tokens from, and one 6 | phone number to RECEIVE tokens at. 7 | Only the SENDING phone number will be (re-)registered with Signal, so use a 8 | Google voice number for that one. 9 | The RECEIVING number will never be messed with. 10 | 11 | ## Is it safe to depend on signal-authenticator for my security? 12 | 13 | NO, absolutely not (yet). 14 | This authenticator needs to be thoroughly tested and reviewed before you should depend on 15 | it. 16 | At present, it should only be used for testing purposes on a machine you have 17 | physical access to (in case of unforeseen lockout of SSH) and should be used in conjunction with 18 | public-key authentication or password-based authentication. 19 | 20 | ## I found a bug, usability concern, or typo... 21 | 22 | Report it to the issues page. If it is security critical, report it without 23 | giving details and we will find a way to get in contact. 24 | 25 | ## Didn't NIST deprecate 2FA through SMS? 26 | 27 | [Yes](https://pages.nist.gov/800-63-3/sp800-63b.html). 28 | Signal does not use SMS. 29 | SMS was deprecated because it is not encrypted and therefore susceptible to a 30 | huge number of attacks rendering it inappropriate for authentication. 31 | Signal messages are end-to-end encrypted using strong modern cryptography. 32 | Only someone with root access to the sending server or someone with 33 | the ability to unlock your phone and Signal app can see the 2FA tokens. 34 | 35 | ## What is wrong with google-authenticator? 36 | 37 | Google-authenticator is, as far as I can tell, a good product. 38 | I would not go so far as to say that anything is "wrong" with it. 39 | I do have some concerns though. 40 | 41 | - Google-authenticator uses either HOTP (HMAC-based One-Time Password) or TOTP (Time-based 42 | One-Time Password) algorithms in order to generate 2FA tokens. 43 | With HOTP and TOTP, a pre-shared key and either a counter (HOTP) or an accurate 44 | clock (TOTP) is used to generate the 2FA token. 45 | The authenticating server never sends the user any token. 46 | This makes HOTP vulnerable to denial-of-service attacks based on counter 47 | desynchronization, and it makes TOTP vulnerable to replay attacks where an 48 | attacker looking over your shoulder could use the same 2FA token as you to log 49 | in to your account if she acts quickly enough. 50 | So much for "one-time" passwords! 51 | 52 | - Pre-shared keys are too easy to share or steal. 53 | The pre-shared key for google-authenticator is shared either by scanning a 54 | QR code or by inputting the 26 alphanumeric character secret key. 55 | It should not be easy to share a secret key like this. 56 | Signal uses a key generated on your device automatically that is trusted by the 57 | server on first use. 58 | Should a new key be required, it is verified by fingerprint. 59 | The user never has the chance to even see the secret key, and therefore is in 60 | no danger of sharing it (even accidentally) or having it stolen by an 61 | onlooker or camera. 62 | 63 | - Google may store a copy of your secret key, and thus may have access to your 64 | 2FA tokens. 65 | Upon creation of the secret key, the user is presented with a Google link 66 | containing the QR code with their secret key. 67 | Encoded in the URL is the secret key, whether it is for HOTP or TOTP, 68 | and the hostname of the machine for which the key is valid. 69 | Google may store all of this information and also other fingerprinting 70 | information about which device you visited the URL on. 71 | 72 | ## Can google see my authentication tokens with signal-authenticator? 73 | 74 | Short answer: the tokens themselves NO, when the tokens are sent MAYBE. 75 | 76 | Long answer: even if you register with a Google voice number, Google cannot see 77 | your authentication tokens. The reason is that the tokens are end-to-end 78 | encrypted and transmitted through Signal, not through SMS. 79 | One end is your phone, the other end is your computer. 80 | Neither end is your Google voice SMS inbox. 81 | The only reason a Google voice number is suggested is because Signal 82 | requires a "real" phone number in order to register, regardless of whether you are 83 | registering from a phone or computer. 84 | However, Signal itself depends on Google play services in a way that Google 85 | may be able to tell when you receive an authentication token, but Google will 86 | not be able to distinguish between this authentication token 87 | versus any other Signal message that you receive on your phone without doing 88 | some kind of traffic correlation attack. 89 | In any case, the tokens themselves are never seen by Google. 90 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -x c -D_POSIX_C_SOURCE -D_DEFAULT_SOURCE -std=c99 3 | CWARN_FLAGS = -Wall -Wextra -Wno-long-long -Wno-variadic-macros 4 | CSHAREDLIB_FLAGS = -fPIC -DPIC -shared -rdynamic 5 | LIB_SECURITY_DIR ?= "/lib/x86_64-linux-gnu/security" 6 | SIGNAL_CLI ?= "/usr/local/bin/signal-cli" 7 | SIGNAL_SHELL ?= "/bin/sh" 8 | SIGNAL_HOME ?= "/var/lib/signal-authenticator" 9 | PREFIX ?= "/usr/local" 10 | SHARE_DIR ?= $(PREFIX)/share 11 | PAMD_DIR ?= "/etc/pam.d" 12 | SIGNAL_USER = "signal-authenticator" 13 | PSA = pam_signal_authenticator 14 | SA = signal-authenticator 15 | 16 | all: $(PSA).so 17 | 18 | warn: CFLAGS += $(CWARN_FLAGS) 19 | warn: $(PSA).so 20 | 21 | $(PSA).so : $(PSA).c 22 | gcc $(CSHAREDLIB_FLAGS) $(CFLAGS) -DSIGNAL_CLI='$(SIGNAL_CLI)' -o $@ $< 23 | 24 | install: 25 | install -m 644 $(PSA).so $(LIB_SECURITY_DIR)/$(PSA).so 26 | install -m 755 signal-auth-setup $(PREFIX)/bin/signal-auth-setup 27 | install -m 755 signal-auth-link $(PREFIX)/bin/signal-auth-link 28 | install -m 755 signal-auth-opt-in $(PREFIX)/bin/signal-auth-opt-in 29 | mkdir -p $(SHARE_DIR)/$(SA) 30 | install -m 644 share/org.asamk.Signal.conf $(SHARE_DIR)/$(SA)/org.asamk.Signal.conf 31 | install -m 644 share/org.asamk.Signal.service $(SHARE_DIR)/$(SA)/org.asamk.Signal.service 32 | install -m 644 share/signal-authenticator.service $(SHARE_DIR)/$(SA)/signal-authenticator.service 33 | install -m 644 share/sample_pam_sshd $(SHARE_DIR)/$(SA)/sample_pam_sshd 34 | install -m 644 share/sample_sshd_config $(SHARE_DIR)/$(SA)/sample_sshd_config 35 | install -m 644 share/sample_pam_signal-authenticator $(SHARE_DIR)/$(SA)/sample_pam_signal-authenticator 36 | [ -e $(PAMD_DIR)/signal-authenticator ] || install -m 644 share/sample_pam_signal-authenticator $(PAMD_DIR)/signal-authenticator 37 | adduser --system --quiet --group --shell $(SIGNAL_SHELL) --home $(SIGNAL_HOME) $(SIGNAL_USER) 38 | chown -R $(SIGNAL_USER):$(SIGNAL_USER) $(SIGNAL_HOME) 39 | 40 | uninstall: 41 | rm -f $(LIB_SECURITY_DIR)/$(PSA).so 42 | rm -f $(PREFIX)/bin/signal-auth-setup 43 | rm -f $(PREFIX)/bin/signal-auth-link 44 | rm -f $(PREFIX)/bin/signal-auth-opt-in 45 | rm -f $(PAMD_DIR)/signal-authenticator 46 | rm --preserve-root -rf $(SHARE_DIR)/$(SA) 47 | deluser --system --quiet $(SIGNAL_USER) 48 | 49 | purge: uninstall 50 | rm --preserve-root -rf $(SIGNAL_HOME) 51 | # remove backups of the pam config file that may be present after 52 | # multiple installations 53 | rm -f $(PAMD_DIR)/signal-authenticator.~* 54 | 55 | clean: 56 | rm -f $(PSA).so 57 | 58 | .PHONY: warn all clean install uninstall purge 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # signal-authenticator 2 | 3 | PAM module for two-factor authentication through [Signal](https://github.com/WhisperSystems/Signal-Android). 4 | 5 | This project is in its ALPHA stage. 6 | It has been tested only by me for one year. 7 | It has not been professionally audited and you should not depend on it for your security at this time. 8 | The project is, however, ready for enthusiastic testers and contributors. 9 | 10 | Report bugs to the issues page and please rebase to my 11 | master branch before submitting any pull requests. 12 | See the [contributing page](CONTRIBUTING.md) for details. 13 | 14 | Releases are now signed with my GPG key with fingerprint 15 | 16 | ``` 17 | 6E59 B8E5 A268 E206 A086 329E 507E 1F83 7C14 FFA9 18 | ``` 19 | 20 | - [Requirements](#requirements) 21 | - [Options](#options) 22 | - [Setup (basic)](#setup-basic) 23 | - [Setup (share Signal number across multiple systems)](#setup-share-signal-number-across-multiple-systems) 24 | - [Setup (use the system dbus)](#setup-use-the-system-dbus) 25 | - [How can I require other combinations of authentication?](#how-can-i-require-other-combinations-of-authentication) 26 | - [Managing signal-authenticator manually](#managing-signal-authenticator-manually) 27 | - [Something didn't work?](#something-didnt-work) 28 | - [Uninstalling](#uninstalling) 29 | - [FAQ](FAQ.md) 30 | - [Contributing](CONTRIBUTING.md) 31 | 32 | ## Requirements 33 | 34 | - A phone with Signal installed (for receiving 1-time tokens) 35 | - A different phone number (using a google voice number is fine) 36 | - [signal-cli](https://github.com/AsamK/signal-cli) (version >= 0.5.3) 37 | - SSH server (assumed to be using publickey authentication already) 38 | 39 | ## Options 40 | 41 | These are options that you can pass as arguments to 42 | `pam_signal_authenticator.so` in your `/etc/pam.d/signal-authenticator` file. 43 | 44 | `-n`, `--nullok` (recommended) allows users who have not opted in to bypass Signal 45 | authentication, does not apply if user tried to opt in but has a bad config 46 | 47 | `-N`, `--nonull` requires all users to have properly setup Signal authentication 48 | (high chance of user locking themselves out of ssh) 49 | 50 | `-p`, `--nostrictpermissions` (not recommended) allows users to make bad choices about 51 | the permissions of their config files while still allowing them to use 52 | two-factor authentication 53 | 54 | `-s`, `--silent` no warnings or errors will be written to the system log 55 | 56 | `-d`, `--debug` print warnings and errors to the system log even if the `PAM_SILENT` flag is passed to PAM 57 | 58 | `-I`, `--ignore-spaces` ignore spaces in user's response (allowed characters must not contain 59 | a space) 60 | 61 | `-a`, `--add-space-every [n]` add a space every n characters so users can more easily 62 | read the token (implies `--ignore-spaces`) 63 | 64 | `-D`, `--dbus` speed things up by using signal-cli's experimental system dbus interface (requires 65 | signal-authenticator.service to be enabled) 66 | 67 | `-t`, `--time-limit [n]` tokens expire after n seconds. By default there is no 68 | time limit. 69 | 70 | `-C`, `--allowed-chars [chars]` tokens will be made up of these characters only. The 71 | number of allowed characters must be a divisor of 256. The default allowed 72 | characters are `abcdefghjkmnpqrstuvwxyz123456789`. 73 | 74 | `-T`, `--token-len [n]` sets the length of 1-time tokens. The default token 75 | length is 12. 76 | 77 | ## Setup (basic) 78 | 79 | ### Overview 80 | 81 | - Install signal-cli and java 82 | - Install build dependencies, download, make, and install signal-authenticator 83 | - Setup the system signal user with `sudo signal-auth-setup` 84 | - Modify `/etc/ssh/sshd_config` 85 | - Modify `/etc/pam.d/sshd` 86 | - (Optional) modify `/etc/pam.d/signal-authenticator` to change options 87 | - Restart ssh server 88 | - Opt-in a user with `signal-auth-opt-in` 89 | - Test it! 90 | 91 | ### The details 92 | 93 | Install [signal-cli](https://github.com/AsamK/signal-cli) and java: 94 | 95 | ``` 96 | sudo apt-get update && sudo apt-get upgrade 97 | sudo apt-get install default-jre 98 | export VERSION=0.5.6 99 | wget https://github.com/AsamK/signal-cli/releases/download/v"${VERSION}"/signal-cli-"${VERSION}".tar.gz 100 | sudo tar xf signal-cli-"${VERSION}".tar.gz -C /opt 101 | sudo ln -sf /opt/signal-cli-"${VERSION}"/bin/signal-cli /usr/local/bin/ 102 | ``` 103 | 104 | Get the build dependencies, download, make, and install signal-authenticator: 105 | 106 | ``` 107 | sudo apt-get install build-essential libpam0g-dev 108 | git clone "https://github.com/kb100/signal-authenticator.git" 109 | # or fork your own copy and clone that 110 | cd signal-authenticator 111 | make 112 | sudo make install 113 | ``` 114 | 115 | Next setup the signal-authenticator user's Signal number: 116 | 117 | ``` 118 | sudo signal-auth-setup 119 | ``` 120 | 121 | This will prompt you for the Signal number (including plus sign and country code) 122 | the authenticator will use to SEND tokens, e.g. `+15551231234`. 123 | It is recommended and easy to create a google voice number for this step. 124 | This step (re)registers the given number with Signal servers, so 125 | DO NOT use the number that you want to RECEIVE tokens at for this step. 126 | 127 | We give instructions assuming that public key authentication is already setup and that 128 | the desired authentication is public key AND Signal authentication. 129 | For other authentication combinations, see 130 | [How can I require other combinations of authentication?](#how-can-i-require-other-combinations-of-authentication). 131 | In order to require public key authentication and allow users to opt in to two-factor authentication, 132 | the important options for `/etc/ssh/sshd_config` are 133 | 134 | ``` 135 | # ... other options 136 | 137 | # If you want to make sure it works before going live only listen to localhost 138 | # ListenAddress 127.0.0.1 139 | AuthenticationMethods publickey,keyboard-interactive:pam 140 | PubkeyAuthentication yes 141 | AuthorizedKeysFile %h/.ssh/authorized_keys 142 | ChallengeResponseAuthentication yes 143 | PasswordAuthentication no 144 | UsePAM yes 145 | ``` 146 | 147 | and for `/etc/pam.d/sshd` 148 | 149 | ``` 150 | # comment out this common-auth line, this will ask for a passphrase even though 151 | # we have disabled PasswordAuthentication 152 | # @include common-auth 153 | @include signal-authenticator 154 | ``` 155 | 156 | Note: PAM config files are are more like scripts, 157 | they are executed in order so make sure you put 158 | the new include signal-authenticator line exactly where the common-auth line used to be (near the top), 159 | otherwise you may allow a user access before authenticating them (BAD!). 160 | 161 | You may add options in `/etc/pam.d/signal-authenticator` to your liking at this 162 | time. 163 | Sane defaults are used and you do not need to change any options right now if you 164 | just want to get it working first. 165 | 166 | Restart your sshd (for future reference, this is only needed after 167 | modifying `/etc/ssh/sshd_config`, modifications to the PAM files take effect 168 | immediately): 169 | 170 | ``` 171 | sudo systemctl restart sshd 172 | ``` 173 | 174 | Your signal-authenticator is now up and running! Though no one has opted in 175 | yet, so if you test it you should see 176 | 177 | ``` 178 | [user ~]$ ssh user@localhost 179 | Enter passphrase for key '/home/user/.ssh/id_rsa': 180 | Authenticated with partial success. 181 | Authenticated fully. User has not enabled two-factor authentication. 182 | Last login: Wed Jul 20 19:59:45 2016 from 127.0.0.1 183 | [user ~]$ 184 | ``` 185 | 186 | To opt in, a user should run 187 | ``` 188 | signal-auth-opt-in 189 | ``` 190 | which will ask the user for the phone number to RECEIVE tokens at. 191 | There is no danger of messing up your already installed Signal at this step. 192 | This will create the necessary 193 | `.signal_authenticator` file in the user's home directory. 194 | 195 | Now the user's two-factor authentication is enabled, and it should look 196 | something like: 197 | 198 | ``` 199 | [user ~]$ ssh user@localhost 200 | Enter passphrase for key '/home/user/.ssh/id_rsa': 201 | Authenticated with partial success. 202 | (1-time code sent through Signal!) 203 | 1-time code: mlfdolnvfb 204 | Last login: Wed Jun 29 16:36:29 2016 from 127.0.0.1 205 | [user ~]$ 206 | ``` 207 | 208 | ## Setup (share Signal number across multiple systems) 209 | 210 | If you administrate multiple servers and would like to have 211 | signal-authenticator share a single real phone number for all of your servers, 212 | this section is for you. 213 | 214 | Pick one of your machines as primary and follow the setup for the previous 215 | section on that machine. 216 | 217 | On all other machines follow the 218 | instructions of the previous section, except: 219 | use 220 | 221 | ``` 222 | sudo signal-auth-setup as-linked 223 | ``` 224 | 225 | which will provide a tsdevice:/... link. 226 | The program will hang until you complete the rest of the process. 227 | Copy this link and via a secure channel transmit it to the primary machine. 228 | On the primary machine run 229 | 230 | ``` 231 | sudo signal-auth-link add 232 | ``` 233 | 234 | which will prompt you to paste the tsdevice:/... link. 235 | The two devices will then link and the signal number is shared between the 236 | linked devices. The primary is the only one that can add or remove linked 237 | devices. 238 | 239 | ## Setup (use the system dbus) 240 | 241 | Using a long-lived signal-cli instance that uses the system dbus offers a noticeable 242 | speedup for users because it bypasses signal-cli's significant startup overhead. 243 | First, setup signal-authenticator without the dbus option. 244 | The dbus service file, dbus configuration file, and the systemd service file 245 | should already be available in `/usr/local/share/signal-authenticator`. 246 | Theoretically, systemd is not required and you could use another system daemon 247 | manager, but our instructions assume you are using systemd. 248 | Copy the files to the correct locations, have sed put in the correct phone number to 249 | send tokens from, and enable the service: 250 | 251 | ``` 252 | DIR="/usr/local/share/signal-authenticator" 253 | sudo cp $DIR/org.asamk.Signal.conf /etc/dbus-1/system.d 254 | sudo cp $DIR/org.asamk.Signal.service /usr/share/dbus-1/system-services 255 | sudo cp $DIR/signal-authenticator.service /etc/systemd/system 256 | username=$(sudo cat ~signal-authenticator/.signal_authenticator | grep -o "+.*$") 257 | sudo sed -i -e "s|%number%|$username|" /etc/systemd/system/signal-authenticator.service 258 | sudo systemctl daemon-reload 259 | sudo systemctl enable signal-authenticator.service 260 | sudo systemctl reload dbus.service 261 | ``` 262 | At this point, the `--dbus` flag will work when passed to signal-authenticator 263 | in your `/etc/pam.d/sshd`. 264 | While the long-lived signal-cli is running, the authenticator will ONLY work 265 | with the `--dbus` flag. 266 | If you want to go back to not using the dbus, you must stop the 267 | signal-authenticator service: 268 | 269 | ``` 270 | systemctl stop signal-authenticator.service 271 | systemctl disable signal-authenticator.service 272 | ``` 273 | 274 | ## How can I require other combinations of authentication? 275 | 276 | Other multi-factor authentication combinations can be achieved by changing 277 | `/etc/pam.d/sshd` and `/etc/ssh/sshd_config`. 278 | In the below examples, only the parts of the files that need to be changed 279 | from what was described above are shown. 280 | 281 | #### Public key AND Signal 282 | 283 | `/etc/pam.d/sshd` 284 | ``` 285 | # comment out this common-auth line 286 | # @include common-auth 287 | @include signal-authenticator 288 | ``` 289 | 290 | `/etc/ssh/sshd_config` 291 | ``` 292 | AuthenticationMethods publickey,keyboard-interactive:pam 293 | ``` 294 | 295 | #### Public key AND Password AND Signal 296 | 297 | `/etc/pam.d/sshd` 298 | ``` 299 | @include common-auth 300 | @include signal-authenticator 301 | ``` 302 | 303 | `/etc/ssh/sshd_config` 304 | ``` 305 | AuthenticationMethods publickey,keyboard-interactive:pam 306 | ``` 307 | 308 | #### Public key OR (Password AND Signal) 309 | 310 | `/etc/pam.d/sshd` 311 | ``` 312 | @include common-auth 313 | @include signal-authenticator 314 | ``` 315 | 316 | `/etc/ssh/sshd_config` 317 | ``` 318 | AuthenticationMethods publickey keyboard-interactive:pam 319 | ``` 320 | 321 | #### Password AND Signal 322 | 323 | **(Highly discouraged, you should allow public key access)** 324 | 325 | `/etc/pam.d/sshd` 326 | ``` 327 | @include common-auth 328 | @include signal-authenticator 329 | ``` 330 | 331 | `/etc/ssh/sshd_config` 332 | ``` 333 | AuthenticationMethods keyboard-interactive:pam 334 | ``` 335 | 336 | #### (Public key AND Signal) OR (Password AND Signal) 337 | 338 | Unfortunately, due to the way that ssh interacts with PAM, this is not 339 | possible. The following **does not work** and will break your logins 340 | 341 | `/etc/ssh/sshd_config` 342 | ``` 343 | # DON'T DO THIS 344 | AuthenticationMethods publickey,keyboard-interactive:pam password,keyboard-interactive:pam 345 | ``` 346 | 347 | Although one would hope that this would work, when PAM is enabled "password" 348 | ALWAYS uses PAM, which we do not want since we are using PAM for Signal 349 | authentication. If you know a way around this please let me know. 350 | 351 | ## Managing signal-authenticator manually 352 | 353 | signal-authenticator works simply by using signal-cli and keeping the config in 354 | the signal-authenticator user's home directory `/var/lib/signal-authenticator`. 355 | If you need to do things like trust a user's new key, remove a user from the 356 | trust store, or reset a session from the server side, you may get fine control 357 | by switching to the signal-authenticator user with `sudo su 358 | signal-authenticator` and using signal-cli manually. 359 | If you want to completely start over with a fresh config, new keys, and 360 | reregister Signal, you can use `sudo signal-auth-setup override` 361 | instead. 362 | 363 | ## Something didn't work? 364 | 365 | If something isn't working create an issue on the issues page and let me know 366 | what's happening. 367 | Errors are logged in your system logs using syslog. 368 | If your sshd config has `SyslogFacility AUTH` (this is the default on 369 | debian, e.g.) then the right log is probably `/var/log/auth`, 370 | but it may also be `/var/log/syslog` depending on your system. 371 | You can also access logs using `sudo journalctl` if you are using systemd. 372 | 373 | ## Uninstalling 374 | 375 | If you want to uninstall signal-authenticator, first remove it from your pam 376 | configuration file `/etc/pam.d/sshd` and sshd 377 | configuration file `/etc/ssh/sshd_config`. 378 | 379 | To remove signal-authenticator but leave configuration files (e.g. if you plan 380 | on reinstalling shortly), from the repository directory run 381 | 382 | ``` 383 | sudo make uninstall 384 | ``` 385 | 386 | To remove signal-authenticator, including configuration files (pam 387 | configuration, signal-authenticator home directory, etc.) run 388 | 389 | ``` 390 | sudo make purge 391 | ``` 392 | 393 | Note, this operation deletes your signal-authenticator's private keys. 394 | If you reinstall, you will have to register with Signal servers again and 395 | new private keys will be generated. Any previous users will receive key change 396 | notices the next time they receive a one-time token from your authenticator. 397 | -------------------------------------------------------------------------------- /VERIFYING.md: -------------------------------------------------------------------------------- 1 | # Verifying releases 2 | 3 | Security conscious invididuals can check the GPG signature of all releases 4 | starting from `v0.4`. 5 | 6 | If this is your first time verifying a release, you will need to import my GPG key. 7 | 8 | ``` 9 | gpg --keyserver pgp.mit.edu --recv-key 6E59B8E5A268E206A086329E507E1F837C14FFA9 10 | ``` 11 | 12 | Now you can verify releases as follows: 13 | 14 | ``` 15 | # assuming you have cloned the repo into ~/signal-authenticator 16 | cd ~/signal-authenticator 17 | git tag --verify v0.4 18 | ``` 19 | 20 | You should see a message telling you that the signature is good and 21 | signed using the RSA key mentioned above. 22 | It is OK if it says the signature is untrusted. 23 | This just means that we have not verified identities in person and signed each 24 | other's keys. 25 | -------------------------------------------------------------------------------- /pam_signal_authenticator.c: -------------------------------------------------------------------------------- 1 | /* 2 | * pam_signal_authenticator.c 3 | * Copyright (C) 2016 James Murphy 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 2 of the License. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #define PAM_SM_ACCOUNT 34 | #define PAM_SM_AUTH 35 | #define PAM_SM_PASSWORD 36 | #define PAM_SM_SESSION 37 | #include 38 | #include 39 | #include 40 | 41 | #define VERSION "0.4" 42 | #define MODULE_NAME "pam_signal_authenticator.so" 43 | #ifndef SIGNAL_CLI 44 | #define SIGNAL_CLI "/usr/local/bin/signal-cli" 45 | #endif 46 | #define SIGNAL_CLI_LEN ((sizeof(SIGNAL_CLI)/sizeof(SIGNAL_CLI[0]))-1) 47 | 48 | #ifndef MAX_BUF_SIZE 49 | #define MAX_BUF_SIZE 1024 50 | #endif 51 | #ifndef TOKEN_LEN 52 | #define TOKEN_LEN 12 53 | #endif 54 | #ifndef MAX_TOKEN_LEN 55 | #define MAX_TOKEN_LEN 256 56 | #endif 57 | #ifndef MINIMUM_BITS_OF_ENTROPY 58 | #define MINIMUM_BITS_OF_ENTROPY 40 59 | #endif 60 | #ifndef TOKEN_TIME_TO_EXPIRE 61 | #define TOKEN_TIME_TO_EXPIRE 90 62 | #endif 63 | 64 | #ifndef CONFIG_FILE 65 | #define CONFIG_FILE ".signal_authenticator" 66 | #endif 67 | #ifndef SYSTEM_SIGNAL_USER 68 | #define SYSTEM_SIGNAL_USER "signal-authenticator" 69 | #endif 70 | 71 | #ifndef ALLOWED_CHARS_DEFAULT 72 | #define ALLOWED_CHARS_DEFAULT "abcdefghjkmnpqrstuvwxyz123456789" 73 | #endif 74 | #define ALLOWED_CHARS_LEN_DEFAULT ((sizeof(ALLOWED_CHARS_DEFAULT)/sizeof(ALLOWED_CHARS_DEFAULT[0]))-1) 75 | 76 | #ifndef SSH_PROMPT 77 | #define SSH_PROMPT "Input 1-time code: " 78 | #endif 79 | #ifndef SIGNAL_MESSAGE_PREFIX 80 | #define SIGNAL_MESSAGE_PREFIX "1-time code: " 81 | #endif 82 | #ifndef SIGNAL_MESSAGE_SUFFIX 83 | #define SIGNAL_MESSAGE_SUFFIX "" 84 | #endif 85 | #ifndef MAX_RECIPIENTS 86 | #define MAX_RECIPIENTS 5 87 | #endif 88 | #ifndef MAX_USERNAME_LEN 89 | #define MAX_USERNAME_LEN 32 90 | #endif 91 | 92 | typedef struct params { 93 | bool nullok; 94 | bool strict_permissions; 95 | bool silent; 96 | bool ignore_spaces; 97 | bool use_dbus; 98 | time_t time_limit; 99 | char *allowed_chars; 100 | size_t allowed_chars_len; 101 | size_t token_len; 102 | size_t add_space_every; 103 | } Params; 104 | 105 | void errorx(pam_handle_t *pamh, const Params *params, const char *msg, ...) 106 | { 107 | va_list ap; 108 | va_start(ap, msg); 109 | if (!params || !params->silent) 110 | pam_vsyslog(pamh, LOG_ERR, msg, ap); 111 | va_end(ap); 112 | } 113 | 114 | void free_str_array(char *ptr[], size_t len) 115 | { 116 | for (size_t i = 0; i < len; i++) { 117 | if (ptr[i]) 118 | free(ptr[i]); 119 | } 120 | } 121 | 122 | int get_2fa_config_filename(const char* home_dir, char fn_buf[MAX_BUF_SIZE]) 123 | { 124 | if (home_dir == NULL || fn_buf == NULL) 125 | return PAM_AUTH_ERR; 126 | size_t buf_size = sizeof(char[MAX_BUF_SIZE]); 127 | int snp_ret = snprintf(fn_buf, buf_size, 128 | "%s/"CONFIG_FILE, home_dir); 129 | if (snp_ret < 0 || (size_t)snp_ret >= buf_size) 130 | return PAM_AUTH_ERR; 131 | return PAM_SUCCESS; 132 | } 133 | 134 | void make_spaced_version_of_token(const Params *params, const char * token, 135 | char spaced_token_buf[MAX_BUF_SIZE]) 136 | { 137 | if (!params || !params->add_space_every || !token || !spaced_token_buf) 138 | return; 139 | size_t spaces_to_add = 2 * (params->token_len / params->add_space_every); 140 | if (spaces_to_add + params->token_len + 1 >= MAX_BUF_SIZE) 141 | return; 142 | for (size_t i = 1; *token; i++, token++, spaced_token_buf++) { 143 | *spaced_token_buf = *token; 144 | if (*(token+1) && i % params->add_space_every == 0) { 145 | *++spaced_token_buf = ' '; 146 | *++spaced_token_buf = ' '; 147 | } 148 | } 149 | *spaced_token_buf = '\0'; 150 | } 151 | 152 | int make_message(const Params *params, const char *token, char message_buf[MAX_BUF_SIZE]) 153 | { 154 | if (token == NULL || message_buf == NULL) 155 | return PAM_AUTH_ERR; 156 | 157 | char spaced_token_buf[MAX_BUF_SIZE] = {0}; 158 | if (params->add_space_every) { 159 | make_spaced_version_of_token(params, token, spaced_token_buf); 160 | token = spaced_token_buf; 161 | } 162 | 163 | size_t buf_size = sizeof(char[MAX_BUF_SIZE]); 164 | int snp_ret = snprintf(message_buf, buf_size, 165 | "%s%s%s", SIGNAL_MESSAGE_PREFIX, token, SIGNAL_MESSAGE_SUFFIX); 166 | if (snp_ret < 0 || (size_t)snp_ret >= buf_size) 167 | return PAM_AUTH_ERR; 168 | return PAM_SUCCESS; 169 | } 170 | 171 | bool configs_exist_permissions_good( 172 | pam_handle_t *pamh, 173 | const Params *params, 174 | struct passwd *pw, 175 | struct passwd *signal_pw, 176 | const char *config_filename, 177 | const char *signal_config_filename) 178 | { 179 | struct stat s = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, {0}}; 180 | int result = stat(config_filename, &s); 181 | if (result < 0) /* File does not exist or something else fails */ 182 | return false; 183 | if (params->strict_permissions) { 184 | if (s.st_uid != pw->pw_uid) { 185 | errorx(pamh, params, "User uid=%d, but config uid=%d", pw->pw_uid, s.st_uid); 186 | return false; 187 | } else if (s.st_gid != pw->pw_gid) { 188 | errorx(pamh, params, "User gid=%d, but config gid=%d", pw->pw_gid, s.st_gid); 189 | return false; 190 | } else if ((s.st_mode & S_IROTH) || (s.st_mode & S_IWOTH) || (s.st_mode & S_IXOTH)) { 191 | errorx(pamh, params, "config has bad permissions, try chmod o-rwx"); 192 | return false; 193 | } 194 | } 195 | 196 | result = stat(signal_config_filename, &s); 197 | if (result < 0) 198 | return false; 199 | /* Option --nostrictpermissions does not apply to the admin */ 200 | if (s.st_uid != signal_pw->pw_uid || s.st_gid != signal_pw->pw_gid) { 201 | errorx(pamh, params, "signal-authenticator uid=%d, but config uid=%d", 202 | signal_pw->pw_uid, s.st_uid); 203 | return false; 204 | } 205 | if ((s.st_mode & S_IROTH) || (s.st_mode & S_IWOTH) || (s.st_mode & S_IXOTH)) { 206 | errorx(pamh, params, "signal-authenticator config has bad permissions, try chmod o-rwx"); 207 | return false; 208 | } 209 | return true; 210 | } 211 | 212 | int drop_privileges(struct passwd *pw) 213 | { 214 | int gid_ret = setgid(pw->pw_gid); 215 | int uid_ret = setuid(pw->pw_uid); 216 | if (uid_ret != 0 || gid_ret != 0) 217 | return PAM_AUTH_ERR; 218 | return PAM_SUCCESS; 219 | } 220 | 221 | 222 | /* 223 | * Gives the number of bits of entropy of a token of length token_len with 224 | * allowed_chars_len possible characters. 225 | */ 226 | int bits_of_entropy(size_t token_len, size_t allowed_chars_len) 227 | { 228 | /* allowed_chars_len is a divisor of 256, and thus a power of 2 */ 229 | size_t power = 0; 230 | while (allowed_chars_len > 1) { 231 | allowed_chars_len >>= 1; 232 | power++; 233 | } 234 | return power * token_len; 235 | } 236 | 237 | /* 238 | * Will be token_len many characters from allowed_chars. 239 | * Result is uniform string in allowed_chars because allow_chars_len is a 240 | * divisor of 256. 241 | */ 242 | int generate_random_token(char token_buf[MAX_TOKEN_LEN + 1], const Params *params) 243 | { 244 | FILE *urandom = fopen("/dev/urandom", "r"); 245 | const char *allowed_chars = params->allowed_chars; 246 | size_t n = params->allowed_chars_len; 247 | size_t token_len = params->token_len; 248 | 249 | if (urandom == NULL) 250 | return PAM_AUTH_ERR; 251 | unsigned char c; 252 | for (size_t i = 0; i < token_len; i++) { 253 | c = fgetc(urandom); 254 | token_buf[i] = allowed_chars[c % n]; 255 | } 256 | token_buf[token_len] = '\0'; 257 | if (fclose(urandom) != 0) 258 | return PAM_AUTH_ERR; 259 | return PAM_SUCCESS; 260 | } 261 | 262 | bool looks_like_phone_number(const char *str) 263 | { 264 | if (str == NULL) 265 | return false; 266 | size_t len = strlen(str); 267 | if (len == 0 || len > MAX_USERNAME_LEN) 268 | return false; 269 | while (*str) { 270 | if (!(*str == '+' || ('0' <= *str && *str <= '9'))) 271 | return false; 272 | str++; 273 | } 274 | return true; 275 | } 276 | 277 | int parse_signal_username(const char *config_filename, char username_buf[MAX_USERNAME_LEN + 1]) 278 | { 279 | FILE *config_fp = fopen(config_filename, "r"); 280 | if (config_fp == NULL) 281 | return PAM_AUTH_ERR; 282 | 283 | bool username_found = false; 284 | char line_buf[MAX_BUF_SIZE] = {0}; 285 | while (!username_found && fgets(line_buf, sizeof(line_buf), config_fp) != NULL) { 286 | size_t len = strlen(line_buf); 287 | if (line_buf[len - 1] != '\n') 288 | return PAM_AUTH_ERR; 289 | line_buf[len - 1] = '\0'; 290 | const char *line = line_buf; 291 | switch (*line) { 292 | case '#': /* Comment? */ 293 | case '\0': /* Empty line? */ 294 | break; 295 | case 'u': /* username */ 296 | if (strncmp(line, "username=", strlen("username=")) != 0) 297 | goto cleanup_then_return_auth_err; 298 | line += strlen("username="); 299 | if (looks_like_phone_number(line)) { 300 | /* It is known here that strlen(line) <= MAX_USERNAME_LEN */ 301 | strncpy(username_buf, line, MAX_USERNAME_LEN + 1); 302 | username_found = true; 303 | } else { 304 | goto cleanup_then_return_auth_err; 305 | } 306 | break; 307 | default: /* Ignore garbage */ 308 | break; 309 | } 310 | } 311 | if (fclose(config_fp) != 0 || !username_found) 312 | return PAM_AUTH_ERR; 313 | 314 | return PAM_SUCCESS; 315 | 316 | cleanup_then_return_auth_err: 317 | fclose(config_fp); 318 | return PAM_AUTH_ERR; 319 | } 320 | 321 | int parse_signal_recipients(const char *config_filename, char *recipients_arr[MAX_RECIPIENTS]) 322 | { 323 | FILE *config_fp = fopen(config_filename, "r"); 324 | if (config_fp == NULL) 325 | return PAM_AUTH_ERR; 326 | 327 | int recipient_count = 0; 328 | char line_buf[MAX_BUF_SIZE] = {0}; 329 | while (fgets(line_buf, sizeof(line_buf), config_fp) != NULL) { 330 | size_t len = strlen(line_buf); 331 | if (line_buf[len - 1] != '\n') 332 | return PAM_AUTH_ERR; 333 | line_buf[len - 1] = '\0'; 334 | const char *line = line_buf; 335 | switch (*line) { 336 | case '#': /* Comment? */ 337 | case '\0': /* Empty line? */ 338 | break; 339 | case 'r': /* recipient */ 340 | if (strncmp(line, "recipient=", strlen("recipient=")) != 0) 341 | goto cleanup_then_return_auth_err; 342 | line += strlen("recipient="); 343 | if (looks_like_phone_number(line)) { 344 | size_t username_len = strlen(line); 345 | recipients_arr[recipient_count] = calloc(username_len + 1, sizeof(char)); 346 | if (!recipients_arr[recipient_count]) 347 | goto cleanup_then_return_auth_err; 348 | strcpy(recipients_arr[recipient_count++], line); 349 | } else { 350 | goto cleanup_then_return_auth_err; 351 | } 352 | break; 353 | default: 354 | break; 355 | } 356 | 357 | /* 358 | * If the user specified more than MAX_RECIPIENTS recipients, just use 359 | * the first few 360 | */ 361 | if (recipient_count == MAX_RECIPIENTS) 362 | break; 363 | } 364 | if (fclose(config_fp) != 0 || recipient_count == 0) 365 | return PAM_AUTH_ERR; 366 | 367 | return PAM_SUCCESS; 368 | 369 | cleanup_then_return_auth_err: 370 | fclose(config_fp); 371 | return PAM_AUTH_ERR; 372 | } 373 | 374 | int build_signal_send_command( 375 | const Params *params, 376 | const char *sender, 377 | char *recipients[MAX_RECIPIENTS], 378 | const char *args[4 + MAX_RECIPIENTS + 1]) 379 | { 380 | if (sender == NULL || recipients == NULL || args == NULL) 381 | return PAM_AUTH_ERR; 382 | int dbus_offset = params->use_dbus ? -1 : 0; 383 | args[0] = "signal-cli"; 384 | if (!params->use_dbus) { 385 | args[1] = "-u"; 386 | args[2] = sender; 387 | } else { 388 | args[1] = "--dbus-system"; 389 | } 390 | args[3 + dbus_offset] = "send"; 391 | for (size_t i = 0; i < MAX_RECIPIENTS; i++) { 392 | if (recipients[i] && recipients[i][0]) { 393 | args[i + 4 + dbus_offset] = recipients[i]; 394 | } else { 395 | args[i + 4 + dbus_offset] = (const char *)NULL; 396 | break; 397 | } 398 | } 399 | args[4 + dbus_offset + MAX_RECIPIENTS] = (const char *)NULL; 400 | return PAM_SUCCESS; 401 | } 402 | 403 | int build_signal_receive_command(const char *username, const char *args[8]) 404 | { 405 | if (username == NULL || args == NULL) 406 | return PAM_AUTH_ERR; 407 | args[0] = "signal-cli"; 408 | args[1] = "-u"; 409 | args[2] = username; 410 | args[3] = "receive"; 411 | args[4] = "-t"; 412 | args[5] = "0"; 413 | args[6] = "--ignore-attachments"; 414 | args[7] = (const char *)NULL; 415 | return PAM_SUCCESS; 416 | } 417 | 418 | int signal_cli(pam_handle_t *pamh, const Params *params, 419 | struct passwd *drop_pw, char *const argv[], 420 | const char *msg) 421 | { 422 | pid_t c_pid; 423 | int status; 424 | int fd[2]; 425 | 426 | if (msg && pipe(fd) != 0) { 427 | errorx(pamh, params, "failed to make pipe for sending message"); 428 | return PAM_AUTH_ERR; 429 | } 430 | 431 | c_pid = fork(); 432 | if (c_pid == 0) { 433 | /* child */ 434 | int fdnull = open("/dev/null", O_RDWR); 435 | if (!fdnull) 436 | exit(EXIT_FAILURE); 437 | else if (msg && close(fd[1]) != 0) 438 | exit(EXIT_FAILURE); 439 | else if (dup2(msg ? fd[0] : fdnull, STDIN_FILENO) < 0) 440 | exit(EXIT_FAILURE); 441 | else if (msg && close(fd[0]) != 0) 442 | exit(EXIT_FAILURE); 443 | else if (dup2(fdnull, STDOUT_FILENO) < 0) 444 | exit(EXIT_FAILURE); 445 | else if (dup2(fdnull, STDERR_FILENO) < 0) 446 | exit(EXIT_FAILURE); 447 | else if (close(fdnull) != 0) 448 | exit(EXIT_FAILURE); 449 | else if (drop_privileges(drop_pw) != PAM_SUCCESS) 450 | exit(EXIT_FAILURE); 451 | execv(SIGNAL_CLI, argv); 452 | } else if (c_pid < 0) { 453 | errorx(pamh, params, "failed to fork child for sending message"); 454 | return PAM_AUTH_ERR; 455 | } 456 | /* parent */ 457 | bool failure = false; 458 | if (msg) { 459 | failure |= close(fd[0]); 460 | size_t n = strlen(msg); 461 | failure |= write(fd[1], msg, n) != (ssize_t)n; 462 | failure |= close(fd[1]); 463 | } 464 | wait(&status); 465 | 466 | if (failure || !WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS) 467 | return PAM_AUTH_ERR; 468 | 469 | return PAM_SUCCESS; 470 | } 471 | 472 | /* result is a valid string as long as input is */ 473 | void delete_spaces_inplace(char str[MAX_BUF_SIZE]) 474 | { 475 | if(!str) 476 | return; 477 | size_t i = 0; 478 | size_t j = 0; 479 | while (j < MAX_BUF_SIZE) { 480 | if (str[j] == ' ') 481 | j++; 482 | else 483 | str[i++] = str[j++]; 484 | } 485 | while (i < MAX_BUF_SIZE) { 486 | str[i++] = '\0'; 487 | } 488 | } 489 | 490 | int wait_for_response(pam_handle_t *pamh, const Params *params, char response_buf[MAX_BUF_SIZE]) 491 | { 492 | struct timespec sent_time; 493 | struct timespec completed_time; 494 | if (params->time_limit) { 495 | clock_gettime(CLOCK_MONOTONIC, &sent_time); 496 | pam_info(pamh, "Token expires in %zu seconds.", params->time_limit); 497 | } 498 | 499 | char *response = NULL; 500 | int ret = pam_prompt(pamh, PAM_PROMPT_ECHO_ON, &response, SSH_PROMPT); 501 | if (ret != PAM_SUCCESS) { 502 | if (response) 503 | free(response); 504 | if (ret == PAM_BUF_ERR) 505 | errorx(pamh, params, "Possible malicious attempt, PAM_BUF_ERR."); 506 | return ret; 507 | } 508 | 509 | if (response) { 510 | strncpy(response_buf, response, MAX_BUF_SIZE); 511 | free(response); 512 | if (response_buf[MAX_BUF_SIZE - 1] != '\0' ) { 513 | errorx(pamh, params, "Possible malicious attempt, response way too long."); 514 | return PAM_AUTH_ERR; 515 | } 516 | if (params->time_limit) { 517 | clock_gettime(CLOCK_MONOTONIC, &completed_time); 518 | if (completed_time.tv_sec > sent_time.tv_sec + params->time_limit) { 519 | errorx(pamh, params, "took too long to respond, token expired"); 520 | return PAM_AUTH_ERR; 521 | } 522 | } 523 | if (params->ignore_spaces) 524 | delete_spaces_inplace(response_buf); 525 | return PAM_SUCCESS; 526 | } 527 | return PAM_CONV_ERR; 528 | } 529 | 530 | bool is_spacefree(char *str) 531 | { 532 | if (!str) 533 | return true; 534 | while (*str) { 535 | if (*str++ == ' ') 536 | return false; 537 | } 538 | return true; 539 | } 540 | 541 | int parse_args(pam_handle_t *pamh, Params *params, int argc, const char **argv) 542 | { 543 | int c; 544 | int idx = -1; 545 | opterr = 0; /* global, tells getopt to not print any errors */ 546 | while (1) { 547 | static const char optstring[] = "+nNpsdIDa:t:C:T:"; 548 | static struct option options[] = { 549 | {"nullok", 0, 0, 'n'}, 550 | {"nonull", 0, 0, 'N'}, 551 | {"nostrictpermissions", 0, 0, 'p'}, 552 | {"silent", 0, 0, 's'}, 553 | {"debug", 0, 0, 'd'}, 554 | {"ignore-spaces", 0, 0, 'I'}, 555 | {"dbus", 0, 0, 'D'}, 556 | {"add-space-every", 1, 0, 'a'}, 557 | {"time-limit", 1, 0, 't'}, 558 | {"allowed-chars", 1, 0, 'C'}, 559 | {"token-len", 1, 0, 'T'}, 560 | {0, 0, 0, 0} 561 | }; 562 | 563 | c = getopt_long(argc, (char * const *)argv, optstring, options, &idx); 564 | if (c > 0) { 565 | for (size_t i = 0; options[i].name; i++) { 566 | if (options[i].val == c) { 567 | idx = i; 568 | break; 569 | } 570 | } 571 | } else if (c < 0) { 572 | break; 573 | } 574 | if (idx < 0) { 575 | errorx(pamh, NULL, "error processing arguments, aborting"); 576 | return PAM_AUTH_ERR; 577 | } else if (!idx--) { /* nullok */ 578 | params->nullok = true; 579 | } else if (!idx--) { /* nonull */ 580 | params->nullok = false; 581 | } else if (!idx--) { /* nostrictpermissions */ 582 | params->strict_permissions = false; 583 | } else if (!idx--) { /* silent */ 584 | params->silent = true; 585 | } else if (!idx--) { /* debug */ 586 | params->silent = false; 587 | } else if (!idx--) { /*ignore-spaces */ 588 | params->ignore_spaces = true; 589 | if (!is_spacefree(params->allowed_chars)) { 590 | errorx(pamh, NULL, "cannot ignore spaces if space is an allowed token character, aborting"); 591 | return PAM_AUTH_ERR; 592 | } 593 | } else if (!idx--) { /* dbus */ 594 | params->use_dbus = true; 595 | } else if (!idx--) { /* add-space-every */ 596 | params->add_space_every = (size_t)atoi(optarg); 597 | params->ignore_spaces = true; 598 | if (!is_spacefree(params->allowed_chars)) { 599 | errorx(pamh, NULL, "cannot add spaces if space is an allowed token character, aborting"); 600 | return PAM_AUTH_ERR; 601 | } 602 | } else if (!idx--) { /* time-limit */ 603 | params->time_limit = (time_t)atoi(optarg); 604 | if (params->time_limit > 3600) { 605 | errorx(pamh, NULL, "allowed time to login is more than an hour, too long, aborting"); 606 | return PAM_AUTH_ERR; 607 | } 608 | } else if (!idx--) { /* allowed-chars */ 609 | strncpy(params->allowed_chars, optarg, 255); 610 | params->allowed_chars[255] = '\0'; 611 | if (params->ignore_spaces && !is_spacefree(params->allowed_chars)) { 612 | errorx(pamh, NULL, "cannot ignore spaces if space is an allowed token character, aborting"); 613 | return PAM_AUTH_ERR; 614 | } 615 | size_t n = strlen(params->allowed_chars); 616 | params->allowed_chars_len = n; 617 | if (n < 8) { 618 | errorx(pamh, NULL, "allowed-chars is too short, must be at least 8 characters, aborting"); 619 | return PAM_AUTH_ERR; 620 | } else if (256 % n != 0) { 621 | errorx(pamh, NULL, "allowed-chars: %s\nlength: %zu\nlength must be a divisor of 256, aborting", params->allowed_chars, n); 622 | return PAM_AUTH_ERR; 623 | } 624 | } else if (!idx--) { /* token-len */ 625 | size_t len = (size_t)atoi(optarg); 626 | if (len > MAX_TOKEN_LEN) { 627 | errorx(pamh, NULL, "invalid token length: %zu", len); 628 | return PAM_AUTH_ERR; 629 | } 630 | params->token_len = len; 631 | } else { 632 | errorx(pamh, NULL, "error processing command line arguments, aborting"); 633 | return PAM_AUTH_ERR; 634 | } 635 | } 636 | if (optind != argc) { 637 | errorx(pamh, NULL, "Non-option argument given, did you forget --? Aborting"); 638 | return PAM_AUTH_ERR; 639 | } 640 | 641 | if (!params->allowed_chars || !params->allowed_chars[0]) { 642 | params->allowed_chars = ALLOWED_CHARS_DEFAULT; 643 | params->allowed_chars_len = ALLOWED_CHARS_LEN_DEFAULT; 644 | } 645 | 646 | int bits = bits_of_entropy(params->token_len, params->allowed_chars_len); 647 | if (bits < MINIMUM_BITS_OF_ENTROPY) { 648 | errorx(pamh, NULL, "Only %i bits of entropy per token, increase length or allow more characters, aborting", bits); 649 | return PAM_AUTH_ERR; 650 | } 651 | return PAM_SUCCESS; 652 | } 653 | 654 | /* 655 | * This is the entry point, think of it as main(). 656 | * PAM entry point for authentication verification 657 | */ 658 | PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) 659 | { 660 | int ret; 661 | char allowed_chars[256] = {0}; 662 | char *recipients_arr[MAX_RECIPIENTS] = {0}; 663 | 664 | Params params_s = { 665 | .nullok = !(flags & PAM_DISALLOW_NULL_AUTHTOK), 666 | .strict_permissions = true, 667 | .silent = flags & PAM_SILENT, 668 | .ignore_spaces = false, 669 | .use_dbus = false, 670 | .time_limit = 0, 671 | .allowed_chars = allowed_chars, 672 | .allowed_chars_len = 0, 673 | .token_len = TOKEN_LEN, 674 | .add_space_every = 0 675 | }; 676 | Params *params = ¶ms_s; 677 | if ((ret = parse_args(pamh, params, argc, argv)) != PAM_SUCCESS) 678 | return ret; 679 | 680 | int NULL_FAILURE = params->nullok ? PAM_SUCCESS : PAM_AUTH_ERR; 681 | 682 | /* Determine the user */ 683 | const char *user = NULL; 684 | if ((ret = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS || user == NULL) { 685 | errorx(pamh, params, "failed to get user"); 686 | return ret; 687 | } 688 | 689 | /* Get the user's passwd info */ 690 | struct passwd *pw = NULL; 691 | struct passwd pw_s; 692 | char passdw_char_buf[MAX_BUF_SIZE] = {0}; 693 | ret = getpwnam_r(user, &pw_s, passdw_char_buf, sizeof(passdw_char_buf), &pw); 694 | if (ret != 0 || pw == NULL || pw->pw_dir == NULL || pw->pw_dir[0] != '/') { 695 | errorx(pamh, params, "failed to get passwd struct"); 696 | return PAM_AUTH_ERR; 697 | } 698 | 699 | /* Get the signal-authenticator user's passwd info */ 700 | struct passwd *signal_pw = NULL; 701 | struct passwd signal_pw_s; 702 | char signal_passdw_char_buf[MAX_BUF_SIZE] = {0}; 703 | ret = getpwnam_r(SYSTEM_SIGNAL_USER, &signal_pw_s, signal_passdw_char_buf, 704 | sizeof(signal_passdw_char_buf), &signal_pw); 705 | if (ret != 0 || signal_pw == NULL || signal_pw->pw_dir == NULL || signal_pw->pw_dir[0] != '/') { 706 | errorx(pamh, params, "failed to get signal passwd struct"); 707 | return PAM_AUTH_ERR; 708 | } 709 | 710 | /* Check that user wants 2 factor authentication */ 711 | char config_filename_buf[MAX_BUF_SIZE] = {0}; 712 | if (get_2fa_config_filename(pw->pw_dir, config_filename_buf) != PAM_SUCCESS) { 713 | errorx(pamh, params, "failed to get config filename"); 714 | goto null_failure; 715 | } 716 | 717 | char signal_config_filename_buf[MAX_BUF_SIZE] = {0}; 718 | if (get_2fa_config_filename(signal_pw->pw_dir, signal_config_filename_buf) != PAM_SUCCESS) { 719 | errorx(pamh, params, "failed to get signal-authenticator config filename"); 720 | goto null_failure; 721 | } 722 | 723 | const char *config_filename = config_filename_buf; 724 | const char *signal_config_filename = signal_config_filename_buf; 725 | 726 | if (!configs_exist_permissions_good(pamh, params, pw, signal_pw, config_filename, signal_config_filename)) 727 | goto null_failure; 728 | 729 | /* 730 | * At this point we know the user must do 2fa, 731 | * they either opted in by putting the config file where it should be 732 | * or the sysadmin requires 2fa 733 | * (though the user or admin may still have an invalid config file) 734 | * from here on failures should err on the side of denying access 735 | */ 736 | 737 | char username_buf[MAX_USERNAME_LEN + 1] = {0}; 738 | if (parse_signal_username(signal_config_filename, username_buf) != PAM_SUCCESS) { 739 | errorx(pamh, params, "Failed to parse sender username from config"); 740 | goto cleanup_then_return_auth_err; 741 | } 742 | const char *username = username_buf; 743 | 744 | char token_buf[MAX_TOKEN_LEN + 1] = {0}; 745 | if (generate_random_token(token_buf, params) != PAM_SUCCESS) { 746 | errorx(pamh, params, "failed to generate random token"); 747 | goto cleanup_then_return_auth_err; 748 | } 749 | const char *token = token_buf; 750 | 751 | char message_buf[MAX_BUF_SIZE] = {0}; 752 | if (make_message(params, token, message_buf) != PAM_SUCCESS) { 753 | errorx(pamh, params, "failed to make message from token"); 754 | goto cleanup_then_return_auth_err; 755 | } 756 | const char *message = message_buf; 757 | 758 | if (parse_signal_recipients(config_filename, recipients_arr) != PAM_SUCCESS) { 759 | errorx(pamh, params, "Failed to parse recipients from config"); 760 | goto cleanup_then_return_auth_err; 761 | } 762 | 763 | const char *signal_send_args_arr[4 + MAX_RECIPIENTS + 1] = {0}; 764 | ret = build_signal_send_command(params, username, recipients_arr, signal_send_args_arr); 765 | if (ret != PAM_SUCCESS) { 766 | errorx(pamh, params, "Failed to build signal send command"); 767 | goto cleanup_then_return_auth_err; 768 | } 769 | char * const * signal_send_args = (char * const *)signal_send_args_arr; 770 | 771 | if (!params->use_dbus) { 772 | const char *signal_receive_args_arr[8]; 773 | if (build_signal_receive_command(username, signal_receive_args_arr) != PAM_SUCCESS) { 774 | errorx(pamh, params, "Failed to build signal receive command"); 775 | goto cleanup_then_return_auth_err; 776 | } 777 | 778 | char * const * signal_receive_args = (char * const *)signal_receive_args_arr; 779 | if (signal_cli(pamh, params, signal_pw, signal_receive_args, NULL) != PAM_SUCCESS) { 780 | errorx(pamh, params, "signal-cli receive command failed"); 781 | goto cleanup_then_return_auth_err; 782 | } 783 | } 784 | 785 | if (signal_cli(pamh, params, signal_pw, signal_send_args, message) != PAM_SUCCESS) { 786 | errorx(pamh, params, "signal-cli send command failed"); 787 | goto cleanup_then_return_auth_err; 788 | } 789 | 790 | char response_buf[MAX_BUF_SIZE] = {0}; 791 | if (wait_for_response(pamh, params, response_buf) != PAM_SUCCESS) { 792 | errorx(pamh, params, "failed response"); 793 | goto cleanup_then_return_auth_err; 794 | } 795 | const char *response = response_buf; 796 | if (strlen(response) != params->token_len || strncmp(response, token, params->token_len) != 0) { 797 | errorx(pamh, params, "incorrect token"); 798 | goto cleanup_then_return_auth_err; 799 | } 800 | 801 | free_str_array(recipients_arr, MAX_RECIPIENTS); 802 | return PAM_SUCCESS; 803 | 804 | null_failure: 805 | if (params->nullok) 806 | pam_info(pamh, "Authenticated fully. User has not enabled two-factor authentication."); 807 | return NULL_FAILURE; 808 | cleanup_then_return_auth_err: 809 | free_str_array(recipients_arr, MAX_RECIPIENTS); 810 | return PAM_AUTH_ERR; 811 | } 812 | 813 | /* 814 | * These PAM entry points are not used in signal-authenticator 815 | */ 816 | 817 | #pragma GCC diagnostic push 818 | #pragma GCC diagnostic ignored "-Wunused-parameter" 819 | 820 | /* PAM entry point for session creation */ 821 | PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) 822 | { 823 | return PAM_IGNORE; 824 | } 825 | 826 | /* PAM entry point for session cleanup */ 827 | PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char **argv) 828 | { 829 | return PAM_IGNORE; 830 | } 831 | 832 | /* PAM entry point for accounting */ 833 | PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) 834 | { 835 | return PAM_IGNORE; 836 | } 837 | 838 | /* 839 | * PAM entry point for setting user credentials (that is, to actually 840 | * establish the authenticated user's credentials to the service provider) 841 | */ 842 | PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) 843 | { 844 | return PAM_IGNORE; 845 | } 846 | 847 | /* PAM entry point for authentication token (password) changes */ 848 | PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, const char **argv) 849 | { 850 | return PAM_IGNORE; 851 | } 852 | 853 | #pragma GCC diagnostic pop 854 | -------------------------------------------------------------------------------- /share/org.asamk.Signal.conf: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /share/org.asamk.Signal.service: -------------------------------------------------------------------------------- 1 | [D-BUS Service] 2 | Name=org.asamk.Signal 3 | Exec=/bin/false 4 | SystemdService=dbus-org.asamk.Signal.service 5 | -------------------------------------------------------------------------------- /share/sample_pam_signal-authenticator: -------------------------------------------------------------------------------- 1 | # PAM configuration for the signal-authenticator service 2 | # 3 | # The default config is preserved in 4 | # /usr/local/share/signal-authenticator/sample_pam_signal-authenticator 5 | 6 | auth required pam_permit.so 7 | auth required pam_signal_authenticator.so --nullok 8 | 9 | ## Options for pam_signal_authenticator.so 10 | # 11 | # `-n`, `--nullok` (recommended) allows users who have not opted in to bypass Signal 12 | # authentication, does not apply if user tried to opt in but has a bad config 13 | # 14 | # `-N`, `--nonull` requires all users to have properly setup Signal authentication 15 | # (high chance of user locking themselves out of ssh) 16 | # 17 | # `-p`, `--nostrictpermissions` (not recommended) allows users to make bad choices about 18 | # the permissions of their config files while still allowing them to use 19 | # two-factor authentication 20 | # 21 | # `-s`, `--silent` no warnings or errors will be written to the system log 22 | # 23 | # `-d`, `--debug` print warnings and errors to the system log even if the `PAM_SILENT` flag is passed to PAM 24 | # 25 | # `-I`, `--ignore-spaces` ignore spaces in user's response (allowed characters must not contain 26 | # a space) 27 | # 28 | # `-a`, `--add-space-every [n]` add a space every n characters so users can more easily 29 | # read the token (implies `--ignore-spaces`) 30 | # 31 | # `-D`, `--dbus` speed things up by using signal-cli's experimental system dbus interface (requires 32 | # signal-authenticator.service to be enabled) 33 | # 34 | # `-t`, `--time-limit [n]` tokens expire after n seconds. By default there is no 35 | # time limit. 36 | # 37 | # `-C`, `--allowed-chars [chars]` tokens will be made up of these characters only. The 38 | # number of allowed characters must be a divisor of 256. The default allowed 39 | # characters are `abcdefghjkmnpqrstuvwxyz123456789`. 40 | # 41 | # `-T`, `--token-len [n]` sets the length of 1-time tokens. The default token 42 | # length is 12. 43 | -------------------------------------------------------------------------------- /share/sample_pam_sshd: -------------------------------------------------------------------------------- 1 | # PAM configuration for the Secure Shell service 2 | # /etc/pam.d/sshd 3 | 4 | # Standard Un*x authentication. 5 | # comment out this common-auth line, this will ask for a passphrase even though 6 | # we have disabled PasswordAuthentication 7 | # @include common-auth 8 | @include signal_authenticator 9 | 10 | # Disallow non-root logins when /etc/nologin exists. 11 | account required pam_nologin.so 12 | 13 | # Uncomment and edit /etc/security/access.conf if you need to set complex 14 | # access limits that are hard to express in sshd_config. 15 | # account required pam_access.so 16 | 17 | # Standard Un*x authorization. 18 | @include common-account 19 | 20 | # SELinux needs to be the first session rule. This ensures that any 21 | # lingering context has been cleared. Without this it is possible that a 22 | # module could execute code in the wrong domain. 23 | session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close 24 | 25 | # Set the loginuid process attribute. 26 | session required pam_loginuid.so 27 | 28 | # Create a new session keyring. 29 | session optional pam_keyinit.so force revoke 30 | 31 | # Standard Un*x session setup and teardown. 32 | @include common-session 33 | 34 | # Print the message of the day upon successful login. 35 | # This includes a dynamically generated part from /run/motd.dynamic 36 | # and a static (admin-editable) part from /etc/motd. 37 | session optional pam_motd.so motd=/run/motd.dynamic 38 | session optional pam_motd.so noupdate 39 | 40 | # Print the status of the user's mailbox upon successful login. 41 | session optional pam_mail.so standard noenv # [1] 42 | 43 | # Set up user limits from /etc/security/limits.conf. 44 | session required pam_limits.so 45 | 46 | # Read environment variables from /etc/environment and 47 | # /etc/security/pam_env.conf. 48 | session required pam_env.so # [1] 49 | # In Debian 4.0 (etch), locale-related environment variables were moved to 50 | # /etc/default/locale, so read that as well. 51 | session required pam_env.so user_readenv=1 envfile=/etc/default/locale 52 | 53 | # SELinux needs to intervene at login time to ensure that the process starts 54 | # in the proper default security context. Only sessions which are intended 55 | # to run in the user's context should be run after this. 56 | session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so open 57 | 58 | # Standard Un*x password updating. 59 | @include common-password 60 | -------------------------------------------------------------------------------- /share/sample_sshd_config: -------------------------------------------------------------------------------- 1 | # $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $ 2 | # /etc/ssh/sshd_config 3 | 4 | # This is the sshd server system-wide configuration file. See 5 | # sshd_config(5) for more information. 6 | 7 | # This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin 8 | 9 | # The strategy used for options in the default sshd_config shipped with 10 | # OpenSSH is to specify options with their default value where 11 | # possible, but leave them commented. Uncommented options override the 12 | # default value. 13 | 14 | #Port 22 15 | #AddressFamily any 16 | ListenAddress 127.0.0.1 17 | #ListenAddress :: 18 | 19 | #HostKey /etc/ssh/ssh_host_rsa_key 20 | #HostKey /etc/ssh/ssh_host_ecdsa_key 21 | #HostKey /etc/ssh/ssh_host_ed25519_key 22 | 23 | # Ciphers and keying 24 | #RekeyLimit default none 25 | 26 | # Logging 27 | #SyslogFacility AUTH 28 | #LogLevel INFO 29 | 30 | # Authentication: 31 | 32 | #LoginGraceTime 2m 33 | PermitRootLogin no 34 | #StrictModes yes 35 | #MaxAuthTries 6 36 | #MaxSessions 10 37 | 38 | AuthenticationMethods publickey,keyboard-interactive:pam 39 | PubkeyAuthentication yes 40 | 41 | # The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2 42 | # but this is overridden so installations will only check .ssh/authorized_keys 43 | AuthorizedKeysFile .ssh/authorized_keys 44 | 45 | #AuthorizedPrincipalsFile none 46 | 47 | #AuthorizedKeysCommand none 48 | #AuthorizedKeysCommandUser nobody 49 | 50 | # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts 51 | #HostbasedAuthentication no 52 | # Change to yes if you don't trust ~/.ssh/known_hosts for 53 | # HostbasedAuthentication 54 | #IgnoreUserKnownHosts no 55 | # Don't read the user's ~/.rhosts and ~/.shosts files 56 | #IgnoreRhosts yes 57 | 58 | # To disable tunneled clear text passwords, change to no here! 59 | PasswordAuthentication no 60 | #PermitEmptyPasswords no 61 | 62 | # Change to yes to enable challenge-response passwords (beware issues with 63 | # some PAM modules and threads) 64 | ChallengeResponseAuthentication yes 65 | 66 | # Kerberos options 67 | #KerberosAuthentication no 68 | #KerberosOrLocalPasswd yes 69 | #KerberosTicketCleanup yes 70 | #KerberosGetAFSToken no 71 | 72 | # GSSAPI options 73 | #GSSAPIAuthentication no 74 | #GSSAPICleanupCredentials yes 75 | #GSSAPIStrictAcceptorCheck yes 76 | #GSSAPIKeyExchange no 77 | 78 | # Set this to 'yes' to enable PAM authentication, account processing, 79 | # and session processing. If this is enabled, PAM authentication will 80 | # be allowed through the ChallengeResponseAuthentication and 81 | # PasswordAuthentication. Depending on your PAM configuration, 82 | # PAM authentication via ChallengeResponseAuthentication may bypass 83 | # the setting of "PermitRootLogin without-password". 84 | # If you just want the PAM account and session checks to run without 85 | # PAM authentication, then enable this but set PasswordAuthentication 86 | # and ChallengeResponseAuthentication to 'no'. 87 | UsePAM yes 88 | 89 | #AllowAgentForwarding yes 90 | #AllowTcpForwarding yes 91 | #GatewayPorts no 92 | X11Forwarding yes 93 | #X11DisplayOffset 10 94 | #X11UseLocalhost yes 95 | #PermitTTY yes 96 | PrintMotd no 97 | #PrintLastLog yes 98 | #TCPKeepAlive yes 99 | #UseLogin no 100 | #UsePrivilegeSeparation sandbox 101 | #PermitUserEnvironment no 102 | #Compression delayed 103 | #ClientAliveInterval 0 104 | #ClientAliveCountMax 3 105 | #UseDNS no 106 | #PidFile /var/run/sshd.pid 107 | #MaxStartups 10:30:100 108 | #PermitTunnel no 109 | #ChrootDirectory none 110 | #VersionAddendum none 111 | 112 | # no default banner path 113 | #Banner none 114 | 115 | # Allow client to pass locale environment variables 116 | AcceptEnv LANG LC_* 117 | 118 | # override default of no subsystems 119 | Subsystem sftp /usr/lib/openssh/sftp-server 120 | 121 | # Example of overriding settings on a per-user basis 122 | #Match User anoncvs 123 | # X11Forwarding no 124 | # AllowTcpForwarding no 125 | # PermitTTY no 126 | # ForceCommand cvs server 127 | -------------------------------------------------------------------------------- /share/signal-authenticator.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Two factor authentication through Signal 3 | Requires=dbus.socket 4 | After=dbus.socket 5 | Wants=network-online.target 6 | After=network-online.target 7 | 8 | [Service] 9 | Type=dbus 10 | Environment="SIGNAL_CLI_OPTS=-Xms2m" 11 | ExecStart=/usr/local/bin/signal-cli -u %number% --config /var/lib/signal-authenticator/.config/signal daemon --ignore-attachments --system 12 | StandardOutput=null 13 | User=signal-authenticator 14 | BusName=org.asamk.Signal 15 | 16 | [Install] 17 | Alias=dbus-org.asamk.Signal.service 18 | -------------------------------------------------------------------------------- /signal-auth-link: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # (C) James Murphy 2016, licensed under GPLv2 4 | # 5 | # Script to setup/opt in to signal authentication 6 | 7 | if ! command -v signal-cli >/dev/null 2>&1; then 8 | echo >&2 "signal-cli not found, aborting." 9 | exit 1 10 | fi 11 | 12 | SIGNAL_CLI="$(which signal-cli)" 13 | SIGNAL_HOME="/var/lib/signal-authenticator" 14 | SIGNAL_AUTH_CONFIG="$SIGNAL_HOME/.signal_authenticator" 15 | 16 | IFS=" 17 | " 18 | 19 | function sanitize_tsdevice_link { 20 | echo "$1" | tr -d " " 21 | } 22 | 23 | 24 | function usage_and_exit { 25 | printf \ 26 | "Usage: signal-auth-link [-h|--help] add|list|remove 27 | Manage subordinate (linked) signal authenticator devices. Only the primary 28 | device can add or remove linked devices. 29 | Options: 30 | add\t\tAdd a subordinate signal authenticator device 31 | list\t\tList all subordinate devices 32 | remove\t\tRemove (revoke) a subordinate signal authenticator device 33 | -h --help\tShow this help message.\n" && exit 0 34 | } 35 | 36 | if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then 37 | usage_and_exit 38 | fi 39 | 40 | if [[ "$(id -u)" -ne 0 ]]; then 41 | echo >&2 "Must be root to manage system user's subordinate devices, aborting." 42 | exit 1 43 | fi 44 | 45 | USERNAME=$(grep -o '+[[:digit:]]\+$' $SIGNAL_AUTH_CONFIG) 46 | 47 | if [[ "$1" == "list" ]]; then 48 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" listDevices 49 | elif [[ "$1" == "add" ]]; then 50 | read -p "Paste tsdevice:/ link from running signal-auth-setup as-linked: " TSDEVICE_LINK 51 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" addDevice --uri "$TSDEVICE_LINK" 52 | elif [[ "$1" == "remove" ]]; then 53 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" listDevices 54 | read -p "What is Device ID to remove? " DEVICE_ID 55 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" removeDevice -d "$DEVICE_ID" 56 | else 57 | usage_and_exit 58 | fi 59 | -------------------------------------------------------------------------------- /signal-auth-opt-in: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # (C) James Murphy 2016, licensed under GPLv2 4 | # 5 | # Script for users to opt in a user for signal authentication 6 | 7 | IFS=" 8 | " 9 | function sanitize_phone_number { 10 | echo "$1" | tr -cd "0123456789+" 11 | } 12 | 13 | function looks_like_phone_number { 14 | if [[ "$1" =~ ^\+[0-9]+$ ]]; then 15 | return 0 16 | else 17 | return 1 18 | fi 19 | } 20 | 21 | if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then 22 | printf \ 23 | "Usage: signal-auth-opt-in [-h|--help] [override] 24 | Opt in to signal authentication. 25 | Options: 26 | [no argument]\tOpt in the current user for signal authentication. 27 | override\tDon't abort if config alerady exists. 28 | -h --help\tShow this help message.\n" && exit 0 29 | fi 30 | 31 | if [[ "$(id -u)" -eq 0 ]]; then 32 | echo "Warning: you are opting in the root user for signal authentication." 33 | echo "If you meant to configure the system for signal authentication, use signal-auth-setup." 34 | fi 35 | 36 | if [[ -f "$HOME/.signal_authenticator" ]]; then 37 | if [[ "$1" != "override" ]]; then 38 | echo >&2 "It looks like you have already opted in for signal authentication." 39 | echo >&2 "Execute 'signal-auth-opt-in override' to override your old config." 40 | exit 2 41 | else 42 | echo >&2 "It looks like signal-authenticator is already setup, continuing anyway." 43 | fi 44 | fi 45 | 46 | read -p "Input signal username to receive tokens at, including country code (e.g. +15553331234): " USERNAME 47 | USERNAME=$(sanitize_phone_number $USERNAME) 48 | echo "Sanitized number: $USERNAME" 49 | if ! looks_like_phone_number $USERNAME; then 50 | echo >&2 "Bad phone number: $USERNAME, aborting" 51 | exit 4 52 | fi 53 | 54 | echo "Creating ~/.signal_authenticator" 55 | echo "recipient=$USERNAME" > "$HOME/.signal_authenticator" 56 | chmod o-rwx "$HOME/.signal_authenticator" 57 | echo "Remember to test sshing in before logging out to avoid lockout." 58 | echo "If testing fails or if you want to opt out, delete .signal_authenticator." 59 | echo "You have successfully opted in for signal authentication." 60 | -------------------------------------------------------------------------------- /signal-auth-setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # (C) James Murphy 2016, licensed under GPLv2 4 | # 5 | # Script to setup system for signal authentication 6 | 7 | if ! command -v signal-cli >/dev/null 2>&1; then 8 | echo >&2 "signal-cli not found, aborting." 9 | exit 1 10 | fi 11 | 12 | SIGNAL_CLI="$(which signal-cli)" 13 | SIGNAL_HOME="/var/lib/signal-authenticator" 14 | 15 | IFS=" 16 | " 17 | function sanitize_phone_number { 18 | echo "$1" | tr -cd "0123456789+" 19 | } 20 | 21 | function looks_like_phone_number { 22 | if [[ "$1" =~ ^\+[0-9]+$ ]]; then 23 | return 0 24 | else 25 | return 1 26 | fi 27 | } 28 | 29 | if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then 30 | printf \ 31 | "Usage: signal-auth-setup [-h|--help] [as-linked] [override] 32 | Setup signal authentication on your system. 33 | Options: 34 | [no argument]\tSetup the signal-authenticator user's home by registering a 35 | \t\tsignal number 36 | as-linked\tSetup the signal-authenticator user's home by linking as a 37 | \t\tsubordinate device of an existing signal authenticator. 38 | override\tDon't abort if config alerady exists. 39 | -h --help\tShow this help message.\n" && exit 0 40 | fi 41 | 42 | if [[ "$(id -u)" -ne 0 ]]; then 43 | echo >&2 "Must be root to setup for the system user, aborting." 44 | exit 1 45 | fi 46 | 47 | if [[ -f "$SIGNAL_HOME/.signal_authenticator" ]] || [[ -d "$SIGNAL_HOME/.signal" ]]; then 48 | if [[ "$1" != "override" ]] && [[ "$2" != "override" ]]; then 49 | echo >&2 "It looks like signal-authenticator's home is already setup, aborting." 50 | echo >&2 "Use the override argument to bypass." 51 | echo >&2 "Bypassing will completely remove all previous"\ 52 | "configuration, including stored keys and fingerprints." 53 | exit 2 54 | else 55 | echo >&2 "It looks like signal-authenticator's home is already setup, continuing anyway." 56 | fi 57 | fi 58 | 59 | read -p "Input signal username to send tokens from (e.g. +15553331234): " USERNAME 60 | USERNAME=$(sanitize_phone_number $USERNAME) 61 | echo "Sanitized number: $USERNAME" 62 | if ! looks_like_phone_number $USERNAME; then 63 | echo >&2 "Bad phone number: $USERNAME, aborting" 64 | exit 4 65 | fi 66 | echo "Creating $SIGNAL_HOME/.signal_authenticator" 67 | echo "username=$USERNAME" > "$SIGNAL_HOME/.signal_authenticator" 68 | chmod o-rwx "$SIGNAL_HOME/.signal_authenticator" 69 | chown signal-authenticator:signal-authenticator "$SIGNAL_HOME/.signal_authenticator" 70 | 71 | echo "Removing old config, if it exists" 72 | rm -rf "$SIGNAL_HOME/.config/signal" >/dev/null 2>&1 73 | 74 | echo "Registering signal username" 75 | if [[ "$1" == "as-linked" ]] || [[ "$2" == "as-linked" ]]; then 76 | echo "Registering as subordinate (linked) device." 77 | echo "To complete linking, you must run signal-auth-link from the primary device." 78 | echo "It will ask for the following tsdevice:/ link." 79 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" link 80 | if [[ "$?" != "0" ]]; then 81 | echo >&2 "Failed to link, aborting." 82 | exit 3 83 | fi 84 | else 85 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" register 86 | read -p "Verify code (sent SMS to $USERNAME): " CODE 87 | sudo -u signal-authenticator "$SIGNAL_CLI" -u "$USERNAME" verify "$CODE" 88 | if [[ "$?" != "0" ]]; then 89 | echo >&2 "Failed to verify $USERNAME, aborting." 90 | exit 3 91 | fi 92 | fi 93 | chmod -R o-rwx "$SIGNAL_HOME/.config/signal" 94 | chown -R signal-authenticator:signal-authenticator "$SIGNAL_HOME/.config/signal" 95 | echo "Your signal authentication is now setup." 96 | --------------------------------------------------------------------------------