Skip to content

Commit

Permalink
add export of plain otpauth url list, fix #196
Browse files Browse the repository at this point in the history
  • Loading branch information
scito committed Mar 31, 2024
1 parent 1b11c4c commit 6bdcaf3
Show file tree
Hide file tree
Showing 6 changed files with 215 additions and 150 deletions.
280 changes: 140 additions & 140 deletions Pipfile.lock

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
[![Stand With Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/badges/StandWithUkraine.svg)](https://stand-with-ukraine.pp.ua)
<!-- ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/protobuf)
[![GitHub Pipenv locked Python version](https://img.shields.io/github/pipenv/locked/python-version/scito/extract_otp_secrets)](https://github.com/scito/extract_otp_secrets/blob/master/Pipfile.lock)
![protobuf version](https://img.shields.io/badge/protobuf-4.25.2-informational)-->
![protobuf version](https://img.shields.io/badge/protobuf-5.26.1-informational)-->

<!-- [![Github all releases](https://img.shields.io/github/downloads/scito/extract_otp_secrets/total.svg)](https://GitHub.com/scito/extract_otp_secrets/releases/) -->

Expand Down Expand Up @@ -235,7 +235,7 @@ OpenCV requires [Visual C++ redistributable 2015](https://www.microsoft.com/en-u

## Program help: arguments and options

<pre>usage: extract_otp_secrets.py [-h] [--csv FILE] [--keepass FILE] [--json FILE] [--txt FILE] [--printqr] [--saveqr DIR] [--camera NUMBER] [--qr {ZBAR,QREADER,QREADER_DEEP,CV2,CV2_WECHAT}] [-i] [--no-color] [--version] [-d | -v | -q] [infile ...]
<pre>usage: extract_otp_secrets.py [-h] [--csv FILE] [--keepass FILE] [--json FILE] [--txt FILE] [--urls FILE] [--printqr] [--saveqr DIR] [--camera NUMBER] [--qr {ZBAR,QREADER,QREADER_DEEP,CV2,CV2_WECHAT}] [-i] [--no-color] [--version] [-d | -v | -q] [infile ...]

Extracts one time password (OTP) secrets from QR codes exported by two-factor authentication (2FA) apps
If no infiles are provided, a GUI window starts and QR codes are captured from the camera.
Expand All @@ -246,10 +246,11 @@ positional arguments:

options:
-h, --help show this help message and exit
--csv FILE, -c FILE export csv file or - for stdout
--csv FILE, -c FILE export csv file, or - for stdout
--keepass FILE, -k FILE export totp/hotp csv file(s) for KeePass, - for stdout
--json FILE, -j FILE export json file or - for stdout
--txt FILE, -t FILE export txt file or - for stdout
--urls FILE, -u FILE export file with list of otpauth urls, or - for stdout
--printqr, -p print QR code(s) as text to the terminal
--saveqr DIR, -s DIR save QR code(s) as images to directory
--camera NUMBER, -C NUMBER camera number of system (default camera: 0)
Expand Down Expand Up @@ -709,7 +710,7 @@ Command for regeneration of Python code from proto3 message definition file (onl

protoc --plugin=protoc-gen-mypy=path/to/protoc-gen-mypy --python_out=src/protobuf_generated_python --mypy_out=src/protobuf_generated_python src/google_auth.proto

The generated protobuf Python code was generated by protoc 25.2 (https://github.com/protocolbuffers/protobuf/releases/tag/v25.2).
The generated protobuf Python code was generated by protoc 26.1 (https://github.com/protocolbuffers/protobuf/releases/tag/v26.1).

For Python type hint generation the [mypy-protobuf](https://github.com/nipunn1313/mypy-protobuf) package is used.

Expand Down
33 changes: 30 additions & 3 deletions src/extract_otp_secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ def main(sys_args: list[str]) -> None:
write_keepass_csv(args.keepass, otps)
write_json(args.json, otps)
write_txt(args.txt, otps, True)
write_urls(args.urls, otps)


# workaround for PYTHON <= 3.9 use: pb.MigrationPayload | None
Expand Down Expand Up @@ -280,10 +281,11 @@ def parse_args(sys_args: list[str]) -> Args:
epilog=example_text)
arg_parser.add_argument('infile', help="""a) file or - for stdin with 'otpauth-migration://...' URLs separated by newlines, lines starting with # are ignored;
b) image file containing a QR code or = for stdin for an image containing a QR code""", nargs='*' if cv2_available else '+')
arg_parser.add_argument('--csv', '-c', help='export csv file or - for stdout', metavar=('FILE'))
arg_parser.add_argument('--csv', '-c', help='export csv file, or - for stdout', metavar=('FILE'))
arg_parser.add_argument('--keepass', '-k', help='export totp/hotp csv file(s) for KeePass, - for stdout', metavar=('FILE'))
arg_parser.add_argument('--json', '-j', help='export json file or - for stdout', metavar=('FILE'))
arg_parser.add_argument('--txt', '-t', help='export txt file or - for stdout', metavar=('FILE'))
arg_parser.add_argument('--urls', '-u', help='export file with list of otpauth urls, or - for stdout', metavar=('FILE'))
arg_parser.add_argument('--printqr', '-p', help='print QR code(s) as text to the terminal', action='store_true')
arg_parser.add_argument('--saveqr', '-s', help='save QR code(s) as images to directory', metavar=('DIR'))
if cv2_available:
Expand All @@ -301,13 +303,14 @@ def parse_args(sys_args: list[str]) -> Args:
output_group.add_argument('-q', '--quiet', help='no stdout output, except output set by -', action='store_true')
args = arg_parser.parse_args(sys_args)
colored = not args.no_color
if args.csv == '-' or args.json == '-' or args.keepass == '-' or args.txt == '-':
if args.csv == '-' or args.json == '-' or args.keepass == '-' or args.txt == '-' or args.urls == '-':
args.quiet = args.q = True

verbose = args.verbose if args.verbose else LogLevel.NORMAL
if args.debug:
verbose = LogLevel.DEBUG
log_debug('Debug mode start')
log_debug(args)
quiet = True if args.quiet else False
if verbose: print(f"QReader installed: {cv2_available}")
if cv2_available:
Expand Down Expand Up @@ -378,7 +381,7 @@ def extract_otps_from_camera(args: Args) -> Otps:

cv2_print_text(img, f"Mode: {qr_mode.name} (Hit SPACE to change)", 0, TextPosition.LEFT, FONT_COLOR, 20)
cv2_print_text(img, "Press ESC to quit", 1, TextPosition.LEFT, FONT_COLOR, 17)
cv2_print_text(img, "Press C/J/K/T to save as csv/json/keepass/txt file", 2, TextPosition.LEFT, FONT_COLOR, None)
cv2_print_text(img, "Press c,j,k,t,u to save as csv/json/keepass/txt/urls file", 2, TextPosition.LEFT, FONT_COLOR, None)

cv2_print_text(img, f"{len(otp_urls)} QR code{'s'[:len(otp_urls) != 1]} captured", 0, TextPosition.RIGHT, FONT_COLOR)
cv2_print_text(img, f"{len(otps)} otp{'s'[:len(otps) != 1]} extracted", 1, TextPosition.RIGHT, FONT_COLOR)
Expand Down Expand Up @@ -484,6 +487,18 @@ def cv2_handle_pressed_keys(qr_mode: QRMode, otps: Otps) -> Tuple[bool, QRMode]:
tk_root.update()
if len(file_name) > 0:
write_txt(file_name, otps, True)
elif (key == ord('u') or key == ord('U')) and is_not_headless():
if has_no_otps_show_warning(otps):
pass
else:
file_name = tkinter.filedialog.asksaveasfilename(
title="Save extracted otp secrets as list of urls",
defaultextension='.txt',
filetypes=[('Text', '*.txt'), ('All', '*.*')]
)
tk_root.update()
if len(file_name) > 0:
write_urls(file_name, otps)
elif key == 32:
qr_mode = next_valid_qr_mode(qr_mode, zbar_available)
if verbose >= LogLevel.MORE_VERBOSE: print(f"QR reading mode: {qr_mode}")
Expand Down Expand Up @@ -664,6 +679,10 @@ def print_otp(otp: Otp, out: Optional[TextIO] = None) -> None:
print(otp['url'], file=out)


def write_url(otp: Otp, out: Optional[TextIO] = None) -> None:
print(otp['url'], file=out)


def save_qr_image(otp: Otp, dir: str, j: int) -> str:
if not (os.path.exists(dir)): os.makedirs(dir, exist_ok=True)
pattern = re.compile(r'[\W_]+')
Expand Down Expand Up @@ -697,6 +716,14 @@ def write_txt(file: str, otps: Otps, write_qr: bool = False) -> None:
print(file=outfile)


def write_urls(file: str, otps: Otps) -> None:
if file and len(file) > 0 and len(otps) > 0:
with open_file_or_stdout(file) as outfile:
for otp in otps:
write_url(otp, outfile)
if not quiet: print(f"Exported {len(otps)} otp{'s'[:len(otps) != 1]} to otpauth url list file {file}")


def write_csv(file: str, otps: Otps) -> None:
if file and len(file) > 0 and len(otps) > 0:
with open_file_or_stdout_for_csv(file) as outfile:
Expand Down
6 changes: 3 additions & 3 deletions src/protobuf_generated_python/google_auth_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions tests/data/url_list_output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
otpauth://totp/pi%40raspberrypi?secret=7KSQL2JTUDIS5EF65KLMRQIIGY&issuer=raspberrypi
otpauth://totp/pi%40raspberrypi?secret=7KSQL2JTUDIS5EF65KLMRQIIGY
otpauth://totp/pi%40raspberrypi?secret=7KSQL2JTUDIS5EF65KLMRQIIGY
otpauth://totp/pi%40raspberrypi?secret=7KSQL2JTUDIS5EF65KLMRQIIGY&issuer=raspberrypi
otpauth://hotp/hotp%20demo?secret=7KSQL2JTUDIS5EF65KLMRQIIGY&counter=4
otpauth://totp/encoding%3A%20%C2%BF%C3%A4%C3%84%C3%A9%C3%89%3F%20%28demo%29?secret=7KSQL2JTUDIS5EF65KLMRQIIGY
31 changes: 31 additions & 0 deletions tests/extract_otp_secrets_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,37 @@ def test_extract_txt_stdout_only_comments(capsys: pytest.CaptureFixture[str]) ->
assert captured.err == ''


def test_extract_urls(capsys: pytest.CaptureFixture[str], tmp_path: pathlib.Path) -> None:
# Arrange
output_file = str(tmp_path / 'test_example_url_list.txt')

# Act
extract_otp_secrets.main(['-q', '-u', output_file, 'example_export.txt'])

# Assert
expected_txt = read_file_to_str('tests/data/url_list_output.txt')
actual_txt = read_file_to_str(output_file)

assert actual_txt == expected_txt

captured = capsys.readouterr()

assert captured.out == ''
assert captured.err == ''


def test_extract_urls_stdout(capsys: pytest.CaptureFixture[str]) -> None:
# Act
extract_otp_secrets.main(['-u', '-', 'example_export.txt'])

# Assert
expected_txt = read_file_to_str('tests/data/url_list_output.txt')
captured = capsys.readouterr()

assert captured.out == expected_txt
assert captured.err == ''


def test_extract_not_encoded_plus(capsys: pytest.CaptureFixture[str]) -> None:
# Act
extract_otp_secrets.main(['tests/data/test_plus_problem_export.txt'])
Expand Down

0 comments on commit 6bdcaf3

Please sign in to comment.