🐝
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

348 lines
12 KiB

  1. #!/usr/bin/env python3
  2. #
  3. # Copyright 2012 Google Inc.
  4. # Copyright 2020 Manos Pitsidianakis
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """Performs client tasks for testing IMAP OAuth2 authentication.
  18. To use this script, you'll need to have registered with Google as an OAuth
  19. application and obtained an OAuth client ID and client secret.
  20. See https://developers.google.com/identity/protocols/OAuth2 for instructions on
  21. registering and for documentation of the APIs invoked by this code.
  22. This script has 3 modes of operation.
  23. 1. The first mode is used to generate and authorize an OAuth2 token, the
  24. first step in logging in via OAuth2.
  25. oauth2 --user=xxx@gmail.com \
  26. --client_id=1038[...].apps.googleusercontent.com \
  27. --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \
  28. --generate_oauth2_token
  29. The script will converse with Google and generate an oauth request
  30. token, then present you with a URL you should visit in your browser to
  31. authorize the token. Once you get the verification code from the Google
  32. website, enter it into the script to get your OAuth access token. The output
  33. from this command will contain the access token, a refresh token, and some
  34. metadata about the tokens. The access token can be used until it expires, and
  35. the refresh token lasts indefinitely, so you should record these values for
  36. reuse.
  37. 2. The script will generate new access tokens using a refresh token.
  38. oauth2 --user=xxx@gmail.com \
  39. --client_id=1038[...].apps.googleusercontent.com \
  40. --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \
  41. --refresh_token=1/Yzm6MRy4q1xi7Dx2DuWXNgT6s37OrP_DW_IoyTum4YA
  42. 3. The script will generate an OAuth2 string that can be fed
  43. directly to IMAP or SMTP. This is triggered with the --generate_oauth2_string
  44. option.
  45. oauth2 --generate_oauth2_string --user=xxx@gmail.com \
  46. --access_token=ya29.AGy[...]ezLg
  47. The output of this mode will be a base64-encoded string. To use it, connect to a
  48. IMAPFE and pass it as the second argument to the AUTHENTICATE command.
  49. a AUTHENTICATE XOAUTH2 a9sha9sfs[...]9dfja929dk==
  50. """
  51. import base64
  52. import imaplib
  53. import json
  54. from optparse import OptionParser
  55. import smtplib
  56. import sys
  57. import urllib.request, urllib.parse, urllib.error
  58. def SetupOptionParser():
  59. # Usage message is the module's docstring.
  60. parser = OptionParser(usage=__doc__)
  61. parser.add_option('--generate_oauth2_token',
  62. action='store_true',
  63. dest='generate_oauth2_token',
  64. help='generates an OAuth2 token for testing')
  65. parser.add_option('--generate_oauth2_string',
  66. action='store_true',
  67. dest='generate_oauth2_string',
  68. help='generates an initial client response string for '
  69. 'OAuth2')
  70. parser.add_option('--client_id',
  71. default=None,
  72. help='Client ID of the application that is authenticating. '
  73. 'See OAuth2 documentation for details.')
  74. parser.add_option('--client_secret',
  75. default=None,
  76. help='Client secret of the application that is '
  77. 'authenticating. See OAuth2 documentation for '
  78. 'details.')
  79. parser.add_option('--access_token',
  80. default=None,
  81. help='OAuth2 access token')
  82. parser.add_option('--refresh_token',
  83. default=None,
  84. help='OAuth2 refresh token')
  85. parser.add_option('--scope',
  86. default='https://mail.google.com/',
  87. help='scope for the access token. Multiple scopes can be '
  88. 'listed separated by spaces with the whole argument '
  89. 'quoted.')
  90. parser.add_option('--test_imap_authentication',
  91. action='store_true',
  92. dest='test_imap_authentication',
  93. help='attempts to authenticate to IMAP')
  94. parser.add_option('--test_smtp_authentication',
  95. action='store_true',
  96. dest='test_smtp_authentication',
  97. help='attempts to authenticate to SMTP')
  98. parser.add_option('--user',
  99. default=None,
  100. help='email address of user whose account is being '
  101. 'accessed')
  102. parser.add_option('--quiet',
  103. action='store_true',
  104. default=False,
  105. dest='quiet',
  106. help='Omit verbose descriptions and only print '
  107. 'machine-readable outputs.')
  108. return parser
  109. # The URL root for accessing Google Accounts.
  110. GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
  111. # Hardcoded dummy redirect URI for non-web apps.
  112. REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
  113. def AccountsUrl(command):
  114. """Generates the Google Accounts URL.
  115. Args:
  116. command: The command to execute.
  117. Returns:
  118. A URL for the given command.
  119. """
  120. return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)
  121. def UrlEscape(text):
  122. # See OAUTH 5.1 for a definition of which characters need to be escaped.
  123. return urllib.parse.quote(text, safe='~-._')
  124. def UrlUnescape(text):
  125. # See OAUTH 5.1 for a definition of which characters need to be escaped.
  126. return urllib.parse.unquote(text)
  127. def FormatUrlParams(params):
  128. """Formats parameters into a URL query string.
  129. Args:
  130. params: A key-value map.
  131. Returns:
  132. A URL query string version of the given parameters.
  133. """
  134. param_fragments = []
  135. for param in sorted(iter(params.items()), key=lambda x: x[0]):
  136. param_fragments.append('%s=%s' % (param[0], UrlEscape(param[1])))
  137. return '&'.join(param_fragments)
  138. def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'):
  139. """Generates the URL for authorizing access.
  140. This uses the "OAuth2 for Installed Applications" flow described at
  141. https://developers.google.com/accounts/docs/OAuth2InstalledApp
  142. Args:
  143. client_id: Client ID obtained by registering your app.
  144. scope: scope for access token, e.g. 'https://mail.google.com'
  145. Returns:
  146. A URL that the user should visit in their browser.
  147. """
  148. params = {}
  149. params['client_id'] = client_id
  150. params['redirect_uri'] = REDIRECT_URI
  151. params['scope'] = scope
  152. params['response_type'] = 'code'
  153. return '%s?%s' % (AccountsUrl('o/oauth2/auth'),
  154. FormatUrlParams(params))
  155. def AuthorizeTokens(client_id, client_secret, authorization_code):
  156. """Obtains OAuth access token and refresh token.
  157. This uses the application portion of the "OAuth2 for Installed Applications"
  158. flow at https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse
  159. Args:
  160. client_id: Client ID obtained by registering your app.
  161. client_secret: Client secret obtained by registering your app.
  162. authorization_code: code generated by Google Accounts after user grants
  163. permission.
  164. Returns:
  165. The decoded response from the Google Accounts server, as a dict. Expected
  166. fields include 'access_token', 'expires_in', and 'refresh_token'.
  167. """
  168. params = {}
  169. params['client_id'] = client_id
  170. params['client_secret'] = client_secret
  171. params['code'] = authorization_code
  172. params['redirect_uri'] = REDIRECT_URI
  173. params['grant_type'] = 'authorization_code'
  174. request_url = AccountsUrl('o/oauth2/token')
  175. response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode()).read()
  176. return json.loads(response)
  177. def RefreshToken(client_id, client_secret, refresh_token):
  178. """Obtains a new token given a refresh token.
  179. See https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh
  180. Args:
  181. client_id: Client ID obtained by registering your app.
  182. client_secret: Client secret obtained by registering your app.
  183. refresh_token: A previously-obtained refresh token.
  184. Returns:
  185. The decoded response from the Google Accounts server, as a dict. Expected
  186. fields include 'access_token', 'expires_in', and 'refresh_token'.
  187. """
  188. params = {}
  189. params['client_id'] = client_id
  190. params['client_secret'] = client_secret
  191. params['refresh_token'] = refresh_token
  192. params['grant_type'] = 'refresh_token'
  193. request_url = AccountsUrl('o/oauth2/token')
  194. response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode()).read()
  195. return json.loads(response)
  196. def GenerateOAuth2String(username, access_token, base64_encode=True):
  197. """Generates an IMAP OAuth2 authentication string.
  198. See https://developers.google.com/google-apps/gmail/oauth2_overview
  199. Args:
  200. username: the username (email address) of the account to authenticate
  201. access_token: An OAuth2 access token.
  202. base64_encode: Whether to base64-encode the output.
  203. Returns:
  204. The SASL argument for the OAuth2 mechanism.
  205. """
  206. auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
  207. if base64_encode:
  208. auth_string = base64.b64encode(bytes(auth_string, 'utf-8'))
  209. return auth_string
  210. def TestImapAuthentication(user, auth_string):
  211. """Authenticates to IMAP with the given auth_string.
  212. Prints a debug trace of the attempted IMAP connection.
  213. Args:
  214. user: The Gmail username (full email address)
  215. auth_string: A valid OAuth2 string, as returned by GenerateOAuth2String.
  216. Must not be base64-encoded, since imaplib does its own base64-encoding.
  217. """
  218. print()
  219. imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
  220. imap_conn.debug = 4
  221. imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
  222. imap_conn.select('INBOX')
  223. def TestSmtpAuthentication(user, auth_string):
  224. """Authenticates to SMTP with the given auth_string.
  225. Args:
  226. user: The Gmail username (full email address)
  227. auth_string: A valid OAuth2 string, not base64-encoded, as returned by
  228. GenerateOAuth2String.
  229. """
  230. print()
  231. smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
  232. smtp_conn.set_debuglevel(True)
  233. smtp_conn.ehlo('test')
  234. smtp_conn.starttls()
  235. smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
  236. def RequireOptions(options, *args):
  237. missing = [arg for arg in args if getattr(options, arg) is None]
  238. if missing:
  239. print('Missing options: %s' % ' '.join(missing), file=sys.stderr)
  240. sys.exit(-1)
  241. def main(argv):
  242. options_parser = SetupOptionParser()
  243. (options, args) = options_parser.parse_args()
  244. if options.refresh_token:
  245. RequireOptions(options, 'client_id', 'client_secret')
  246. response = RefreshToken(options.client_id, options.client_secret,
  247. options.refresh_token)
  248. if options.quiet:
  249. print(response['access_token'])
  250. else:
  251. print('Access Token: %s' % response['access_token'])
  252. print('Access Token Expiration Seconds: %s' % response['expires_in'])
  253. elif options.generate_oauth2_string:
  254. RequireOptions(options, 'user', 'access_token')
  255. oauth2_string = GenerateOAuth2String(options.user, options.access_token)
  256. if options.quiet:
  257. print(oauth2_string.decode('utf-8'))
  258. else:
  259. print('OAuth2 argument:\n' + oauth2_string.decode('utf-8'))
  260. elif options.generate_oauth2_token:
  261. RequireOptions(options, 'client_id', 'client_secret')
  262. print('To authorize token, visit this url and follow the directions:')
  263. print(' %s' % GeneratePermissionUrl(options.client_id, options.scope))
  264. authorization_code = input('Enter verification code: ')
  265. response = AuthorizeTokens(options.client_id, options.client_secret,
  266. authorization_code)
  267. print('Refresh Token: %s' % response['refresh_token'])
  268. print('Access Token: %s' % response['access_token'])
  269. print('Access Token Expiration Seconds: %s' % response['expires_in'])
  270. elif options.test_imap_authentication:
  271. RequireOptions(options, 'user', 'access_token')
  272. TestImapAuthentication(options.user,
  273. GenerateOAuth2String(options.user, options.access_token,
  274. base64_encode=False))
  275. elif options.test_smtp_authentication:
  276. RequireOptions(options, 'user', 'access_token')
  277. TestSmtpAuthentication(options.user,
  278. GenerateOAuth2String(options.user, options.access_token,
  279. base64_encode=False))
  280. else:
  281. options_parser.print_help()
  282. print('Nothing to do, exiting.')
  283. return
  284. if __name__ == '__main__':
  285. main(sys.argv)