Compare commits
525 commits
Author | SHA1 | Date | |
---|---|---|---|
|
96a30c6150 | ||
|
dd153a617c | ||
|
28c7a797cf | ||
|
c2a72fee6c | ||
|
602acc6641 | ||
|
b4564b7d5e | ||
|
d30ba017c9 | ||
|
37ae7c76a6 | ||
|
ef72bd898c | ||
|
52044c95bb | ||
|
b24a7415f6 | ||
|
8d54a1254a | ||
|
ab5cb00ee3 | ||
|
c7fefc1452 | ||
|
a64f7d4134 | ||
|
0a41e8b042 | ||
|
d3c1dfb3d5 | ||
|
a8d3f3fc99 | ||
|
5e24031719 | ||
|
d67e925a47 | ||
|
4c9f494ed3 | ||
|
46a1c2ed04 | ||
|
ad146c97c9 | ||
|
d96b6e65a6 | ||
|
84da432b2d | ||
|
2629b0b715 | ||
|
f7a4ce6133 | ||
|
c5d51b5174 | ||
|
8394baa157 | ||
|
25280abc62 | ||
|
bdc8d3c526 | ||
|
bcac6fa7a3 | ||
|
225b53d719 | ||
|
4ea44151b9 | ||
|
68dcedaeb7 | ||
|
9358fb60c9 | ||
|
9795453a04 | ||
|
8f7ca33e8a | ||
|
fca7e53a0d | ||
|
166b7a908c | ||
|
63805293ff | ||
|
d18dd378c3 | ||
|
41bf8a45ec | ||
|
37b7b75077 | ||
|
8bfab8d2a2 | ||
|
a9e39b4215 | ||
|
a50109ad63 | ||
|
7eb62cfa7b | ||
|
94a3210f09 | ||
|
6d4915a39c | ||
|
e529b76c97 | ||
|
47894cc217 | ||
|
c809d1e725 | ||
|
0c256a0e05 | ||
|
04295dc742 | ||
|
4fb0e4cfcd | ||
|
e032008fdb | ||
|
5178238f8d | ||
|
90ba3b64b5 | ||
|
14589e70d5 | ||
|
a9af82da13 | ||
|
f952ed5b1b | ||
|
97a9040eb8 | ||
|
544608a330 | ||
|
9f26e6b241 | ||
|
2c63350bcf | ||
|
29aca56067 | ||
|
f2821d2837 | ||
|
84993dedae | ||
|
4348529ffd | ||
|
40d81f360b | ||
|
84f488a7bd | ||
|
34d17a2462 | ||
|
e960b7cedc | ||
|
3957177709 | ||
|
f0e66a4651 | ||
|
94a7ca8bc8 | ||
|
8bd0079ffc | ||
|
aa5168e663 | ||
|
28733e029d | ||
|
2114d0a98d | ||
|
fff3427d8d | ||
|
d7173b4efb | ||
|
96f342137a | ||
|
d1ff150cbf | ||
|
9c6d10dc1f | ||
|
d31a1435c2 | ||
|
e5b76fe4a4 | ||
|
942ac6f35f | ||
|
e1a27e8b23 | ||
|
eb51a7a2a7 | ||
|
17d19c53c0 | ||
|
7c985f62ff | ||
|
df47ff1823 | ||
|
d9261d0ac8 | ||
|
b98cd2d4c7 | ||
|
3fdf2fdbc9 | ||
|
7635e5ca10 | ||
|
a2b3f18d76 | ||
|
d3b9471e95 | ||
|
391371002b | ||
|
06af8c2219 | ||
|
8f4ec79144 | ||
|
969baeed4c | ||
|
d5218d770e | ||
|
26c6916e79 | ||
|
11b36c566e | ||
|
7e94f76653 | ||
|
fe663cf43f | ||
|
1d99bae469 | ||
|
e25ab17fd6 | ||
|
6f4064ff58 | ||
|
3146d4824c | ||
|
55a8bee695 | ||
|
b9d9179537 | ||
|
f05f423d23 | ||
|
4cc4d2370c | ||
|
b3c6639146 | ||
|
71d399f645 | ||
|
4990d23c32 | ||
|
6c4af1c9de | ||
|
f7f9c916ba | ||
|
b30eb050de | ||
|
3cb0869597 | ||
|
06ea485e55 | ||
|
dc591212bb | ||
|
9bfd07c6b4 | ||
|
39fa6bb4a1 | ||
|
0341db0046 | ||
|
201288952a | ||
|
4b92d46049 | ||
|
0b8de57e3a | ||
|
6af4374da3 | ||
|
0d24d12c55 | ||
|
09fd78a5a5 | ||
|
79c01833e8 | ||
|
ad5a9b3131 | ||
|
7d39da8213 | ||
|
4fed9486de | ||
|
f8ae7d4e0e | ||
|
da44f49c56 | ||
|
46ddaad281 | ||
|
fdf54e6498 | ||
|
a062e718d7 | ||
|
ac7717bde8 | ||
|
d2ba7d8f1d | ||
|
93a5fe643c | ||
|
1632e2f10e | ||
|
d87caa06f6 | ||
|
f1855ba7c0 | ||
|
a5be7b26bb | ||
|
bff16bd341 | ||
|
64697b6808 | ||
|
7e04a4240a | ||
|
2dc6376533 | ||
|
f080e35971 | ||
|
2d180f0209 | ||
|
2934dd3927 | ||
|
6a5b8d5573 | ||
|
a72126ffcd | ||
|
fe0d6e9aca | ||
|
9835b8a52f | ||
|
3eb17d78d2 | ||
|
4deff5f633 | ||
|
cbc46ad8eb | ||
|
8defefb11e | ||
|
7950e43f70 | ||
|
bd0d1f1fba | ||
|
e4eabdcdd3 | ||
|
ac3120b016 | ||
|
ee670c41c0 | ||
|
ef382c1dce | ||
|
bfd0667f3a | ||
|
75fcf3c456 | ||
|
bf553ba251 | ||
|
b277e53099 | ||
|
4ba0459bb6 | ||
|
3457f9cb43 | ||
|
2d4f9bb25c | ||
|
b4e5574815 | ||
|
15bb6230f0 | ||
|
8366173eb1 | ||
|
99f977d7df | ||
|
911ead0242 | ||
|
9def58a39c | ||
|
c86eedd63c | ||
|
932c98def5 | ||
|
daa930fbee | ||
|
27adb3d019 | ||
|
5634cf82ee | ||
|
cae60f6ed6 | ||
|
738e8f1664 | ||
|
b5f4364733 | ||
|
2a5284f678 | ||
|
dcf1779f39 | ||
|
d3099d7686 | ||
|
85c4662a61 | ||
|
5599e28c9f | ||
|
ea7bd32ec7 | ||
|
409518f455 | ||
|
8c453585d5 | ||
|
7f0d5ca8ab | ||
|
db6557ca0d | ||
|
9f1d692d6d | ||
|
0d90792c47 | ||
|
980a14deb1 | ||
|
2409fac47e | ||
|
352a892075 | ||
|
9657ea6822 | ||
|
f9385ac78e | ||
|
9d1f2a7ee7 | ||
|
c78dd00731 | ||
|
6e31f66dde | ||
|
a9e5d4b1c5 | ||
|
15349156db | ||
|
0b340a3cf1 | ||
|
5a262650a0 | ||
|
ebe31b6df7 | ||
|
230f85b6ac | ||
|
afb1d79aea | ||
|
ad8344460d | ||
|
5303bd69d0 | ||
|
9f338a7af3 | ||
|
cac5f57cc7 | ||
|
3f5fa9a033 | ||
|
a52af3675b | ||
|
fdc61e63d1 | ||
|
610cda120e | ||
|
2678961a4c | ||
|
1ee063f58e | ||
|
1a6ad62a2e | ||
|
eeded86641 | ||
|
deabfc299d | ||
|
d8db1ae9b3 | ||
|
8839a18543 | ||
|
c86e31648a | ||
|
0b84a103e5 | ||
|
d13ca2079e | ||
|
2fc13d40e2 | ||
|
174456226b | ||
|
5e3b2507ab | ||
|
ed9cf91cfb | ||
|
e653ac684f | ||
|
1b7c089fa1 | ||
|
221e64ab8c | ||
|
4a8f7a74d2 | ||
|
8dd10c9b29 | ||
|
aaded51d38 | ||
|
31c08ac206 | ||
|
73281ef069 | ||
|
37539f7679 | ||
|
138f36f562 | ||
|
9f7c8fef68 | ||
|
b040088038 | ||
|
07b9439c27 | ||
|
2f4d1e3cfa | ||
|
14d49d33b1 | ||
|
b55df7ea26 | ||
|
e6847975ff | ||
|
6ef038efc9 | ||
|
abe808b7bf | ||
|
a19f379314 | ||
|
eb08e751b4 | ||
|
57c64b346d | ||
|
2c68f3389d | ||
|
84e2712403 | ||
|
43f73e91bd | ||
|
01498ff069 | ||
|
af0379ac3d | ||
|
944bd2abcd | ||
|
bc0ec74596 | ||
|
6a82b236aa | ||
|
28b4f8ea39 | ||
|
0374525697 | ||
|
fc8653fab7 | ||
|
603d8555ab | ||
|
39707e808a | ||
|
2da17c9a0a | ||
|
be80904f96 | ||
|
a56659e44f | ||
|
ae2049abe8 | ||
|
7dcfbc112f | ||
|
10d97efe16 | ||
|
02014972b4 | ||
|
0bdaa60bbf | ||
|
00ea8dca71 | ||
|
eb3c417ff2 | ||
|
69159b9360 | ||
|
c11593e7e4 | ||
|
b1d559ea00 | ||
|
c6bd5b5dc4 | ||
|
0c797f41f6 | ||
|
d8dec8a29f | ||
|
55ca4dc049 | ||
|
537060fc1f | ||
|
1901994d0e | ||
|
14cd422207 | ||
|
eb199178b1 | ||
|
b4fc32f6f9 | ||
|
145c03e926 | ||
|
c75db0f6e3 | ||
|
86d5f40989 | ||
|
dfdd9563c4 | ||
|
8b1f3a145d | ||
|
743abea8bf | ||
|
d21ceef797 | ||
|
070be5b629 | ||
|
669d8e4dad | ||
|
a48ada2252 | ||
|
4900a2ede7 | ||
|
ccc087b797 | ||
|
c27b01318b | ||
|
6ee4b4eab8 | ||
|
9a5b0fbf6a | ||
|
033ef7a4a1 | ||
|
672e4bbce8 | ||
|
2e96ca8f6e | ||
|
5d38ad84c7 | ||
|
00b6bcb7c7 | ||
|
3bcfaff786 | ||
|
4b9745237d | ||
|
df699f0785 | ||
|
37e818e9ca | ||
|
e6f75fa5aa | ||
|
873e564104 | ||
|
17a4ebe813 | ||
|
1ffe464ed8 | ||
|
4ac3c09338 | ||
|
e4cf29e852 | ||
|
a92cd5b1aa | ||
|
274dd373c2 | ||
|
e6d8de4dc2 | ||
|
a311df931b | ||
|
376b7b8870 | ||
|
3e0397ace7 | ||
|
d285a4ba3b | ||
|
7c949a75c8 | ||
|
a36544e1ff | ||
|
6fa5e6d78a | ||
|
6d2b10022e | ||
|
bb6c733999 | ||
|
b941415715 | ||
|
add51351c1 | ||
|
86733d50a8 | ||
|
6d546e6298 | ||
|
3c05e95fda | ||
|
5153bcd1dc | ||
|
692d431fab | ||
|
26184d5544 | ||
|
e9ca3f6a42 | ||
|
a2ab02c3a2 | ||
|
6aab910403 | ||
|
2e6973be01 | ||
|
de3818c5f9 | ||
|
9c4ca31144 | ||
|
a9773bcbc0 | ||
|
f656dc4853 | ||
|
1e2d82afb5 | ||
|
1931e11706 | ||
|
f892f1afdc | ||
|
e5ee4b64de | ||
|
5157a14ff4 | ||
|
ece0f19ec0 | ||
|
69169708ef | ||
|
001e507d30 | ||
|
c119484c1f | ||
|
4e57ce073a | ||
|
c9629f62e3 | ||
|
feac39ae0a | ||
|
5a004efd06 | ||
|
f3e6c11240 | ||
|
140b2abda6 | ||
|
bf0b6d1572 | ||
|
ce2285d617 | ||
|
4e09b98d07 | ||
|
73c3f54051 | ||
|
49a264ba3f | ||
|
fdc606fb0e | ||
|
8722e9f294 | ||
|
71edb794c1 | ||
|
e611e31ad3 | ||
|
58a13d8bab | ||
|
aa1fa6a318 | ||
|
49aea80080 | ||
|
d3cdc309ed | ||
|
e1f86d3750 | ||
|
f1158f9a3d | ||
|
531e69ea88 | ||
|
1b1f12f423 | ||
|
02d8cade2a | ||
|
8f6a1d8345 | ||
|
7d7dd6701e | ||
|
edb2663baf | ||
|
c98ff1c914 | ||
|
dc18f3a7ab | ||
|
4788b330ed | ||
|
18ffc3a4fa | ||
|
cee428b708 | ||
|
ac3811ddbd | ||
|
1b213841e9 | ||
|
2eee5721d9 | ||
|
5da5d32976 | ||
|
f668004305 | ||
|
1825acdbb3 | ||
|
2fa4be52d9 | ||
|
7f7fedf59c | ||
|
1258ef6e97 | ||
|
0bc5ca7016 | ||
|
ca86b44640 | ||
|
f38f9b6e52 | ||
|
d594da3b86 | ||
|
5689431f8c | ||
|
0aabe95375 | ||
|
f5ac96f722 | ||
|
0af027b27e | ||
|
a5f9f7671b | ||
|
c9d9d194b2 | ||
|
d460fa8b12 | ||
|
47be84aaca | ||
|
357d04f34b | ||
|
4e208f1840 | ||
|
3e5a0fa175 | ||
|
2346d04725 | ||
|
d67a93a982 | ||
|
847deafe86 | ||
|
746f76af18 | ||
|
5fdc12bfb8 | ||
|
51fea91577 | ||
|
5379e9572c | ||
|
217a88f0de | ||
|
72c0acfbf1 | ||
|
c3d3f33ec3 | ||
|
555b47b3fb | ||
|
91e2a1b2c6 | ||
|
5cfdb84bc2 | ||
|
ad2cdd2a7e | ||
|
691d927050 | ||
|
c17bdf92a5 | ||
|
bb762b2f47 | ||
|
b2414e0c33 | ||
|
afafe44d60 | ||
|
071d9d7d2d | ||
|
467e669fb8 | ||
|
298d29dc07 | ||
|
db2ec59c07 | ||
|
e0578fce39 | ||
|
38f41b144f | ||
|
58897b6695 | ||
|
2e4058cfca | ||
|
e4d7ea4475 | ||
|
31a888c0e4 | ||
|
8a3408b405 | ||
|
b57bc38341 | ||
|
52d247f102 | ||
|
a808fa1fe6 | ||
|
8b18e9a292 | ||
|
7e7a192ff7 | ||
|
79f8341aad | ||
|
c17a17e1b8 | ||
|
b5ed878659 | ||
|
31cc0f884e | ||
|
afc09a35ac | ||
|
d6cdbd5541 | ||
|
258e758395 | ||
|
2f6647d85e | ||
|
e42d130741 | ||
|
f3910790bb | ||
|
e040630088 | ||
|
8567a06f54 | ||
|
6c34a8f2df | ||
|
ca93b7289c | ||
|
c6d9fd0d75 | ||
|
d6aedb771c | ||
|
67a7b9b0ee | ||
|
fcc56d6d73 | ||
|
7c58e28d56 | ||
|
66731164d6 | ||
|
9aea25ea32 | ||
|
e0a668fa1e | ||
|
cc48bc9537 | ||
|
98d0bb72c5 | ||
|
5e7b614e92 | ||
|
4be38f8854 | ||
|
3dcccd1e63 | ||
|
bbc2f77b30 | ||
|
e3f7d10394 | ||
|
d4c1758f1b | ||
|
489842cc78 | ||
|
8b5d0ef0ff | ||
|
c23db2a5e9 | ||
|
d2bf5478ba | ||
|
d8ffc179e0 | ||
|
c936d9a0ac | ||
|
e47a2173b1 | ||
|
fcc5900494 | ||
|
e9475585ca | ||
|
7385028554 | ||
|
c6ad1255be | ||
|
ca22c634ac | ||
|
34bf68d560 | ||
|
b313b857c8 | ||
|
d64bf5cade | ||
|
36c4b7c819 | ||
|
71bb8e8adc | ||
|
747c09c91a | ||
|
fe6a51030f | ||
|
23257ee615 | ||
|
8ded30e09e | ||
|
bde8a37d3f | ||
|
52b40ab582 | ||
|
e9d9b61024 | ||
|
347322ce26 | ||
|
d7b952b40f | ||
|
4e583530cd | ||
|
a355cb6644 | ||
|
05b944c40b | ||
|
196e4ffdb8 | ||
|
e058586680 | ||
|
3376da2da2 | ||
|
8680d8d4c0 | ||
|
748c9b01d0 | ||
|
4a90c146e5 | ||
|
142f394d98 | ||
|
5b8d581a48 | ||
|
24fefadd4d |
149 changed files with 17430 additions and 1786 deletions
3
.github/FUNDING.yml
vendored
Normal file
3
.github/FUNDING.yml
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
# These are supported funding model platforms
|
||||
|
||||
github: [dyc3]
|
42
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
42
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
|
@ -0,0 +1,42 @@
|
|||
name: Bug Report
|
||||
description: Something isn't working as expected
|
||||
labels: ["bug", "triage"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to fill out this bug report!
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: What version of steamguard-cli are you running? You can find this by running `steamguard --version`. **Do NOT just say "latest", or your issue will be automatically closed.**
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: What did you expect to happen?
|
||||
placeholder: Tell us what you see!
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Steps To Reproduce
|
||||
description: Steps to reproduce the behavior.
|
||||
placeholder: |
|
||||
1. In this environment...
|
||||
2. With this config...
|
||||
3. Run '...'
|
||||
4. See error...
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. Make sure to use `-v debug` or `-v trace`. **If you use `-v trace`, make sure to remove any private information like 2fa secrets!** This will be automatically formatted into code, so no need for backticks.
|
||||
placeholder: |
|
||||
Paste your logs with at least `-v debug` enabled here
|
||||
render: Shell
|
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Q&A and Troubleshooting Support
|
||||
url: https://github.com/dyc3/steamguard-cli/discussions/new?category=q-a
|
||||
about: Please ask and answer questions here.
|
13
.github/ISSUE_TEMPLATE/feature.yml
vendored
Normal file
13
.github/ISSUE_TEMPLATE/feature.yml
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
name: Feature Request
|
||||
description: Suggest an idea for this project
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to fill out this feature request!
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
validations:
|
||||
required: true
|
17
.github/workflows/aur-checker.yml
vendored
Normal file
17
.github/workflows/aur-checker.yml
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
name: AUR Tester
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "32 5 */3 * *"
|
||||
push:
|
||||
branches: [ master, main ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test-install:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Install AUR package
|
||||
run: ./scripts/check-aur.sh
|
89
.github/workflows/release.yml
vendored
89
.github/workflows/release.yml
vendored
|
@ -1,89 +0,0 @@
|
|||
name: Release new version
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'The version number to use'
|
||||
default: '0.0.0.0'
|
||||
# Input has to be provided for the workflow to run
|
||||
required: true
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate version number
|
||||
run: |
|
||||
# validate version structure
|
||||
bash -c '[[ ${{ github.event.inputs.version }} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 1'
|
||||
# ensure version doesn't already exist
|
||||
bash -c 'git rev-parse "v${{ github.event.inputs.version }}" >/dev/null 2>&1 && exit 2 || exit 0'
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.3
|
||||
with:
|
||||
submodules: true
|
||||
- name: Install dependencies
|
||||
run: sudo apt install nuget mono-complete make
|
||||
- name: Update version number, and commit
|
||||
run: |
|
||||
git config --global user.name "Github Actions"
|
||||
git config --global user.email "dyc3@users.noreply.github.com"
|
||||
sed -ri "s/Version\(\"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\"\)/Version\(\"${{ github.event.inputs.version }}\"\)/g" AssemblyInfo.cs
|
||||
git commit -m "Update version" AssemblyInfo.cs
|
||||
- name: Build
|
||||
run: |
|
||||
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
|
||||
make
|
||||
mv build steamguard-cli-v${{ github.event.inputs.version }}
|
||||
tar -cf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz steamguard-cli-v${{ github.event.inputs.version }}
|
||||
- name: Tag and push version commit
|
||||
run: |
|
||||
git push origin master
|
||||
git tag -a "v${{ github.event.inputs.version }}" -m "Release v${{ github.event.inputs.version }}"
|
||||
git push origin "v${{ github.event.inputs.version }}"
|
||||
- name: Upload Build Artifact
|
||||
uses: actions/upload-artifact@v2.2.0
|
||||
with:
|
||||
name: build
|
||||
path: steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
|
||||
deb-package:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.3
|
||||
- name: Download Build Artifact (tar)
|
||||
uses: actions/download-artifact@v2.0.5
|
||||
with:
|
||||
name: build
|
||||
- run: |
|
||||
tar -xf steamguard-cli-v${{ github.event.inputs.version }}.tar.gz
|
||||
mv steamguard-cli-v${{ github.event.inputs.version }} build
|
||||
bash package.sh
|
||||
- name: Upload deb
|
||||
uses: actions/upload-artifact@v2.2.0
|
||||
with:
|
||||
name: deb
|
||||
path: steamguard-cli_${{ github.event.inputs.version }}-0.deb
|
||||
# TODO: update AUR pkgbuild
|
||||
draft:
|
||||
# FIXME: the auto drafter doesn't work
|
||||
needs: [build, deb-package]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download Build Artifact (tar)
|
||||
uses: actions/download-artifact@v2.0.5
|
||||
with:
|
||||
name: build
|
||||
- name: Download Build Artifact (deb)
|
||||
uses: actions/download-artifact@v2.0.5
|
||||
with:
|
||||
name: deb
|
||||
- name: Release Drafter
|
||||
uses: release-drafter/release-drafter@v5.11.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
name: v${{ github.event.inputs.version }}
|
||||
tag: v${{ github.event.inputs.version }}
|
||||
version: ${{ github.event.inputs.version }}
|
||||
publish: false
|
47
.github/workflows/rust.yml
vendored
Normal file
47
.github/workflows/rust.yml
vendored
Normal file
|
@ -0,0 +1,47 @@
|
|||
name: Lint, Build, Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master, main]
|
||||
pull_request:
|
||||
branches: [master, main]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- run: rustup component add clippy rustfmt
|
||||
- uses: actions/checkout@v4
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@v2
|
||||
- name: Check format
|
||||
run: cargo fmt --all -- --check
|
||||
- name: Check
|
||||
run: cargo check --verbose --all-targets --all-features
|
||||
- name: Clippy
|
||||
run: cargo clippy --workspace --no-deps --all-features --all-targets -- -D warnings
|
||||
- name: Validate documentation
|
||||
run: cargo doc --workspace --no-deps --all-features
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features --all-targets --workspace
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target: [x86_64-unknown-linux-musl, x86_64-pc-windows-gnu]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
prefix-key: v0-rust-${{ matrix.target }}
|
||||
- name: Install Cross
|
||||
uses: baptiste0928/cargo-install@v2
|
||||
with:
|
||||
crate: cross
|
||||
- name: Check
|
||||
run: cross check --verbose --all-targets --all-features --target ${{ matrix.target }}
|
6
.gitignore
vendored
6
.gitignore
vendored
|
@ -5,4 +5,8 @@ obj/
|
|||
SteamAuth/SteamAuth/packages/
|
||||
test_maFiles/
|
||||
|
||||
*.deb
|
||||
*.deb
|
||||
*.tar.gz
|
||||
|
||||
target/
|
||||
aur/
|
||||
|
|
3
.gitmodules
vendored
3
.gitmodules
vendored
|
@ -1,3 +0,0 @@
|
|||
[submodule "SteamAuth"]
|
||||
path = SteamAuth
|
||||
url = https://github.com/dyc3/SteamAuth.git
|
64
.vscode/launch.json
vendored
Normal file
64
.vscode/launch.json
vendored
Normal file
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "lldb",
|
||||
"request": "launch",
|
||||
"name": "Debug unit tests in library 'steamguard'",
|
||||
"cargo": {
|
||||
"args": [
|
||||
"test",
|
||||
"--no-run",
|
||||
"--lib",
|
||||
"--package=steamguard"
|
||||
],
|
||||
"filter": {
|
||||
"name": "steamguard",
|
||||
"kind": "lib"
|
||||
}
|
||||
},
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
{
|
||||
"type": "lldb",
|
||||
"request": "launch",
|
||||
"name": "Debug executable 'steamguard-cli'",
|
||||
"cargo": {
|
||||
"args": [
|
||||
"build",
|
||||
"--bin=steamguard",
|
||||
"--package=steamguard-cli"
|
||||
],
|
||||
"filter": {
|
||||
"name": "steamguard",
|
||||
"kind": "bin"
|
||||
}
|
||||
},
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
{
|
||||
"type": "lldb",
|
||||
"request": "launch",
|
||||
"name": "Debug unit tests in executable 'steamguard-cli'",
|
||||
"cargo": {
|
||||
"args": [
|
||||
"test",
|
||||
"--no-run",
|
||||
"--bin=steamguard",
|
||||
"--package=steamguard-cli"
|
||||
],
|
||||
"filter": {
|
||||
"name": "steamguard",
|
||||
"kind": "bin"
|
||||
}
|
||||
},
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}"
|
||||
}
|
||||
]
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
|
||||
[assembly: AssemblyTitle("steamguard-cli")]
|
||||
[assembly: AssemblyDescription("https://github.com/dyc3/steamguard-cli")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("steamguard-cli")]
|
||||
[assembly: AssemblyCopyright("")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
|
||||
[assembly: AssemblyVersion("0.3.5.1")]
|
||||
[assembly: AssemblyFileVersion("0.3.5.1")]
|
4053
Cargo.lock
generated
Normal file
4053
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
84
Cargo.toml
Normal file
84
Cargo.toml
Normal file
|
@ -0,0 +1,84 @@
|
|||
[workspace]
|
||||
|
||||
members = ["steamguard"]
|
||||
|
||||
[package]
|
||||
name = "steamguard-cli"
|
||||
version = "0.14.0"
|
||||
authors = ["dyc3 (Carson McManus) <carson.mcmanus1@gmail.com>"]
|
||||
edition = "2021"
|
||||
description = "A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||
keywords = ["steam", "2fa", "steamguard", "authentication", "cli"]
|
||||
categories = ["command-line-utilities"]
|
||||
repository = "https://github.com/dyc3/steamguard-cli"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
||||
[features]
|
||||
default = ["qr", "updater", "keyring"]
|
||||
qr = ["dep:qrcode"]
|
||||
updater = ["dep:update-informer"]
|
||||
keyring = ["dep:keyring"]
|
||||
|
||||
# [[bin]]
|
||||
# name = "steamguard-cli"
|
||||
# filename = "steamguard" # TODO: uncomment when https://github.com/rust-lang/cargo/issues/9778 is stablized.
|
||||
|
||||
[[bin]]
|
||||
name = "steamguard"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "^1.0"
|
||||
base64 = "0.22.1"
|
||||
text_io = "0.1.8"
|
||||
rpassword = "7.2.0"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"blocking",
|
||||
"json",
|
||||
"cookies",
|
||||
"gzip",
|
||||
"rustls-tls",
|
||||
] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
rsa = "0.9.2"
|
||||
rand = "0.8.5"
|
||||
clap = { version = "4.5.4", features = ["derive", "cargo", "env"] }
|
||||
clap_complete = "4.5.2"
|
||||
log = "0.4.19"
|
||||
stderrlog = "0.6"
|
||||
cookie = "0.18"
|
||||
regex = "1"
|
||||
lazy_static = "1.4.0"
|
||||
uuid = { version = "1.8", features = ["v4"] }
|
||||
steamguard = { version = "^0.14.0", path = "./steamguard" }
|
||||
dirs = "5.0.1"
|
||||
aes = { version = "0.8.3", features = ["zeroize"] }
|
||||
thiserror = "1.0.61"
|
||||
crossterm = { version = "0.23.2", features = ["event-stream"] }
|
||||
qrcode = { version = "0.14.0", optional = true }
|
||||
gethostname = "0.4.3"
|
||||
secrecy = { version = "0.8", features = ["serde"] }
|
||||
zeroize = { version = "^1.6.0", features = ["std", "zeroize_derive"] }
|
||||
serde_path_to_error = "0.1.11"
|
||||
update-informer = { version = "1.0.0", optional = true, default-features = false, features = [
|
||||
"github",
|
||||
] }
|
||||
phonenumber = "0.3"
|
||||
cbc = { version = "0.1.2", features = ["std", "zeroize"] }
|
||||
inout = { version = "0.1.3", features = ["std"] }
|
||||
keyring = { version = "2.0.4", optional = true }
|
||||
argon2 = { version = "0.5.0", features = ["std", "zeroize"] }
|
||||
pbkdf2 = { version = "0.12.1", features = ["parallel"] }
|
||||
sha1 = "0.10.5"
|
||||
rayon = "1.7.0"
|
||||
rqrr = "0.7.1"
|
||||
image = "0.25"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
proptest = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = true
|
687
LICENSE
687
LICENSE
|
@ -1,21 +1,674 @@
|
|||
MIT License
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (c) 2017 Carson McManus
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
|
546
Manifest.cs
546
Manifest.cs
|
@ -1,546 +0,0 @@
|
|||
using Newtonsoft.Json;
|
||||
using SteamAuth;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace SteamGuard
|
||||
{
|
||||
public class Manifest
|
||||
{
|
||||
private const int PBKDF2_ITERATIONS = 50000; //Set to 50k to make program not unbearably slow. May increase in future.
|
||||
private const int SALT_LENGTH = 8;
|
||||
private const int KEY_SIZE_BYTES = 32;
|
||||
private const int IV_LENGTH = 16;
|
||||
|
||||
[JsonProperty("encrypted")]
|
||||
public bool Encrypted { get; set; }
|
||||
|
||||
[JsonProperty("first_run")]
|
||||
public bool FirstRun { get; set; } = true;
|
||||
|
||||
[JsonProperty("entries")]
|
||||
public List<ManifestEntry> Entries { get; set; }
|
||||
|
||||
[JsonProperty("periodic_checking")]
|
||||
public bool PeriodicChecking { get; set; } = false;
|
||||
|
||||
[JsonProperty("periodic_checking_interval")]
|
||||
public int PeriodicCheckingInterval { get; set; } = 5;
|
||||
|
||||
[JsonProperty("periodic_checking_checkall")]
|
||||
public bool CheckAllAccounts { get; set; } = false;
|
||||
|
||||
[JsonProperty("auto_confirm_market_transactions")]
|
||||
public bool AutoConfirmMarketTransactions { get; set; } = false;
|
||||
|
||||
[JsonProperty("auto_confirm_trades")]
|
||||
public bool AutoConfirmTrades { get; set; } = false;
|
||||
|
||||
private static Manifest _manifest { get; set; }
|
||||
|
||||
public static Manifest GetManifest(bool forceLoad = false)
|
||||
{
|
||||
// Check if already staticly loaded
|
||||
if (_manifest != null && !forceLoad)
|
||||
{
|
||||
return _manifest;
|
||||
}
|
||||
|
||||
// Find config dir and manifest file
|
||||
string maFile = Path.Combine(Program.SteamGuardPath, "manifest.json");
|
||||
|
||||
// If there's no config dir, create it
|
||||
if (!Directory.Exists(Program.SteamGuardPath))
|
||||
{
|
||||
_manifest = _generateNewManifest();
|
||||
return _manifest;
|
||||
}
|
||||
|
||||
// If there's no manifest, create it
|
||||
if (!File.Exists(maFile))
|
||||
{
|
||||
Utils.Verbose("warn: No manifest file found at {0}", maFile);
|
||||
bool? createNewManifest = Program.SteamGuardPath ==
|
||||
Program.defaultSteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME")) ? true : (bool?) null;
|
||||
while (createNewManifest == null)
|
||||
{
|
||||
Console.Write($"Generate new manifest.json in {Program.SteamGuardPath}? [Y/n]");
|
||||
var answer = Console.ReadLine();
|
||||
if (answer != null)
|
||||
createNewManifest = !answer.StartsWith("n") && !answer.StartsWith("N");
|
||||
}
|
||||
if ((bool) createNewManifest)
|
||||
{
|
||||
_manifest = _generateNewManifest(true);
|
||||
return _manifest;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string manifestContents = File.ReadAllText(maFile);
|
||||
_manifest = JsonConvert.DeserializeObject<Manifest>(manifestContents);
|
||||
|
||||
if (_manifest.Encrypted && _manifest.Entries.Count == 0)
|
||||
{
|
||||
_manifest.Encrypted = false;
|
||||
_manifest.Save();
|
||||
}
|
||||
|
||||
_manifest.RecomputeExistingEntries();
|
||||
|
||||
Utils.Verbose($"{_manifest.Entries.Count} accounts loaded");
|
||||
return _manifest;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("error: Could not open manifest file: {0}", ex.ToString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Manifest _generateNewManifest(bool scanDir = false)
|
||||
{
|
||||
Utils.Verbose("Generating new manifest...");
|
||||
|
||||
// No directory means no manifest file anyways.
|
||||
Manifest newManifest = new Manifest();
|
||||
newManifest.Encrypted = false;
|
||||
newManifest.PeriodicCheckingInterval = 5;
|
||||
newManifest.PeriodicChecking = false;
|
||||
newManifest.AutoConfirmMarketTransactions = false;
|
||||
newManifest.AutoConfirmTrades = false;
|
||||
newManifest.Entries = new List<ManifestEntry>();
|
||||
newManifest.FirstRun = true;
|
||||
|
||||
// Take a pre-manifest version and generate a manifest for it.
|
||||
if (scanDir)
|
||||
{
|
||||
if (Directory.Exists(Program.SteamGuardPath))
|
||||
{
|
||||
DirectoryInfo dir = new DirectoryInfo(Program.SteamGuardPath);
|
||||
var files = dir.GetFiles();
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (file.Extension != ".maFile") continue;
|
||||
|
||||
string contents = File.ReadAllText(file.FullName);
|
||||
try
|
||||
{
|
||||
SteamGuardAccount account = JsonConvert.DeserializeObject<SteamGuardAccount>(contents);
|
||||
ManifestEntry newEntry = new ManifestEntry()
|
||||
{
|
||||
Filename = file.Name,
|
||||
SteamID = account.Session.SteamID
|
||||
};
|
||||
newManifest.Entries.Add(newEntry);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Utils.Verbose("warn: {0}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
if (newManifest.Entries.Count > 0)
|
||||
{
|
||||
newManifest.Save();
|
||||
newManifest.PromptSetupPassKey(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newManifest.Save())
|
||||
{
|
||||
return newManifest;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public class IncorrectPassKeyException : Exception { }
|
||||
public class ManifestNotEncryptedException : Exception { }
|
||||
|
||||
// TODO: move PromptForPassKey to Program.cs
|
||||
// TODO: make PromptForPassKey more secure
|
||||
public string PromptForPassKey()
|
||||
{
|
||||
if (!this.Encrypted)
|
||||
{
|
||||
throw new ManifestNotEncryptedException();
|
||||
}
|
||||
|
||||
bool passKeyValid = false;
|
||||
string passKey = "";
|
||||
while (!passKeyValid)
|
||||
{
|
||||
Console.WriteLine("Please enter encryption password: ");
|
||||
passKey = Utils.ReadLineSecure();
|
||||
if (passKey == "")
|
||||
continue;
|
||||
passKeyValid = this.VerifyPasskey(passKey);
|
||||
if (!passKeyValid)
|
||||
{
|
||||
Console.WriteLine("Incorrect.");
|
||||
}
|
||||
}
|
||||
return passKey;
|
||||
}
|
||||
|
||||
// TODO: move PromptSetupPassKey to Program.cs
|
||||
public string PromptSetupPassKey(bool inAccountSetupProcess = false)
|
||||
{
|
||||
if (inAccountSetupProcess)
|
||||
{
|
||||
Console.Write("Would you like to use encryption? [Y/n] ");
|
||||
string doEncryptAnswer = Console.ReadLine();
|
||||
if (doEncryptAnswer == "n" || doEncryptAnswer == "N")
|
||||
{
|
||||
Console.WriteLine("WARNING: You chose to not encrypt your files. Doing so imposes a security risk for yourself. If an attacker were to gain access to your computer, they could completely lock you out of your account and steal all your items.");
|
||||
Console.WriteLine("You may add encryption later using the --encrypt argument.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
string newPassKey = "";
|
||||
string confirmPassKey = "";
|
||||
do
|
||||
{
|
||||
Console.Write("Enter" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
|
||||
newPassKey = Utils.ReadLineSecure();
|
||||
Console.Write("Confirm" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
|
||||
confirmPassKey = Utils.ReadLineSecure();
|
||||
|
||||
if (newPassKey != confirmPassKey)
|
||||
{
|
||||
Console.WriteLine("Passkeys do not match.");
|
||||
}
|
||||
} while (newPassKey != confirmPassKey || newPassKey == "");
|
||||
|
||||
return newPassKey;
|
||||
}
|
||||
|
||||
public SteamAuth.SteamGuardAccount[] GetAllAccounts(string passKey = null, int limit = -1)
|
||||
{
|
||||
if (passKey == null && this.Encrypted) return new SteamGuardAccount[0];
|
||||
|
||||
List<SteamAuth.SteamGuardAccount> accounts = new List<SteamAuth.SteamGuardAccount>();
|
||||
foreach (var entry in this.Entries)
|
||||
{
|
||||
var account = GetAccount(entry, passKey);
|
||||
if (account == null) continue;
|
||||
accounts.Add(account);
|
||||
|
||||
if (limit != -1 && limit >= accounts.Count)
|
||||
break;
|
||||
}
|
||||
|
||||
return accounts.ToArray();
|
||||
}
|
||||
|
||||
public SteamGuardAccount GetAccount(ManifestEntry entry, string passKey = null)
|
||||
{
|
||||
string fileText = "";
|
||||
Stream stream = null;
|
||||
RijndaelManaged aes256;
|
||||
|
||||
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
|
||||
if (this.Encrypted)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream(Convert.FromBase64String(File.ReadAllText(filename)));
|
||||
byte[] key = GetEncryptionKey(passKey, entry.Salt);
|
||||
|
||||
aes256 = new RijndaelManaged
|
||||
{
|
||||
IV = Convert.FromBase64String(entry.IV),
|
||||
Key = key,
|
||||
Padding = PaddingMode.PKCS7,
|
||||
Mode = CipherMode.CBC
|
||||
};
|
||||
|
||||
ICryptoTransform decryptor = aes256.CreateDecryptor(aes256.Key, aes256.IV);
|
||||
stream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
|
||||
Utils.Verbose($"Decrypting {filename}...");
|
||||
}
|
||||
else
|
||||
{
|
||||
FileStream fileStream = File.OpenRead(filename);
|
||||
stream = fileStream;
|
||||
}
|
||||
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
fileText = reader.ReadToEnd();
|
||||
}
|
||||
stream.Close();
|
||||
|
||||
return JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(fileText);
|
||||
}
|
||||
|
||||
public bool VerifyPasskey(string passkey)
|
||||
{
|
||||
if (!this.Encrypted || this.Entries.Count == 0) return true;
|
||||
|
||||
var accounts = this.GetAllAccounts(passkey, 1);
|
||||
return accounts != null && accounts.Length == 1;
|
||||
}
|
||||
|
||||
public bool RemoveAccount(SteamGuardAccount account, bool deleteMaFile = true)
|
||||
{
|
||||
ManifestEntry entry = (from e in this.Entries where e.SteamID == account.Session.SteamID select e).FirstOrDefault();
|
||||
if (entry == null) return true; // If something never existed, did you do what they asked?
|
||||
|
||||
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
|
||||
this.Entries.Remove(entry);
|
||||
|
||||
if (this.Entries.Count == 0)
|
||||
{
|
||||
this.Encrypted = false;
|
||||
}
|
||||
|
||||
if (this.Save() && deleteMaFile)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(filename);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool SaveAccount(SteamGuardAccount account, bool encrypt, string passKey = null, string salt = null, string iV = null)
|
||||
{
|
||||
if (encrypt && (String.IsNullOrEmpty(passKey) || String.IsNullOrEmpty(salt) || String.IsNullOrEmpty(iV))) return false;
|
||||
|
||||
string jsonAccount = JsonConvert.SerializeObject(account);
|
||||
|
||||
string filename = account.Session.SteamID.ToString() + ".maFile";
|
||||
Utils.Verbose($"Saving account {account.AccountName} to {filename}...");
|
||||
|
||||
ManifestEntry newEntry = new ManifestEntry()
|
||||
{
|
||||
SteamID = account.Session.SteamID,
|
||||
IV = iV,
|
||||
Salt = salt,
|
||||
Filename = filename
|
||||
};
|
||||
|
||||
bool foundExistingEntry = false;
|
||||
for (int i = 0; i < this.Entries.Count; i++)
|
||||
{
|
||||
if (this.Entries[i].SteamID == account.Session.SteamID)
|
||||
{
|
||||
this.Entries[i] = newEntry;
|
||||
foundExistingEntry = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundExistingEntry)
|
||||
{
|
||||
this.Entries.Add(newEntry);
|
||||
}
|
||||
|
||||
bool wasEncrypted = this.Encrypted;
|
||||
this.Encrypted = encrypt;
|
||||
|
||||
if (!this.Save())
|
||||
{
|
||||
this.Encrypted = wasEncrypted;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Stream stream = null;
|
||||
MemoryStream ms = null;
|
||||
RijndaelManaged aes256;
|
||||
|
||||
if (encrypt)
|
||||
{
|
||||
ms = new MemoryStream();
|
||||
byte[] key = GetEncryptionKey(passKey, newEntry.Salt);
|
||||
|
||||
aes256 = new RijndaelManaged
|
||||
{
|
||||
IV = Convert.FromBase64String(newEntry.IV),
|
||||
Key = key,
|
||||
Padding = PaddingMode.PKCS7,
|
||||
Mode = CipherMode.CBC
|
||||
};
|
||||
|
||||
ICryptoTransform encryptor = aes256.CreateEncryptor(aes256.Key, aes256.IV);
|
||||
stream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
|
||||
}
|
||||
else
|
||||
{
|
||||
// An unencrypted maFile is shorter than the encrypted version,
|
||||
// so when an unencrypted maFile gets written this way, the file does not get wiped
|
||||
// leaving encrypted text after the final } bracket. Deleting and recreating the file fixes this.
|
||||
File.Delete(Path.Combine(Program.SteamGuardPath, newEntry.Filename));
|
||||
stream = File.OpenWrite(Path.Combine(Program.SteamGuardPath, newEntry.Filename)); // open or create
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(stream))
|
||||
{
|
||||
writer.Write(jsonAccount);
|
||||
}
|
||||
|
||||
if (encrypt)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(Program.SteamGuardPath, newEntry.Filename), Convert.ToBase64String(ms.ToArray()));
|
||||
}
|
||||
|
||||
stream.Close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Utils.Verbose("error: {0}", ex.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Save()
|
||||
{
|
||||
string filename = Path.Combine(Program.SteamGuardPath, "manifest.json");
|
||||
if (!Directory.Exists(Program.SteamGuardPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
Utils.Verbose("Creating {0}", Program.SteamGuardPath);
|
||||
Directory.CreateDirectory(Program.SteamGuardPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Utils.Verbose($"error: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string contents = JsonConvert.SerializeObject(this);
|
||||
File.WriteAllText(filename, contents);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Utils.Verbose($"error: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RecomputeExistingEntries()
|
||||
{
|
||||
List<ManifestEntry> newEntries = new List<ManifestEntry>();
|
||||
|
||||
foreach (var entry in this.Entries)
|
||||
{
|
||||
string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
newEntries.Add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
this.Entries = newEntries;
|
||||
|
||||
if (this.Entries.Count == 0)
|
||||
{
|
||||
this.Encrypted = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void MoveEntry(int from, int to)
|
||||
{
|
||||
if (from < 0 || to < 0 || from > Entries.Count || to > Entries.Count - 1) return;
|
||||
ManifestEntry sel = Entries[from];
|
||||
Entries.RemoveAt(from);
|
||||
Entries.Insert(to, sel);
|
||||
Save();
|
||||
}
|
||||
|
||||
public class ManifestEntry
|
||||
{
|
||||
[JsonProperty("encryption_iv")]
|
||||
public string IV { get; set; }
|
||||
|
||||
[JsonProperty("encryption_salt")]
|
||||
public string Salt { get; set; }
|
||||
|
||||
[JsonProperty("filename")]
|
||||
public string Filename { get; set; }
|
||||
|
||||
[JsonProperty("steamid")]
|
||||
public ulong SteamID { get; set; }
|
||||
}
|
||||
|
||||
/*
|
||||
Crypto Functions
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// Returns an 8-byte cryptographically random salt in base64 encoding
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetRandomSalt()
|
||||
{
|
||||
byte[] salt = new byte[SALT_LENGTH];
|
||||
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
|
||||
{
|
||||
rng.GetBytes(salt);
|
||||
}
|
||||
return Convert.ToBase64String(salt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a 16-byte cryptographically random initialization vector (IV) in base64 encoding
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetInitializationVector()
|
||||
{
|
||||
byte[] IV = new byte[IV_LENGTH];
|
||||
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
|
||||
{
|
||||
rng.GetBytes(IV);
|
||||
}
|
||||
return Convert.ToBase64String(IV);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <param name="salt"></param>
|
||||
/// <returns></returns>
|
||||
private static byte[] GetEncryptionKey(string password, string salt)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
throw new ArgumentException("Password is empty");
|
||||
}
|
||||
if (string.IsNullOrEmpty(salt))
|
||||
{
|
||||
throw new ArgumentException("Salt is empty");
|
||||
}
|
||||
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), PBKDF2_ITERATIONS))
|
||||
{
|
||||
return pbkdf2.GetBytes(KEY_SIZE_BYTES);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
30
PKGBUILD
Normal file
30
PKGBUILD
Normal file
|
@ -0,0 +1,30 @@
|
|||
# Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
|
||||
# Contributor: Mads Mogensen <mads256h at gmail dot com>
|
||||
|
||||
_pkgname=steamguard-cli
|
||||
pkgname=${_pkgname}-git
|
||||
pkgver=0.14.0.r1.602acc66
|
||||
pkgrel=1
|
||||
pkgdesc="A command line utility to generate Steam 2FA codes and respond to confirmations."
|
||||
arch=('i686' 'x86_64' 'armv6h' 'armv7h')
|
||||
url="https://github.com/dyc3/steamguard-cli"
|
||||
license=('GPL3')
|
||||
makedepends=('rust' 'cargo' 'git')
|
||||
source=("git+https://github.com/dyc3/steamguard-cli.git")
|
||||
sha256sums=('SKIP')
|
||||
options=(!lto)
|
||||
|
||||
pkgver() {
|
||||
cd "${srcdir}/${_pkgname}"
|
||||
git describe --long --tags --match 'v*' | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/v//g'
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "${srcdir}/${_pkgname}"
|
||||
cargo build --release
|
||||
}
|
||||
|
||||
package() {
|
||||
install -Dm755 "${srcdir}/${_pkgname}/target/release/steamguard" "${pkgdir}/usr/bin/steamguard"
|
||||
ln -s "${pkgdir}/usr/bin/steamguard" "${pkgdir}/usr/bin/${_pkgname}"
|
||||
}
|
795
Program.cs
795
Program.cs
|
@ -1,795 +0,0 @@
|
|||
using Newtonsoft.Json;
|
||||
using SteamAuth;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SteamGuard
|
||||
{
|
||||
public static class Program
|
||||
{
|
||||
public const string defaultSteamGuardPath = "~/maFiles";
|
||||
|
||||
public static string SteamGuardPath { get; set; } = defaultSteamGuardPath;
|
||||
public static Manifest Manifest { get; set; }
|
||||
public static SteamGuardAccount[] SteamGuardAccounts { get; set; }
|
||||
public static bool Verbose { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// The main entry point for the application
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
string action = "";
|
||||
string user = "";
|
||||
string passkey = "";
|
||||
|
||||
// Parse cli arguments
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
if (args[i].StartsWith("-"))
|
||||
{
|
||||
// TODO: there's gotta be some framework or tool or something for this
|
||||
if (args[i] == "-v" || args[i] == "--verbose")
|
||||
{
|
||||
Verbose = true;
|
||||
}
|
||||
else if (args[i] == "-m" || args[i] == "--mafiles-path")
|
||||
{
|
||||
i++;
|
||||
if (i < args.Length)
|
||||
{
|
||||
SteamGuardPath = args[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Expected path after {args[i-1]}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (args[i] == "-p" || args[i] == "--passkey")
|
||||
{
|
||||
i++;
|
||||
if (i < args.Length)
|
||||
{
|
||||
passkey = args[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Expected encryption passkey after {args[i-1]}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (args[i] == "--help" || args[i] == "-h")
|
||||
{
|
||||
ShowHelp();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else // Parse as action or username
|
||||
{
|
||||
if (string.IsNullOrEmpty(action))
|
||||
{
|
||||
if (args[i] == "add" || args[i] == "setup")
|
||||
{
|
||||
action = "setup";
|
||||
}
|
||||
else if (args[i] == "trade")
|
||||
{
|
||||
action = "trade";
|
||||
}
|
||||
else if (args[i] == "encrypt")
|
||||
{
|
||||
action = "encrypt";
|
||||
}
|
||||
else if (args[i] == "decrypt")
|
||||
{
|
||||
action = "decrypt";
|
||||
}
|
||||
else if (args[i] == "remove")
|
||||
{
|
||||
action = "remove";
|
||||
}
|
||||
else if (args[i] == "2fa" || args[i] == "code" || args[i] == "generate-code")
|
||||
{
|
||||
action = "generate-code";
|
||||
}
|
||||
else if (args[i] == "accept-all")
|
||||
{
|
||||
action = "accept-all";
|
||||
}
|
||||
else if (string.IsNullOrEmpty(user))
|
||||
{
|
||||
user = args[i];
|
||||
}
|
||||
}
|
||||
else if (string.IsNullOrEmpty(user))
|
||||
{
|
||||
user = args[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(action))
|
||||
{
|
||||
action = "generate-code";
|
||||
}
|
||||
|
||||
// Do some configuring
|
||||
SteamGuardPath = SteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME"));
|
||||
if (!Directory.Exists(SteamGuardPath))
|
||||
{
|
||||
if (SteamGuardPath == defaultSteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME")))
|
||||
{
|
||||
Utils.Verbose("warn: {0} does not exist, creating...", SteamGuardPath);
|
||||
Directory.CreateDirectory(SteamGuardPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("error: {0} does not exist.", SteamGuardPath);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Utils.Verbose($"Action: {action}");
|
||||
if (user.Length > 0)
|
||||
{
|
||||
Utils.Verbose($"User: {user}");
|
||||
}
|
||||
Utils.Verbose($"Passkey: {passkey.Length > 0 ? "[specified]" : "[not specified]" }");
|
||||
Utils.Verbose($"maFiles path: {SteamGuardPath}");
|
||||
|
||||
// Perform desired action
|
||||
switch (action)
|
||||
{
|
||||
case "generate-code":
|
||||
GenerateCode(user, passkey);
|
||||
break;
|
||||
case "encrypt": // Can also be used to change passkey
|
||||
Console.WriteLine(Encrypt(passkey));
|
||||
break;
|
||||
case "decrypt":
|
||||
Console.WriteLine(Decrypt(passkey));
|
||||
break;
|
||||
case "setup":
|
||||
Setup(user, passkey);
|
||||
break;
|
||||
case "trade":
|
||||
Trade(user, passkey);
|
||||
break;
|
||||
case "accept-all":
|
||||
AcceptAllTrades(user, passkey);
|
||||
break;
|
||||
default:
|
||||
Console.WriteLine("error: Unknown action: {0}", action);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
static void ShowHelp()
|
||||
{
|
||||
var descPadding = 26;
|
||||
var descWidth = Console.BufferWidth - descPadding;
|
||||
if (descWidth < 20)
|
||||
descWidth = 20;
|
||||
|
||||
var flags = new Dictionary<string, string>
|
||||
{
|
||||
{ "-h, --help", "Display this help message." },
|
||||
{ "-v, --verbose", "Display some extra information when the program is running." },
|
||||
{ "-m, --mafiles-path", "Specify which folder your maFiles are in. Ex: ~/maFiles" },
|
||||
{ "-p, --passkey", "Specify your encryption passkey." },
|
||||
};
|
||||
var actions = new Dictionary<string, string>
|
||||
{
|
||||
{ "code", "Generate a Steam Guard code for the specified user (if any) and exit. (default)" },
|
||||
{ "encrypt", "Encrypt your maFiles or change your encryption passkey." },
|
||||
{ "decrypt", "Remove encryption from your maFiles." },
|
||||
{ "add", "Set up Steam Guard for 2 factor authentication." },
|
||||
{ "trade", "Opens an interactive prompt to handle trade confirmations." },
|
||||
{ "accept-all", "Accepts all trade confirmations." }
|
||||
};
|
||||
|
||||
Console.WriteLine($"steamguard-cli - v{Assembly.GetExecutingAssembly().GetName().Version}");
|
||||
Console.WriteLine("usage: steamguard ACTION [STEAM USERNAME] [OPTIONS]...");
|
||||
Console.WriteLine();
|
||||
foreach (var flag in flags)
|
||||
{
|
||||
// word wrap the descriptions, if needed
|
||||
var desc = flag.Value;
|
||||
if (desc.Length > descWidth)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < desc.Length; i += descWidth)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append("".PadLeft((flag.Key.StartsWith("--") ? 5 : 2) + descPadding));
|
||||
sb.AppendLine(desc.Substring(i, i + descWidth > desc.Length ? desc.Length - i : descWidth).Trim());
|
||||
}
|
||||
desc = sb.ToString().TrimEnd('\n');
|
||||
}
|
||||
Console.WriteLine($"{(flag.Key.StartsWith("--") ? " " : " " )}{flag.Key.PadRight(descPadding)}{desc}");
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Actions:");
|
||||
foreach (var action in actions)
|
||||
{
|
||||
// word wrap the descriptions, if needed
|
||||
var desc = action.Value;
|
||||
if (desc.Length > descWidth)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < desc.Length; i += descWidth)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append("".PadLeft(descPadding + 2));
|
||||
sb.AppendLine(desc.Substring(i, i + descWidth > desc.Length ? desc.Length - i : descWidth).Trim());
|
||||
}
|
||||
desc = sb.ToString().TrimEnd('\n');
|
||||
}
|
||||
Console.WriteLine($" {action.Key.PadRight(descPadding)}{desc}");
|
||||
}
|
||||
}
|
||||
|
||||
static void GenerateCode(string user = "", string passkey = "")
|
||||
{
|
||||
Utils.Verbose("Aligning time...");
|
||||
TimeAligner.AlignTime();
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
Utils.Verbose("Reading accounts from manifest...");
|
||||
if (Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
|
||||
}
|
||||
else
|
||||
{
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts();
|
||||
}
|
||||
if (SteamGuardAccounts.Length == 0)
|
||||
{
|
||||
Console.WriteLine("error: No accounts read.");
|
||||
return;
|
||||
}
|
||||
Utils.Verbose("Selecting account...");
|
||||
string code = "";
|
||||
for (int i = 0; i < SteamGuardAccounts.Length; i++)
|
||||
{
|
||||
SteamGuardAccount account = SteamGuardAccounts[i];
|
||||
if (user != "")
|
||||
{
|
||||
if (account.AccountName.ToLower() == user.ToLower())
|
||||
{
|
||||
Utils.Verbose("Generating code for {0}...", account.AccountName);
|
||||
code = account.GenerateSteamGuardCode();
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Utils.Verbose("Generating code for {0}...", account.AccountName);
|
||||
code = account.GenerateSteamGuardCode();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (code != "")
|
||||
Console.WriteLine(code);
|
||||
else
|
||||
Console.WriteLine("error: No Steam accounts found in {0}", SteamGuardAccounts);
|
||||
}
|
||||
|
||||
static bool Encrypt(string passkey = "")
|
||||
{
|
||||
// NOTE: in this context, `passkey` refers to the old passkey, if there was one
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
Utils.Verbose("Reading accounts from manifest...");
|
||||
if (Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
|
||||
}
|
||||
else
|
||||
{
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts();
|
||||
}
|
||||
|
||||
string newPassKey = Manifest.PromptSetupPassKey();
|
||||
|
||||
for (int i = 0; i < SteamGuardAccounts.Length; i++)
|
||||
{
|
||||
var account = SteamGuardAccounts[i];
|
||||
var salt = Manifest.GetRandomSalt();
|
||||
var iv = Manifest.GetInitializationVector();
|
||||
bool success = Manifest.SaveAccount(account, true, newPassKey, salt, iv);
|
||||
Utils.Verbose("Encrypted {0}: {1}", account.AccountName, success);
|
||||
if (!success) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool Decrypt(string passkey = "")
|
||||
{
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
Utils.Verbose("Reading accounts from manifest...");
|
||||
if (Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
|
||||
}
|
||||
else
|
||||
{
|
||||
Utils.Verbose("Decryption not required.");
|
||||
return true;
|
||||
}
|
||||
|
||||
for (int i = 0; i < SteamGuardAccounts.Length; i++)
|
||||
{
|
||||
var account = SteamGuardAccounts[i];
|
||||
bool success = Manifest.SaveAccount(account, false);
|
||||
Utils.Verbose("Decrypted {0}: {1}", account.AccountName, success);
|
||||
if (!success) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void Setup(string username = "", string passkey = "")
|
||||
{
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
{
|
||||
Console.Write("Username: ");
|
||||
username = Console.ReadLine();
|
||||
}
|
||||
Console.Write("Password: ");
|
||||
var password = Utils.ReadLineSecure();
|
||||
|
||||
UserLogin login = new UserLogin(username, password);
|
||||
LoginResult loginResult;
|
||||
do
|
||||
{
|
||||
Console.Write($"Logging in {username}... ");
|
||||
loginResult = login.DoLogin();
|
||||
Console.WriteLine(loginResult);
|
||||
switch (loginResult)
|
||||
{
|
||||
case LoginResult.NeedEmail:
|
||||
Console.Write("Email code: ");
|
||||
login.EmailCode = Console.ReadLine();
|
||||
break;
|
||||
case LoginResult.Need2FA:
|
||||
Console.Write("2FA code: ");
|
||||
login.TwoFactorCode = Console.ReadLine();
|
||||
break;
|
||||
case LoginResult.NeedCaptcha:
|
||||
Console.WriteLine($"Please open: https://steamcommunity.com/public/captcha.php?gid={login.CaptchaGID}");
|
||||
Console.Write("Captcha text: ");
|
||||
login.CaptchaText = Console.ReadLine();
|
||||
break;
|
||||
case LoginResult.BadCredentials:
|
||||
Console.WriteLine("error: Bad Credentials");
|
||||
return;
|
||||
case LoginResult.TooManyFailedLogins:
|
||||
Console.WriteLine("error: Too many failed logins. Wait a bit before trying again.");
|
||||
return;
|
||||
case LoginResult.LoginOkay:
|
||||
break;
|
||||
default:
|
||||
Console.WriteLine($"Unknown login result: {loginResult}");
|
||||
break;
|
||||
}
|
||||
} while (loginResult != LoginResult.LoginOkay);
|
||||
|
||||
AuthenticatorLinker linker = new AuthenticatorLinker(login.Session);
|
||||
AuthenticatorLinker.LinkResult linkResult = AuthenticatorLinker.LinkResult.GeneralFailure;
|
||||
|
||||
do
|
||||
{
|
||||
linkResult = linker.AddAuthenticator();
|
||||
Console.WriteLine($"Link result: {linkResult}");
|
||||
switch (linkResult)
|
||||
{
|
||||
case AuthenticatorLinker.LinkResult.MustProvidePhoneNumber:
|
||||
var phonenumber = "";
|
||||
do
|
||||
{
|
||||
Console.WriteLine("Enter your mobile phone number in the following format: +{cC} phoneNumber. EG, +1 123-456-7890");
|
||||
phonenumber = Console.ReadLine();
|
||||
phonenumber = FilterPhoneNumber(phonenumber);
|
||||
linker.PhoneNumber = phonenumber;
|
||||
} while (!PhoneNumberOkay(phonenumber));
|
||||
break;
|
||||
case AuthenticatorLinker.LinkResult.MustConfirmEmail:
|
||||
Console.WriteLine("Check your email. Before continuing, click the link in the email to confirm your phone number. Press enter to continue...");
|
||||
Console.ReadLine();
|
||||
break;
|
||||
case AuthenticatorLinker.LinkResult.MustRemovePhoneNumber:
|
||||
linker.PhoneNumber = null;
|
||||
break;
|
||||
case AuthenticatorLinker.LinkResult.AwaitingFinalization:
|
||||
break;
|
||||
case AuthenticatorLinker.LinkResult.GeneralFailure:
|
||||
Console.WriteLine("error: Unable to add your phone number. Steam returned GeneralFailure");
|
||||
return;
|
||||
case AuthenticatorLinker.LinkResult.AuthenticatorPresent:
|
||||
Console.WriteLine("An authenticator is already present.");
|
||||
Console.WriteLine("If you have the revocation code (Rxxxxx), this program can remove it for you.");
|
||||
Console.Write("Would you like to remove the current authenticator using your revocation code? (y/n) ");
|
||||
var answer = Console.ReadLine();
|
||||
if (answer != "y")
|
||||
continue;
|
||||
Console.Write("Revocation code (Rxxxxx): ");
|
||||
var revocationCode = Console.ReadLine();
|
||||
var account = new SteamGuardAccount();
|
||||
account.Session = login.Session;
|
||||
account.RevocationCode = revocationCode;
|
||||
if (account.DeactivateAuthenticator())
|
||||
Console.WriteLine("Successfully deactivated the current authenticator.");
|
||||
else
|
||||
Console.WriteLine("Deactivating the current authenticator was unsuccessful.");
|
||||
continue;
|
||||
default:
|
||||
Console.WriteLine($"error: Unexpected linker result: {linkResult}");
|
||||
return;
|
||||
}
|
||||
} while (linkResult != AuthenticatorLinker.LinkResult.AwaitingFinalization);
|
||||
|
||||
string passKey = null;
|
||||
if (Manifest.Entries.Count == 0)
|
||||
{
|
||||
Console.WriteLine("Looks like we are setting up your first account.");
|
||||
passKey = Manifest.PromptSetupPassKey(true);
|
||||
}
|
||||
else if (Manifest.Entries.Count > 0 && Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
}
|
||||
|
||||
//Save the file immediately; losing this would be bad.
|
||||
if (!Manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey))
|
||||
{
|
||||
Manifest.RemoveAccount(linker.LinkedAccount);
|
||||
Console.WriteLine("Unable to save mobile authenticator file. The mobile authenticator has not been linked.");
|
||||
return;
|
||||
}
|
||||
|
||||
Console.WriteLine(
|
||||
$"The Mobile Authenticator has not yet been linked. Before finalizing the authenticator, please write down your revocation code: {linker.LinkedAccount.RevocationCode}");
|
||||
|
||||
AuthenticatorLinker.FinalizeResult finalizeResponse = AuthenticatorLinker.FinalizeResult.GeneralFailure;
|
||||
do
|
||||
{
|
||||
Console.Write("Please input the SMS message sent to your phone number: ");
|
||||
string smsCode = Console.ReadLine();
|
||||
|
||||
finalizeResponse = linker.FinalizeAddAuthenticator(smsCode);
|
||||
Utils.Verbose(finalizeResponse);
|
||||
|
||||
switch (finalizeResponse)
|
||||
{
|
||||
case AuthenticatorLinker.FinalizeResult.BadSMSCode:
|
||||
continue;
|
||||
|
||||
case AuthenticatorLinker.FinalizeResult.UnableToGenerateCorrectCodes:
|
||||
Console.WriteLine(
|
||||
"Unable to generate the proper codes to finalize this authenticator. The authenticator should not have been linked.");
|
||||
Console.WriteLine(
|
||||
$"In the off-chance it was, please write down your revocation code, as this is the last chance to see it: {linker.LinkedAccount.RevocationCode}");
|
||||
Manifest.RemoveAccount(linker.LinkedAccount);
|
||||
return;
|
||||
|
||||
case AuthenticatorLinker.FinalizeResult.GeneralFailure:
|
||||
Console.WriteLine("Unable to finalize this authenticator. The authenticator should not have been linked.");
|
||||
Console.WriteLine(
|
||||
$"In the off-chance it was, please write down your revocation code, as this is the last chance to see it: {linker.LinkedAccount.RevocationCode}");
|
||||
Manifest.RemoveAccount(linker.LinkedAccount);
|
||||
return;
|
||||
}
|
||||
} while (finalizeResponse != AuthenticatorLinker.FinalizeResult.Success);
|
||||
|
||||
//Linked, finally. Re-save with FullyEnrolled property.
|
||||
Manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey);
|
||||
Console.WriteLine(
|
||||
$"Mobile authenticator successfully linked. Please actually write down your revocation code: {linker.LinkedAccount.RevocationCode}");
|
||||
}
|
||||
|
||||
public static string FilterPhoneNumber(string phoneNumber)
|
||||
=> phoneNumber.Replace("-", "").Replace("(", "").Replace(")", "");
|
||||
|
||||
public static bool PhoneNumberOkay(string phoneNumber)
|
||||
{
|
||||
if (phoneNumber == null || phoneNumber.Length == 0) return false;
|
||||
if (phoneNumber[0] != '+') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void Trade(string user = "", string passkey = "")
|
||||
{
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
Utils.Verbose("Reading accounts from manifest...");
|
||||
if (Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
|
||||
}
|
||||
else
|
||||
{
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts();
|
||||
}
|
||||
if (SteamGuardAccounts.Length == 0)
|
||||
{
|
||||
Console.WriteLine("error: No accounts read.");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var account in SteamGuardAccounts)
|
||||
{
|
||||
if (user != "")
|
||||
if (!string.Equals(account.AccountName, user, StringComparison.CurrentCultureIgnoreCase))
|
||||
continue;
|
||||
|
||||
processConfirmations(account);
|
||||
}
|
||||
}
|
||||
|
||||
enum TradeAction
|
||||
{
|
||||
Accept = 1,
|
||||
Deny = 0,
|
||||
Ignore = -1
|
||||
}
|
||||
|
||||
static bool promptRefreshSession(SteamGuardAccount account)
|
||||
{
|
||||
Console.WriteLine("Your Steam credentials have expired. For trade and market confirmations to work properly, please login again.");
|
||||
string username = account.AccountName;
|
||||
Console.WriteLine($"Username: {username}");
|
||||
Console.Write("Password: ");
|
||||
var password = Console.ReadLine();
|
||||
|
||||
UserLogin login = new UserLogin(username, password);
|
||||
Console.Write($"Logging in {username}... ");
|
||||
LoginResult loginResult = login.DoLogin();
|
||||
if (loginResult == LoginResult.Need2FA && !string.IsNullOrEmpty(account.SharedSecret))
|
||||
{
|
||||
// if we need a 2fa code, and we can generate it, generate a 2fa code and log in.
|
||||
Utils.Verbose(loginResult);
|
||||
TimeAligner.AlignTime();
|
||||
login.TwoFactorCode = account.GenerateSteamGuardCode();
|
||||
Utils.Verbose($"Logging in {username}... ");
|
||||
loginResult = login.DoLogin();
|
||||
}
|
||||
Console.WriteLine(loginResult);
|
||||
if (loginResult == LoginResult.LoginOkay)
|
||||
{
|
||||
account.Session = login.Session;
|
||||
}
|
||||
|
||||
if (account.RefreshSession())
|
||||
{
|
||||
Utils.Verbose("Session refreshed");
|
||||
Manifest.SaveAccount(account, Manifest.Encrypted);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static void processConfirmations(SteamGuardAccount account)
|
||||
{
|
||||
Utils.Verbose("Refeshing Session...");
|
||||
if (account.RefreshSession())
|
||||
{
|
||||
Utils.Verbose("Session refreshed");
|
||||
Manifest.SaveAccount(account, Manifest.Encrypted);
|
||||
}
|
||||
else
|
||||
{
|
||||
Utils.Verbose("Failed to refresh session, prompting user...");
|
||||
if (!promptRefreshSession(account))
|
||||
{
|
||||
Console.WriteLine("Failed to refresh session, aborting...");
|
||||
}
|
||||
}
|
||||
Console.WriteLine("Retrieving trade confirmations...");
|
||||
var tradesTask = account.FetchConfirmationsAsync();
|
||||
tradesTask.Wait();
|
||||
var trades = tradesTask.Result;
|
||||
var tradeActions = new TradeAction[trades.Length];
|
||||
for (var i = 0; i < tradeActions.Length; i++)
|
||||
{
|
||||
tradeActions[i] = TradeAction.Ignore;
|
||||
}
|
||||
if (trades.Length == 0)
|
||||
{
|
||||
Console.WriteLine($"No trade confirmations for {account.AccountName}.");
|
||||
return;
|
||||
}
|
||||
var selected = 0;
|
||||
var colorAccept = ConsoleColor.Green;
|
||||
var colorDeny = ConsoleColor.Red;
|
||||
var colorIgnore = ConsoleColor.Gray;
|
||||
var colorSelected = ConsoleColor.Yellow;
|
||||
var confirm = false;
|
||||
|
||||
do
|
||||
{
|
||||
Console.Clear();
|
||||
if (selected >= trades.Length)
|
||||
selected = trades.Length - 1;
|
||||
else if (selected < 0)
|
||||
selected = 0;
|
||||
Console.ResetColor();
|
||||
Console.WriteLine($"Trade confirmations for {account.AccountName}...");
|
||||
Console.WriteLine("No action will be made without your confirmation.");
|
||||
Console.WriteLine("[a]ccept [d]eny [i]gnore [enter] Confirm [q]uit"); // accept = 1, deny = 0, ignore = -1
|
||||
Console.WriteLine();
|
||||
|
||||
for (var t = 0; t < trades.Length; t++)
|
||||
{
|
||||
ConsoleColor itemColor;
|
||||
switch (tradeActions[t])
|
||||
{
|
||||
case TradeAction.Accept:
|
||||
itemColor = colorAccept;
|
||||
break;
|
||||
case TradeAction.Deny:
|
||||
itemColor = colorDeny;
|
||||
break;
|
||||
case TradeAction.Ignore:
|
||||
itemColor = colorIgnore;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
Console.ForegroundColor = t == selected ? colorSelected : itemColor;
|
||||
|
||||
Console.WriteLine($" [{t}] [{tradeActions[t]}] {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}");
|
||||
}
|
||||
var key = Console.ReadKey();
|
||||
switch (key.Key)
|
||||
{
|
||||
case ConsoleKey.UpArrow:
|
||||
case ConsoleKey.W:
|
||||
selected--;
|
||||
break;
|
||||
case ConsoleKey.DownArrow:
|
||||
case ConsoleKey.S:
|
||||
selected++;
|
||||
break;
|
||||
case ConsoleKey.A:
|
||||
tradeActions[selected] = TradeAction.Accept;
|
||||
break;
|
||||
case ConsoleKey.D:
|
||||
tradeActions[selected] = TradeAction.Deny;
|
||||
break;
|
||||
case ConsoleKey.I:
|
||||
tradeActions[selected] = TradeAction.Ignore;
|
||||
break;
|
||||
case ConsoleKey.Enter:
|
||||
confirm = true;
|
||||
break;
|
||||
case ConsoleKey.Escape:
|
||||
case ConsoleKey.Q:
|
||||
Console.ResetColor();
|
||||
Console.WriteLine("Quitting...");
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} while (!confirm);
|
||||
Console.ResetColor();
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Processing...");
|
||||
for (var t = 0; t < trades.Length; t++)
|
||||
{
|
||||
bool success = false;
|
||||
switch (tradeActions[t])
|
||||
{
|
||||
case TradeAction.Accept:
|
||||
if (Verbose) Console.Write($"Accepting {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
|
||||
success = account.AcceptConfirmation(trades[t]);
|
||||
break;
|
||||
case TradeAction.Deny:
|
||||
if (Verbose) Console.Write($"Denying {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
|
||||
success = account.DenyConfirmation(trades[t]);
|
||||
break;
|
||||
case TradeAction.Ignore:
|
||||
if (Verbose) Console.Write($"Ignoring {trades[t].ConfType} {trades[t].Creator} {trades[t].Description}...");
|
||||
success = true;
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
Utils.Verbose(success);
|
||||
}
|
||||
Console.WriteLine("Done.");
|
||||
}
|
||||
|
||||
static void AcceptAllTrades(string user = "", string passkey = "")
|
||||
{
|
||||
Utils.Verbose("Opening manifest...");
|
||||
Manifest = Manifest.GetManifest(true);
|
||||
Utils.Verbose("Reading accounts from manifest...");
|
||||
if (Manifest.Encrypted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(passkey))
|
||||
{
|
||||
passkey = Manifest.PromptForPassKey();
|
||||
}
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts(passkey);
|
||||
}
|
||||
else
|
||||
{
|
||||
SteamGuardAccounts = Manifest.GetAllAccounts();
|
||||
}
|
||||
if (SteamGuardAccounts.Length == 0)
|
||||
{
|
||||
Console.WriteLine("error: No accounts read.");
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < SteamGuardAccounts.Length; i++)
|
||||
{
|
||||
SteamGuardAccount account = SteamGuardAccounts[i];
|
||||
if ((user != "" && account.AccountName.ToLower() == user.ToLower()) || user == "")
|
||||
{
|
||||
Console.WriteLine($"Accepting Confirmations on {account.AccountName}");
|
||||
Utils.Verbose("Refeshing Session...");
|
||||
if (account.RefreshSession())
|
||||
{
|
||||
Utils.Verbose("Session refreshed");
|
||||
Manifest.SaveAccount(account, Manifest.Encrypted);
|
||||
}
|
||||
else
|
||||
{
|
||||
Utils.Verbose("Failed to refresh session, prompting user...");
|
||||
if (!promptRefreshSession(account))
|
||||
{
|
||||
Console.WriteLine("Failed to refresh session, aborting...");
|
||||
}
|
||||
}
|
||||
Utils.Verbose("Fetching Confirmations...");
|
||||
var tradesTask = account.FetchConfirmationsAsync();
|
||||
tradesTask.Wait();
|
||||
Confirmation[] confirmations = tradesTask.Result;
|
||||
Utils.Verbose("Accepting Confirmations...");
|
||||
account.AcceptMultipleConfirmations(confirmations);
|
||||
if (user != "")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
159
README.md
159
README.md
|
@ -1,100 +1,105 @@
|
|||
# steamguard-cli
|
||||
A linux utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA) on the command line.
|
||||
**This utility is in beta.**
|
||||
|
||||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/rust.yml)
|
||||
[](https://github.com/dyc3/steamguard-cli/actions/workflows/aur-checker.yml)
|
||||
|
||||
A command line utility for setting up and using Steam Mobile Authenticator (AKA Steam 2FA). It can also be used to respond to trade, market, and any other steam mobile confirmations that you would normally get in the app.
|
||||
|
||||
**The only legitimate place to download steamguard-cli binaries is through this repo's releases, or by any package manager that is linked in this document.**
|
||||
|
||||
# Disclaimer
|
||||
**Use this software at your own risk.**
|
||||
**This utility is effectively in beta. Use this software at your own risk. Make sure to back up your maFiles regularly, and make sure to actually write down your revocation code. If you lose both of these, we can't help you, your only recourse is to beg Steam support.**
|
||||
|
||||
# Prerequisites
|
||||
These packages are required to build and run steamguard-cli.
|
||||
* mono-complete
|
||||
* nuget
|
||||
* make
|
||||
# Quickstart
|
||||
|
||||
# Building
|
||||
Downloading as .zip will not work because submodules are used. You must clone the repository.
|
||||
If you have no idea what the rest of this document is talking about, go read the [quickstart](docs/quickstart.md).
|
||||
|
||||
## Linux
|
||||
Building on Linux is very simple. Make sure you have all the prerequisites listed above.
|
||||
# Features
|
||||
|
||||
git clone --recursive https://github.com/dyc3/steamguard-cli.git
|
||||
cd steamguard-cli
|
||||
make
|
||||
- Generate 2FA codes
|
||||
- Respond to trade, market or any other confirmations
|
||||
- Encrypted storage of your 2FA secrets
|
||||
- With the option to store your encryption passkey in the system keyring
|
||||
- Special memory-clearing data structures to prevent leaking secrets
|
||||
- QR code generation for importing 2FA secrets into other applications, like KeeWeb
|
||||
- QR code logins for quickly logging into Steam on a new device, like the Steam Deck
|
||||
- Able to read Steam Desktop Authenticator's `maFiles` format
|
||||
- Uses as many official Steam APIs as possible, unlikely to break
|
||||
|
||||
To run the current build:
|
||||
# Install
|
||||
|
||||
build/steamguard
|
||||
If you have the Rust toolchain installed:
|
||||
```
|
||||
cargo install steamguard-cli
|
||||
```
|
||||
|
||||
To run the current build quickly:
|
||||
Arch-based systems can install from the AUR:
|
||||
|
||||
make run
|
||||
- [steamguard-cli](https://aur.archlinux.org/packages/steamguard-cli/) tracks the latest release
|
||||
- [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/) tracks the latest git commit
|
||||
|
||||
## macOS
|
||||
Otherwise, you can download binaries from the releases.
|
||||
|
||||
Building on macOS is pretty simple. Make sure you have all the prerequisites listed above.
|
||||
## Building From Source
|
||||
|
||||
* For the prerequisites the easiest way to install them is to use [homebrew](https://brew.sh/):
|
||||
|
||||
brew update
|
||||
brew install mono
|
||||
brew install nuget
|
||||
|
||||
* For the application source code:
|
||||
|
||||
git clone --recursive https://github.com/dyc3/steamguard-cli.git
|
||||
cd steamguard-cli
|
||||
make -f makefile.macos
|
||||
|
||||
To run the current build:
|
||||
|
||||
mono build/steamguard
|
||||
|
||||
To run the current build quickly:
|
||||
|
||||
make -f makefile.macos run
|
||||
|
||||
To install run:
|
||||
|
||||
make -f makefile.macos install
|
||||
|
||||
## Windows
|
||||
Coming soon...
|
||||
|
||||
# Installation
|
||||
To install the latest version on Debian-based systems, download the package from the releases section and type
|
||||
|
||||
sudo dpkg --install steamguard-cli_x.x.x.x-x.deb
|
||||
|
||||
For Archlinux, install [steamguard-cli-git](https://aur.archlinux.org/packages/steamguard-cli-git/) from the AUR.
|
||||
|
||||
To install after building from source, run:
|
||||
|
||||
sudo make install
|
||||
```
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
# Usage
|
||||
`steamguard-cli` looks for your `maFiles` folder in the current user's home directory (eg. `~/maFiles/`).
|
||||
Your `maFiles` can be created with [Steam Desktop Authenticator][SDA]. You can create `maFiles` with
|
||||
steamguard-cli using the `setup` action (`steamguard setup`).
|
||||
`steamguard-cli` looks for your `maFiles/manifest.json` in at these paths, in this order:
|
||||
|
||||
Linux:
|
||||
- `~/.config/steamguard-cli/maFiles/`
|
||||
- `~/maFiles/`
|
||||
|
||||
Windows:
|
||||
- `%APPDATA%\Roaming\steamguard-cli\maFiles\`
|
||||
- `%USERPROFILE%\maFiles\`
|
||||
|
||||
Your `maFiles` can be created with or imported from [Steam Desktop Authenticator][SDA]. You can create `maFiles` with steamguard-cli using the `setup` action (`steamguard setup`).
|
||||
|
||||
**REMEMBER TO MAKE BACKUPS OF YOUR `maFiles`, AND TO WRITE DOWN YOUR RECOVERY CODE!**
|
||||
|
||||
[SDA]: https://github.com/Jessecar96/SteamDesktopAuthenticator
|
||||
|
||||
## Arguments
|
||||
usage: steamguard (action) (steam username) -v -h
|
||||
Full helptext can be displayed with:
|
||||
```
|
||||
steamguard --help
|
||||
```
|
||||
|
||||
-h, --help Display this help message.
|
||||
-v, --verbose Display some extra information when the program is running.
|
||||
-m, --mafiles-path Specify which folder your maFiles are in. Ex: ~/maFiles
|
||||
-p, --passkey Specify your encryption passkey.
|
||||
## One Liners
|
||||
|
||||
Actions:
|
||||
generate-code Generate a Steam Guard code for the specified user (if any) and exit. (default)
|
||||
encrypt Encrypt your maFiles or change your encryption passkey.
|
||||
decrypt Remove encryption from your maFiles.
|
||||
code Same as generate-code
|
||||
2fa Same as generate-code
|
||||
add Set up Steam Guard for 2 factor authentication.
|
||||
setup Same as add
|
||||
trade Opens an interactive prompt to handle trade confirmations.
|
||||
accept-all Accepts all trade confirmations.
|
||||
Generate and copy a new code to clipboard:
|
||||
```bash
|
||||
steamguard | xclip -selection clipboard
|
||||
```
|
||||
|
||||
## Importing 2FA Secret Into Other Applications
|
||||
|
||||
It's possible to import your 2FA secret into other applications. This is useful if you want to use a password manager to generate your 2FA codes, like KeeWeb.
|
||||
|
||||
To make this easy, steamguard-cli can generate a QR code for your 2FA secret. You can then scan this QR code with your password manager.
|
||||
|
||||
```bash
|
||||
steamguard qr # print QR code for the first account in your maFiles
|
||||
steamguard -u <account name> qr # print QR code for a specific account
|
||||
```
|
||||
|
||||
There are some applications that do not generate correct 2fa codes from the secret, so **do not use them**:
|
||||
- Google Authenticator
|
||||
- Authy
|
||||
|
||||
# Contributing
|
||||
|
||||
By contributing code to this project, you give me and any future maintainers a non-exclusive transferable license to use that code for this project, including permission to modify, redistribute, and relicense it.
|
||||
|
||||
# License
|
||||
|
||||
`steamguard-cli`, the command line program is licensed under GPLv3.
|
||||
|
||||
`steamguard`, the library that is used by `steamguard-cli` is dual licensed under MIT or Apache 2.0, at your option.
|
||||
|
||||
# Used By
|
||||
|
||||
* [Unreal Engine to Steam publishing CI/CD pipeline](https://github.com/kasp1/dozer-pipelines), a sample pipeline built for [Dozer](https://github.com/kasp1/Dozer), a simple CI/CD runner
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
Subproject commit e0619528fbe8f4c6f74135283b3f991219e73cf4
|
38
Utils.cs
38
Utils.cs
|
@ -1,38 +0,0 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace SteamGuard
|
||||
{
|
||||
public static class Utils
|
||||
{
|
||||
public static string ReadLineSecure()
|
||||
{
|
||||
// Have bash handle the password input, because apparently it's impossible in C#,
|
||||
// and we don't need to worry about windows compatibility.
|
||||
string bash_cmd = @"read -s -p ""Password: "" password; echo $password";
|
||||
Process p = new Process();
|
||||
p.StartInfo.UseShellExecute = false;
|
||||
p.StartInfo.FileName = "bash";
|
||||
p.StartInfo.Arguments = string.Format("-c '{0}'", bash_cmd);
|
||||
p.StartInfo.RedirectStandardOutput = true;
|
||||
p.Start();
|
||||
|
||||
p.WaitForExit();
|
||||
Console.WriteLine();
|
||||
return p.StandardOutput.ReadToEnd().Trim();
|
||||
}
|
||||
|
||||
public static void Verbose(object obj)
|
||||
{
|
||||
Verbose(obj.ToString(), null);
|
||||
}
|
||||
|
||||
public static void Verbose(string format, params object[] arg)
|
||||
{
|
||||
if (Program.Verbose)
|
||||
{
|
||||
Console.WriteLine(format, arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
_steamguard()
|
||||
{
|
||||
local cur prev opts
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
opts="--help --verbose --maFiles-path --passkey"
|
||||
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -F _steamguard steamguard
|
55
docs/quickstart.md
Normal file
55
docs/quickstart.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
# Quickstart
|
||||
|
||||
steamguard-cli is a command-line tool, and as such, it is meant to be used in a terminal. This guide will show you how to get started with steamguard-cli.
|
||||
|
||||
## Windows
|
||||
|
||||
1. Download `steamguard.exe` from the [releases page][releases].
|
||||
2. Place `steamguard.exe` in a folder of your choice. For this example, we will use `%USERPROFILE%\Desktop`.
|
||||
3. Open Powershell or Command Prompt. The prompt should be at `%USERPROFILE%` (eg. `C:\Users\<username>`).
|
||||
4. Use `cd` to change directory into the folder where you placed `steamguard.exe`. For this example, it would be `cd Desktop`.
|
||||
5. You should now be able to run `steamguard.exe` by typing `.\steamguard.exe --help` and pressing enter.
|
||||
|
||||
## Linux
|
||||
|
||||
### Ubuntu/Debian
|
||||
|
||||
1. Download the `.deb` from the [releases page][releases].
|
||||
2. Open a terminal and run this to install it:
|
||||
```bash
|
||||
sudo dpkg -i ./steamguard-cli_<version>_amd64.deb
|
||||
```
|
||||
|
||||
### Other Linux
|
||||
|
||||
1. Download `steamguard` from the [releases page][releases]
|
||||
2. Make it executable, and move `steamguard` to `/usr/local/bin` or any other directory in your `$PATH`.
|
||||
```bash
|
||||
chmod +x ./steamguard
|
||||
sudo mv ./steamguard /usr/local/bin
|
||||
```
|
||||
3. You should now be able to run `steamguard` by typing `steamguard --help` and pressing enter.
|
||||
|
||||
# Importing existing maFiles from Steam Desktop Authenticator
|
||||
|
||||
If you have used [Steam Desktop Authenticator][SDA] before, you can use your existing maFiles into steamguard-cli, and they will be automatically upgraded for use with steamguard-cli.
|
||||
|
||||
1. Make a backup of your `maFiles` folder.
|
||||
2. Place your `maFiles` folder in the following directory:
|
||||
- Linux:
|
||||
- `~/.config/steamguard-cli/maFiles/`
|
||||
- Windows:
|
||||
- `%APPDATA%\Roaming\steamguard-cli\maFiles\`
|
||||
3. Run `steamguard` from your terminal.
|
||||
|
||||
|
||||
### Importing individual maFiles from Steam Desktop Authenticator
|
||||
|
||||
It's also possible to import a single maFile from Steam Desktop Authenticator and add it to your existing manifest.
|
||||
|
||||
```bash
|
||||
steamguard import --sda <path to maFile>
|
||||
```
|
||||
|
||||
[SDA]: https://github.com/Jessecar96/SteamDesktopAuthenticator
|
||||
[releases]: http://github.com/dyc3/steamguard-cli/releases
|
28
makefile
28
makefile
|
@ -1,28 +0,0 @@
|
|||
$(eval SHELL:=/bin/bash)
|
||||
|
||||
all: Program.cs
|
||||
mkdir -p build/
|
||||
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
|
||||
$(eval NEWTONSOFT_JSON_PATH=$(shell find -name Newtonsoft.Json.dll | grep \/net45\/ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n | tail -n 1))
|
||||
echo "NEWTONSOFT_JSON_PATH=$(NEWTONSOFT_JSON_PATH)"
|
||||
mcs -target:library -out:build/SteamAuth.dll -r:$(NEWTONSOFT_JSON_PATH) SteamAuth/SteamAuth/APIEndpoints.cs SteamAuth/SteamAuth/AuthenticatorLinker.cs SteamAuth/SteamAuth/Confirmation.cs SteamAuth/SteamAuth/SessionData.cs SteamAuth/SteamAuth/SteamGuardAccount.cs SteamAuth/SteamAuth/SteamWeb.cs SteamAuth/SteamAuth/TimeAligner.cs SteamAuth/SteamAuth/UserLogin.cs SteamAuth/SteamAuth/Util.cs SteamAuth/SteamAuth/Properties/AssemblyInfo.cs
|
||||
cp $(NEWTONSOFT_JSON_PATH) build/
|
||||
mcs -out:build/steamguard -r:build/SteamAuth.dll -r:build/Newtonsoft.Json.dll -r:/usr/lib/mono/4.5/System.Security.dll Program.cs Manifest.cs AssemblyInfo.cs Utils.cs
|
||||
|
||||
run:
|
||||
build/steamguard -v
|
||||
|
||||
clean:
|
||||
rm -r build/
|
||||
|
||||
install:
|
||||
cp build/steamguard /usr/local/bin/
|
||||
cp build/Newtonsoft.Json.dll /usr/local/bin/
|
||||
cp build/SteamAuth.dll /usr/local/bin/
|
||||
cp bash-tab-completion /etc/bash_completion.d/steamguard
|
||||
|
||||
uninstall:
|
||||
rm -f /usr/local/bin/steamguard
|
||||
rm -f /usr/local/bin/Newtonsoft.Json.dll
|
||||
rm -f /usr/local/bin/SteamAuth.dll
|
||||
rm -f /etc/bash_completion.d/steamguard
|
|
@ -1,24 +0,0 @@
|
|||
all: Program.cs
|
||||
mkdir -p build/
|
||||
nuget restore SteamAuth/SteamAuth/SteamAuth.sln
|
||||
mcs -target:library -out:build/SteamAuth.dll -r:SteamAuth/SteamAuth/packages/Newtonsoft.Json.11.0.1/lib/net45/Newtonsoft.Json.dll SteamAuth/SteamAuth/APIEndpoints.cs SteamAuth/SteamAuth/AuthenticatorLinker.cs SteamAuth/SteamAuth/Confirmation.cs SteamAuth/SteamAuth/SessionData.cs SteamAuth/SteamAuth/SteamGuardAccount.cs SteamAuth/SteamAuth/SteamWeb.cs SteamAuth/SteamAuth/TimeAligner.cs SteamAuth/SteamAuth/UserLogin.cs SteamAuth/SteamAuth/Util.cs SteamAuth/SteamAuth/Properties/AssemblyInfo.cs
|
||||
cp SteamAuth/SteamAuth/packages/Newtonsoft.Json.11.0.1/lib/net45/Newtonsoft.Json.dll build/
|
||||
mcs -out:build/steamguard -r:build/SteamAuth.dll -r:build/Newtonsoft.Json.dll -r:/usr/local/lib/mono/4.5/System.Security.dll Program.cs Manifest.cs AssemblyInfo.cs Utils.cs
|
||||
|
||||
run:
|
||||
mono build/steamguard -v
|
||||
|
||||
clean:
|
||||
rm -r build/
|
||||
|
||||
install:
|
||||
cp build/steamguard /usr/local/bin/
|
||||
cp build/Newtonsoft.Json.dll /usr/local/bin/
|
||||
cp build/SteamAuth.dll /usr/local/bin/
|
||||
cp bash-tab-completion /etc/bash_completion.d/steamguard
|
||||
|
||||
uninstall:
|
||||
rm -f /usr/local/bin/steamguard
|
||||
rm -f /usr/local/bin/Newtonsoft.Json.dll
|
||||
rm -f /usr/local/bin/SteamAuth.dll
|
||||
rm -f /etc/bash_completion.d/steamguard
|
29
package.sh
29
package.sh
|
@ -1,29 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
VERSION=$(build/steamguard --help | head -n 1 | cut -d v -f 2)"-0"
|
||||
TEMP_PKG_PATH="/tmp/steamguard-cli_$VERSION"
|
||||
echo Building Debian package for v$VERSION...
|
||||
|
||||
mkdir -p $TEMP_PKG_PATH/usr/local/bin
|
||||
mkdir -p $TEMP_PKG_PATH/etc/bash_completion.d
|
||||
mkdir -p $TEMP_PKG_PATH/DEBIAN
|
||||
|
||||
cp build/* $TEMP_PKG_PATH/usr/local/bin
|
||||
cp bash-tab-completion $TEMP_PKG_PATH/etc/bash_completion.d/steamguard
|
||||
|
||||
cat <<EOT >> $TEMP_PKG_PATH/DEBIAN/control
|
||||
Package: steamguard-cli
|
||||
Depends: mono-complete
|
||||
Version: $VERSION
|
||||
Section: base
|
||||
Priority: optional
|
||||
Architecture: all
|
||||
Maintainer: Carson McManus <dyc3@users.noreply.github.com>
|
||||
Description: steamguard-cli
|
||||
A command line utility to generate Steam Guard codes
|
||||
(AKA 2 factor authentication codes).
|
||||
EOT
|
||||
|
||||
dpkg-deb --build $TEMP_PKG_PATH steamguard-cli_$VERSION.deb
|
||||
|
||||
rm -rf $TEMP_PKG_PATH
|
2
rustfmt.toml
Normal file
2
rustfmt.toml
Normal file
|
@ -0,0 +1,2 @@
|
|||
tab_spaces = 4
|
||||
hard_tabs = true
|
17
scripts/check-aur.sh
Executable file
17
scripts/check-aur.sh
Executable file
|
@ -0,0 +1,17 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Performs a test install of the package from the AUR. If the package fails to install, there should be a non-zero exit code.
|
||||
# Intended for use with CI.
|
||||
|
||||
set -e
|
||||
|
||||
cd scripts/docker/arch/
|
||||
tar -cvf arch-docker.tar.gz .
|
||||
docker image build -t steamguard-cli-archlinux-builder - < arch-docker.tar.gz
|
||||
rm arch-docker.tar.gz
|
||||
|
||||
BIN_NAME="steamguard"
|
||||
|
||||
docker run --rm steamguard-cli-archlinux-builder /bin/bash -c "./install.sh steamguard-cli-git && $BIN_NAME --version"
|
||||
|
||||
docker image rm steamguard-cli-archlinux-builder:latest
|
3
scripts/docker/arch/Dockerfile
Normal file
3
scripts/docker/arch/Dockerfile
Normal file
|
@ -0,0 +1,3 @@
|
|||
FROM greyltc/archlinux-aur:yay
|
||||
|
||||
COPY install.sh /install.sh
|
5
scripts/docker/arch/install.sh
Executable file
5
scripts/docker/arch/install.sh
Executable file
|
@ -0,0 +1,5 @@
|
|||
#!/bin/bash
|
||||
|
||||
PACKAGE="$1"
|
||||
echo "Installing $PACKAGE"
|
||||
sudo -u ab -D~ bash -c "yay -Syu --removemake --needed --noprogressbar --noconfirm $PACKAGE"
|
126
scripts/full-release.sh
Executable file
126
scripts/full-release.sh
Executable file
|
@ -0,0 +1,126 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
DRY_RUN=true
|
||||
SKIP_CRATE_PUBLISH=false
|
||||
ALLOW_DIRTY=false
|
||||
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
key="$1"
|
||||
|
||||
case $key in
|
||||
--execute)
|
||||
DRY_RUN=false
|
||||
shift # past argument
|
||||
;;
|
||||
--bump)
|
||||
BUMP="$2"
|
||||
shift # past argument
|
||||
shift # past value
|
||||
;;
|
||||
--skip-publish)
|
||||
SKIP_CRATE_PUBLISH=true
|
||||
shift # past argument
|
||||
;;
|
||||
--allow-dirty)
|
||||
ALLOW_DIRTY=true
|
||||
shift # past argument
|
||||
;;
|
||||
*) # unknown option
|
||||
POSITIONAL+=("$1") # save it in an array for later
|
||||
shift # past argument
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
current_branch=$(git rev-parse --abbrev-ref HEAD)
|
||||
|
||||
if [[ "$current_branch" != "master" ]]; then
|
||||
echo "You must be on the master branch to run this script"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git pull
|
||||
|
||||
echo """
|
||||
This will do everything needed to release a new version:
|
||||
- bump the version number
|
||||
- create a git tag
|
||||
- build all artifacts
|
||||
- publish crates on crates.io
|
||||
- upload artifacts to a new release on github
|
||||
"""
|
||||
|
||||
echo "Previewing changes..."
|
||||
params=()
|
||||
if [[ $BUMP != "" ]]; then
|
||||
params+=(--bump "$BUMP")
|
||||
params+=(--bump-dependencies "$BUMP")
|
||||
fi
|
||||
if [[ $SKIP_CRATE_PUBLISH == true ]]; then
|
||||
params+=(--no-publish)
|
||||
fi
|
||||
if [[ $ALLOW_DIRTY == true ]]; then
|
||||
params+=(--allow-dirty)
|
||||
fi
|
||||
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
|
||||
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
echo "This is a dry run, nothing will be done. Artifacts will be built, but not published. Use --execute to do it for real."
|
||||
else
|
||||
echo "This is not a dry run. This is the real deal!"
|
||||
fi
|
||||
echo "Press any key to continue..."
|
||||
read -n 1 -s -r
|
||||
|
||||
|
||||
if [[ $DRY_RUN == false ]]; then
|
||||
params+=(--execute)
|
||||
fi
|
||||
cargo smart-release --update-crates-index --no-changelog --no-tag --no-push --no-publish "${params[@]}"
|
||||
|
||||
#echo "Verify that the publish succeeded, and Press any key to continue..."
|
||||
# read -n 1 -s -r
|
||||
|
||||
if ! which cross; then
|
||||
echo "cross not found, installing..."
|
||||
cargo install cross
|
||||
fi
|
||||
|
||||
BUILD_TARGET="x86_64-unknown-linux-musl"
|
||||
BUILD_TARGET2="x86_64-pc-windows-gnu"
|
||||
# HACK: build targets in this order to avoid a bug in cross
|
||||
cross build --release "--target=$BUILD_TARGET2"
|
||||
cross build --release "--target=$BUILD_TARGET"
|
||||
|
||||
./scripts/package-deb.sh
|
||||
|
||||
BIN_PATH="target/$BUILD_TARGET/release/steamguard"
|
||||
BIN_PATH2="target/$BUILD_TARGET2/release/steamguard.exe"
|
||||
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
||||
|
||||
# TODO: can't compare with the tag anymore because it doesn't exist yet. maybe get a better condition?
|
||||
# TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
|
||||
# if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
|
||||
# echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
|
||||
# if [[ $DRY_RUN == false ]]; then
|
||||
# echo "Aborting."
|
||||
# exit 2
|
||||
# fi
|
||||
# fi
|
||||
VERSION="v$RAW_VERSION"
|
||||
|
||||
echo "It's now safe to push tags and publish for the affected crates."
|
||||
|
||||
if [[ $DRY_RUN == false ]]; then
|
||||
cargo smart-release --update-crates-index --no-changelog --execute
|
||||
fi
|
||||
|
||||
if [[ $DRY_RUN == false ]]; then
|
||||
if [[ $(gh release list | grep -i "Draft" | grep -i "$VERSION" && echo "true" || echo "false") == "true" ]]; then
|
||||
gh release delete --yes "$VERSION"
|
||||
fi
|
||||
gh release create "$VERSION" --discussion-category "General" --title "$VERSION" "$BIN_PATH" "$BIN_PATH2" "./steamguard-cli_$RAW_VERSION-0.deb"
|
||||
fi
|
43
scripts/package-deb.sh
Executable file
43
scripts/package-deb.sh
Executable file
|
@ -0,0 +1,43 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
DISTRO=$(lsb_release -i -s)
|
||||
DISTRO_VERSION=$(lsb_release -r -s)
|
||||
|
||||
if ! which cross; then
|
||||
echo "cross not found, installing..."
|
||||
cargo install cross
|
||||
fi
|
||||
|
||||
BIN_PATH="target/x86_64-unknown-linux-musl/release/steamguard"
|
||||
if [[ ! -f "$BIN_PATH" ]]; then
|
||||
echo "ERROR: Could not find release binaries, building them..."
|
||||
cross build --release --target=x86_64-unknown-linux-musl
|
||||
fi
|
||||
VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
||||
TEMP_PKG_PATH="/tmp/steamguard-cli_$VERSION"
|
||||
echo "Building package on $DISTRO $DISTRO_VERSION for v$VERSION..."
|
||||
|
||||
mkdir -p "$TEMP_PKG_PATH/usr/local/bin"
|
||||
mkdir -p "$TEMP_PKG_PATH/etc/bash_completion.d"
|
||||
mkdir -p "$TEMP_PKG_PATH/DEBIAN"
|
||||
|
||||
cp "$BIN_PATH" "$TEMP_PKG_PATH/usr/local/bin/steamguard"
|
||||
"$BIN_PATH" completion --shell bash > "$TEMP_PKG_PATH/etc/bash_completion.d/steamguard"
|
||||
|
||||
cat <<EOT >> $TEMP_PKG_PATH/DEBIAN/control
|
||||
Package: steamguard-cli
|
||||
Depends:
|
||||
Version: $VERSION
|
||||
Section: base
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
Maintainer: Carson McManus <carson.mcmanus1@gmail.com>
|
||||
Description: steamguard-cli
|
||||
A command line utility to generate Steam 2FA codes and respond to confirmations.
|
||||
EOT
|
||||
|
||||
dpkg-deb -Zxz --build "$TEMP_PKG_PATH" "steamguard-cli_$VERSION-0.deb"
|
||||
|
||||
rm -rf "$TEMP_PKG_PATH"
|
57
scripts/publish-aur.sh
Executable file
57
scripts/publish-aur.sh
Executable file
|
@ -0,0 +1,57 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
DRY_RUN=true
|
||||
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
key="$1"
|
||||
|
||||
case $key in
|
||||
--execute)
|
||||
DRY_RUN=false
|
||||
shift # past argument
|
||||
;;
|
||||
*) # unknown option
|
||||
POSITIONAL+=("$1") # save it in an array for later
|
||||
shift # past argument
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# prerequisites
|
||||
if ! command -v makepkg &> /dev/null; then
|
||||
echo "Error: makepkg is not installed"
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v git &> /dev/null; then
|
||||
echo "Error: git is not installed"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
|
||||
# get version info
|
||||
BIN_PATH="target/release/steamguard"
|
||||
RAW_VERSION="$("$BIN_PATH" --version | cut -d " " -f 2)"
|
||||
TAGGED_VERSION="$(git tag | grep "^v" | tail -n 1 | tr -d v)"
|
||||
if [[ "v$RAW_VERSION" != "v$TAGGED_VERSION" ]]; then
|
||||
echo "Version mismatch: $RAW_VERSION != $TAGGED_VERSION"
|
||||
exit 10
|
||||
fi
|
||||
VERSION="v$RAW_VERSION"
|
||||
|
||||
# update PKGBUILD for AUR
|
||||
if [[ -d "aur" ]]; then
|
||||
rm -rf aur
|
||||
fi
|
||||
git clone ssh://aur@aur.archlinux.org/steamguard-cli-git.git aur
|
||||
cp PKGBUILD aur/PKGBUILD
|
||||
cd aur
|
||||
makepkg -si --noconfirm
|
||||
makepkg --printsrcinfo > .SRCINFO
|
||||
git commit -m "release $VERSION" PKGBUILD
|
||||
if [[ $DRY_RUN == false ]]; then
|
||||
git push
|
||||
rm -rf aur
|
||||
fi
|
||||
cd ..
|
703
src/accountmanager.rs
Normal file
703
src/accountmanager.rs
Normal file
|
@ -0,0 +1,703 @@
|
|||
use crate::accountmanager::legacy::SdaManifest;
|
||||
pub use crate::encryption::EncryptionScheme;
|
||||
use crate::encryption::EntryEncryptor;
|
||||
use log::*;
|
||||
use rayon::prelude::*;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read, Write};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use steamguard::SteamGuardAccount;
|
||||
use thiserror::Error;
|
||||
|
||||
mod legacy;
|
||||
pub mod manifest;
|
||||
pub mod migrate;
|
||||
mod steamv2;
|
||||
mod winauth;
|
||||
|
||||
pub use manifest::*;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AccountManager {
|
||||
manifest: Manifest,
|
||||
accounts: HashMap<String, Arc<Mutex<SteamGuardAccount>>>,
|
||||
folder: String,
|
||||
passkey: Option<SecretString>,
|
||||
}
|
||||
|
||||
impl AccountManager {
|
||||
/// `path` should be the path to manifest.json
|
||||
pub fn new(path: &Path) -> Self {
|
||||
Self {
|
||||
folder: String::from(path.parent().unwrap().to_str().unwrap()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_manifest(manifest: Manifest, folder: String) -> Self {
|
||||
Self {
|
||||
manifest,
|
||||
folder,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_accounts(&mut self, accounts: Vec<SteamGuardAccount>) {
|
||||
for account in accounts {
|
||||
self.register_loaded_account(Arc::new(Mutex::new(account)));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> anyhow::Result<Self, ManifestLoadError> {
|
||||
debug!("loading manifest: {:?}", &path);
|
||||
let file = File::open(path)?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut buffer = String::new();
|
||||
reader.read_to_string(&mut buffer)?;
|
||||
let mut deser = serde_json::Deserializer::from_str(&buffer);
|
||||
let manifest: Manifest = match serde_path_to_error::deserialize(&mut deser) {
|
||||
Ok(m) => m,
|
||||
Err(orig_err) => match serde_json::from_str::<SdaManifest>(&buffer) {
|
||||
Ok(_) => return Err(ManifestLoadError::MigrationNeeded)?,
|
||||
Err(_) => return Err(orig_err)?,
|
||||
},
|
||||
};
|
||||
if manifest.version != CURRENT_MANIFEST_VERSION {
|
||||
return Err(ManifestLoadError::MigrationNeeded)?;
|
||||
}
|
||||
let accountmanager = Self {
|
||||
manifest,
|
||||
folder: String::from(path.parent().unwrap().to_str().unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(accountmanager)
|
||||
}
|
||||
|
||||
/// Tells the manager to keep track of the encryption passkey, and use it for encryption when loading or saving accounts.
|
||||
pub fn submit_passkey(&mut self, passkey: Option<SecretString>) {
|
||||
if let Some(p) = passkey.as_ref() {
|
||||
if p.expose_secret().is_empty() {
|
||||
panic!("Encryption passkey cannot be empty");
|
||||
}
|
||||
}
|
||||
if passkey.is_some() {
|
||||
debug!("passkey was submitted to manifest");
|
||||
} else {
|
||||
debug!("passkey was revoked from manifest");
|
||||
}
|
||||
self.passkey = passkey;
|
||||
}
|
||||
|
||||
pub fn keyring_id(&self) -> Option<&String> {
|
||||
self.manifest.keyring_id.as_ref()
|
||||
}
|
||||
|
||||
pub fn set_keyring_id(&mut self, keyring_id: String) {
|
||||
self.manifest.keyring_id = Some(keyring_id);
|
||||
}
|
||||
|
||||
pub fn clear_keyring_id(&mut self) {
|
||||
self.manifest.keyring_id = None;
|
||||
}
|
||||
|
||||
/// Loads all accounts, and registers them.
|
||||
pub fn load_accounts(&mut self) -> anyhow::Result<(), ManifestAccountLoadError> {
|
||||
let accounts = self
|
||||
.manifest
|
||||
.entries
|
||||
.par_iter()
|
||||
.map(|entry| self.load_account_by_entry(entry))
|
||||
.collect::<Vec<_>>();
|
||||
for account in accounts {
|
||||
self.register_loaded_account(account?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads an account by account name.
|
||||
/// Must call `register_loaded_account` after loading the account.
|
||||
fn load_account(
|
||||
&self,
|
||||
account_name: impl AsRef<str>,
|
||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
||||
let entry = self.get_entry(account_name)?;
|
||||
self.load_account_by_entry(entry)
|
||||
}
|
||||
|
||||
/// Loads an account from a manifest entry.
|
||||
/// Must call `register_loaded_account` after loading the account.
|
||||
fn load_account_by_entry(
|
||||
&self,
|
||||
entry: &ManifestEntry,
|
||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
||||
let path = Path::new(&self.folder).join(&entry.filename);
|
||||
let account = entry.load(
|
||||
path.as_path(),
|
||||
self.passkey.as_ref(),
|
||||
entry.encryption.as_ref(),
|
||||
)?;
|
||||
let account = Arc::new(Mutex::new(account));
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
/// Register an account as loaded, so it can be operated on.
|
||||
fn register_loaded_account(&mut self, account: Arc<Mutex<SteamGuardAccount>>) {
|
||||
let account_name = account.lock().unwrap().account_name.clone();
|
||||
self.accounts.insert(account_name, account);
|
||||
}
|
||||
|
||||
pub fn account_exists(&self, account_name: &String) -> bool {
|
||||
for entry in &self.manifest.entries {
|
||||
if &entry.account_name == account_name {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn add_account(&mut self, account: SteamGuardAccount) {
|
||||
debug!("adding account to manifest: {}", account.account_name);
|
||||
self.manifest.entries.push(ManifestEntry {
|
||||
filename: format!("{}.maFile", &account.account_name),
|
||||
steam_id: account.steam_id,
|
||||
account_name: account.account_name.clone(),
|
||||
encryption: None,
|
||||
});
|
||||
self.accounts
|
||||
.insert(account.account_name.clone(), Arc::new(Mutex::new(account)));
|
||||
}
|
||||
|
||||
pub fn import_account(
|
||||
&mut self,
|
||||
import_path: &String,
|
||||
) -> anyhow::Result<(), ManifestAccountImportError> {
|
||||
let path = Path::new(import_path);
|
||||
if !path.exists() {
|
||||
return Err(ManifestAccountImportError::FileNotFound);
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(ManifestAccountImportError::NotAFile);
|
||||
}
|
||||
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||
let account: SteamGuardAccount = serde_path_to_error::deserialize(&mut deser)?;
|
||||
if self.account_exists(&account.account_name) {
|
||||
return Err(ManifestAccountImportError::AlreadyExists {
|
||||
account_name: account.account_name,
|
||||
});
|
||||
}
|
||||
self.add_account(account);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_account(&mut self, account_name: &String) {
|
||||
let index = self
|
||||
.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.position(|a| &a.account_name == account_name)
|
||||
.unwrap();
|
||||
self.accounts.remove(account_name);
|
||||
self.manifest.entries.remove(index);
|
||||
}
|
||||
|
||||
/// Saves the manifest and all loaded accounts.
|
||||
pub fn save(&self) -> anyhow::Result<()> {
|
||||
info!("Saving manifest and accounts...");
|
||||
let save_results: Vec<_> = self
|
||||
.accounts
|
||||
.values()
|
||||
.par_bridge()
|
||||
.map(|account| -> anyhow::Result<()> {
|
||||
let account = account.lock().unwrap();
|
||||
let entry = self.get_entry(&account.account_name)?.clone();
|
||||
debug!("saving {}", entry.filename);
|
||||
let serialized = serde_json::to_vec(&account.clone())?;
|
||||
ensure!(
|
||||
serialized.len() > 2,
|
||||
"Something extra weird happened and the account was serialized into nothing."
|
||||
);
|
||||
|
||||
let final_buffer: Vec<u8> = match (&self.passkey, entry.encryption.as_ref()) {
|
||||
(Some(passkey), Some(scheme)) => {
|
||||
scheme.encrypt(passkey.expose_secret(), serialized)?
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
bail!("maFiles are encrypted, but no passkey was provided.");
|
||||
}
|
||||
(_, None) => serialized,
|
||||
};
|
||||
|
||||
let path = Path::new(&self.folder).join(&entry.filename);
|
||||
let mut file = File::create(path)?;
|
||||
file.write_all(final_buffer.as_slice())?;
|
||||
file.sync_data()?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.collect();
|
||||
for result in save_results {
|
||||
result?;
|
||||
}
|
||||
debug!("saving manifest");
|
||||
let manifest_serialized = serde_json::to_string(&self.manifest)?;
|
||||
let path = Path::new(&self.folder).join("manifest.json");
|
||||
let mut file = File::create(path)?;
|
||||
file.write_all(manifest_serialized.as_bytes())?;
|
||||
file.sync_data()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return all loaded accounts. Order is not guarenteed.
|
||||
#[allow(dead_code)]
|
||||
pub fn get_all_loaded(&self) -> Vec<Arc<Mutex<SteamGuardAccount>>> {
|
||||
return self.accounts.values().cloned().collect();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_entry(
|
||||
&self,
|
||||
account_name: impl AsRef<str>,
|
||||
) -> anyhow::Result<&ManifestEntry, ManifestAccountLoadError> {
|
||||
self.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.find(|e| e.account_name == account_name.as_ref())
|
||||
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_entry_mut(
|
||||
&mut self,
|
||||
account_name: impl AsRef<str>,
|
||||
) -> anyhow::Result<&mut ManifestEntry, ManifestAccountLoadError> {
|
||||
self.manifest
|
||||
.entries
|
||||
.iter_mut()
|
||||
.find(|e| e.account_name == account_name.as_ref())
|
||||
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
||||
}
|
||||
|
||||
pub fn has_passkey(&self) -> bool {
|
||||
self.passkey.is_some()
|
||||
}
|
||||
|
||||
/// Gets the specified account by name.
|
||||
/// Fails if the account does not exist in the manifest entries.
|
||||
pub fn get_account(
|
||||
&self,
|
||||
account_name: impl AsRef<str>,
|
||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>> {
|
||||
let account = self
|
||||
.accounts
|
||||
.get(account_name.as_ref())
|
||||
.cloned()
|
||||
.ok_or(anyhow!("Account not loaded"));
|
||||
account
|
||||
}
|
||||
|
||||
/// Get or load the spcified account.
|
||||
pub fn get_or_load_account(
|
||||
&mut self,
|
||||
account_name: impl AsRef<str>,
|
||||
) -> anyhow::Result<Arc<Mutex<SteamGuardAccount>>, ManifestAccountLoadError> {
|
||||
let account = self.get_account(account_name.as_ref());
|
||||
if let Ok(account) = account {
|
||||
return Ok(account);
|
||||
}
|
||||
let account = self.load_account(account_name.as_ref())?;
|
||||
self.register_loaded_account(account.clone());
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
/// Determine if any manifest entries are missing `account_name`.
|
||||
fn is_missing_account_name(&self) -> bool {
|
||||
self.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.any(|e| e.account_name.is_empty())
|
||||
}
|
||||
|
||||
fn has_any_uppercase_in_account_names(&self) -> bool {
|
||||
self.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.any(|e| e.account_name != e.account_name.to_lowercase())
|
||||
}
|
||||
|
||||
/// Performs auto-upgrades on the manifest. Returns true if any upgrades were performed.
|
||||
pub fn auto_upgrade(&mut self) -> anyhow::Result<bool, ManifestAccountLoadError> {
|
||||
debug!("Performing auto-upgrade...");
|
||||
let mut upgraded = false;
|
||||
if self.is_missing_account_name() {
|
||||
debug!("Adding missing account names");
|
||||
for i in 0..self.manifest.entries.len() {
|
||||
let account = self.load_account_by_entry(&self.manifest.entries[i].clone())?;
|
||||
self.manifest.entries[i]
|
||||
.account_name
|
||||
.clone_from(&account.lock().unwrap().account_name);
|
||||
}
|
||||
upgraded = true;
|
||||
}
|
||||
|
||||
if self.has_any_uppercase_in_account_names() {
|
||||
debug!("Lowercasing account names");
|
||||
for i in 0..self.manifest.entries.len() {
|
||||
self.manifest.entries[i].account_name =
|
||||
self.manifest.entries[i].account_name.to_lowercase();
|
||||
}
|
||||
upgraded = true;
|
||||
}
|
||||
|
||||
Ok(upgraded)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &ManifestEntry> {
|
||||
self.manifest.entries.iter()
|
||||
}
|
||||
|
||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut ManifestEntry> {
|
||||
self.manifest.entries.iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
trait EntryLoader<T> {
|
||||
fn load(
|
||||
&self,
|
||||
path: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
encryption_params: Option<&EncryptionScheme>,
|
||||
) -> anyhow::Result<T, ManifestAccountLoadError>;
|
||||
}
|
||||
|
||||
impl EntryLoader<SteamGuardAccount> for ManifestEntry {
|
||||
fn load(
|
||||
&self,
|
||||
path: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
encryption_params: Option<&EncryptionScheme>,
|
||||
) -> anyhow::Result<SteamGuardAccount, ManifestAccountLoadError> {
|
||||
debug!("loading entry: {:?}", path);
|
||||
let file = File::open(path)?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let account: SteamGuardAccount = match (&passkey, encryption_params.as_ref()) {
|
||||
(Some(passkey), Some(scheme)) => {
|
||||
let mut ciphertext: Vec<u8> = vec![];
|
||||
reader.read_to_end(&mut ciphertext)?;
|
||||
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
|
||||
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
||||
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
||||
}
|
||||
let s = std::str::from_utf8(&plaintext).unwrap();
|
||||
let mut deser = serde_json::Deserializer::from_str(s);
|
||||
serde_path_to_error::deserialize(&mut deser)?
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
return Err(ManifestAccountLoadError::MissingPasskey);
|
||||
}
|
||||
(_, None) => {
|
||||
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||
serde_path_to_error::deserialize(&mut deser)?
|
||||
}
|
||||
};
|
||||
Ok(account)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManifestLoadError {
|
||||
#[error("Could not find manifest.json in the specified directory.")]
|
||||
Missing(#[from] std::io::Error),
|
||||
#[error("Manifest needs to be migrated to the latest format.")]
|
||||
MigrationNeeded,
|
||||
#[error("Failed to deserialize the manifest. {self:?}")]
|
||||
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManifestAccountLoadError {
|
||||
#[error("Could not find an entry in the manifest for this account. Check your spelling.")]
|
||||
MissingManifestEntry,
|
||||
#[error("Manifest accounts are encrypted, but no passkey was provided.")]
|
||||
MissingPasskey,
|
||||
#[error("Incorrect passkey provided.")]
|
||||
IncorrectPasskey,
|
||||
#[error("Failed to decrypt account. {self:?}")]
|
||||
DecryptionFailed(#[from] crate::encryption::EntryEncryptionError),
|
||||
#[error("Failed to deserialize the account. {self:?}")]
|
||||
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<base64::DecodeError> for ManifestAccountLoadError {
|
||||
fn from(error: base64::DecodeError) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
impl From<std::io::Error> for ManifestAccountLoadError {
|
||||
fn from(error: std::io::Error) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ManifestAccountImportError {
|
||||
#[error("Could not find the specified file.")]
|
||||
FileNotFound,
|
||||
#[error("The specified path is not a file.")]
|
||||
NotAFile,
|
||||
#[error(
|
||||
"The account you are trying to import, \"{account_name}\", already exists in the manifest."
|
||||
)]
|
||||
AlreadyExists { account_name: String },
|
||||
#[error(transparent)]
|
||||
IOError(#[from] std::io::Error),
|
||||
#[error("Failed to deserialize the account. {self:?}")]
|
||||
DeserializationFailed(#[from] serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use steamguard::ExposeSecret;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn test_should_save_new_manifest() {
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let manager = AccountManager::new(manifest_path.as_path());
|
||||
assert!(manager.save().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_save_and_load_manifest() -> anyhow::Result<()> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
println!("tempdir: {}", manifest_path.display());
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
account.account_name = "asdf1234".into();
|
||||
account.revocation_code = String::from("R12345").into();
|
||||
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
||||
)?;
|
||||
manager.add_account(account);
|
||||
manager.save()?;
|
||||
|
||||
let mut manager = AccountManager::load(manifest_path.as_path())?;
|
||||
assert_eq!(manager.manifest.entries.len(), 1);
|
||||
assert_eq!(manager.manifest.entries[0].filename, "asdf1234.maFile");
|
||||
manager.load_accounts()?;
|
||||
assert_eq!(manager.manifest.entries.len(), manager.accounts.len());
|
||||
let account_name = "asdf1234";
|
||||
let account = manager.get_account(account_name)?;
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "asdf1234");
|
||||
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||
assert_eq!(
|
||||
account.shared_secret,
|
||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_save_and_load_manifest_encrypted() -> anyhow::Result<()> {
|
||||
let passkey = Some(SecretString::new("password".into()));
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
account.account_name = "asdf1234".into();
|
||||
account.revocation_code = String::from("R12345").into();
|
||||
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
||||
)?;
|
||||
manager.add_account(account);
|
||||
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
|
||||
manager.submit_passkey(passkey.clone());
|
||||
assert!(manager.save().is_ok());
|
||||
|
||||
let mut loaded_manager = AccountManager::load(manifest_path.as_path()).unwrap();
|
||||
loaded_manager.submit_passkey(passkey);
|
||||
assert_eq!(loaded_manager.manifest.entries.len(), 1);
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries[0].filename,
|
||||
"asdf1234.maFile"
|
||||
);
|
||||
let _r = loaded_manager.load_accounts();
|
||||
if _r.is_err() {
|
||||
eprintln!("{:?}", _r);
|
||||
}
|
||||
assert!(_r.is_ok());
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries.len(),
|
||||
loaded_manager.accounts.len()
|
||||
);
|
||||
let account_name = "asdf1234";
|
||||
let account = loaded_manager.get_account(account_name)?;
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "asdf1234");
|
||||
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||
assert_eq!(
|
||||
account.shared_secret,
|
||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_save_and_load_manifest_encrypted_longer() -> anyhow::Result<()> {
|
||||
let passkey = Some(SecretString::new("password".into()));
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
account.account_name = "asdf1234".into();
|
||||
account.revocation_code = String::from("R12345").into();
|
||||
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
||||
)
|
||||
.unwrap();
|
||||
account.uri = String::from("otpauth://;laksdjf;lkasdjf;lkasdj;flkasdjlkf;asjdlkfjslk;adjfl;kasdjf;lksdjflk;asjd;lfajs;ldkfjaslk;djf;lsakdjf;lksdj").into();
|
||||
account.token_gid = "asdf1234".into();
|
||||
manager.add_account(account);
|
||||
manager.submit_passkey(passkey.clone());
|
||||
manager.manifest.entries[0].encryption = Some(EncryptionScheme::generate());
|
||||
manager.save()?;
|
||||
|
||||
let mut loaded_manager = AccountManager::load(manifest_path.as_path())?;
|
||||
loaded_manager.submit_passkey(passkey);
|
||||
assert_eq!(loaded_manager.manifest.entries.len(), 1);
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries[0].filename,
|
||||
"asdf1234.maFile"
|
||||
);
|
||||
loaded_manager.load_accounts()?;
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries.len(),
|
||||
loaded_manager.accounts.len()
|
||||
);
|
||||
let account_name = "asdf1234";
|
||||
let account = loaded_manager.get_account(account_name)?;
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "asdf1234");
|
||||
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||
assert_eq!(
|
||||
account.shared_secret,
|
||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_import() -> anyhow::Result<()> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let manifest_path = tmp_dir.path().join("manifest.json");
|
||||
let mut manager = AccountManager::new(manifest_path.as_path());
|
||||
let mut account = SteamGuardAccount::new();
|
||||
account.account_name = "asdf1234".into();
|
||||
account.revocation_code = String::from("R12345").into();
|
||||
account.shared_secret = steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into(),
|
||||
)
|
||||
.unwrap();
|
||||
manager.add_account(account);
|
||||
manager.save()?;
|
||||
std::fs::remove_file(&manifest_path)?;
|
||||
|
||||
let mut loaded_manager = AccountManager::new(manifest_path.as_path());
|
||||
assert!(loaded_manager
|
||||
.import_account(
|
||||
&tmp_dir
|
||||
.path()
|
||||
.join("asdf1234.maFile")
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.unwrap()
|
||||
)
|
||||
.is_ok());
|
||||
assert_eq!(
|
||||
loaded_manager.manifest.entries.len(),
|
||||
loaded_manager.accounts.len()
|
||||
);
|
||||
let account_name = "asdf1234";
|
||||
let account = loaded_manager.get_account(account_name)?;
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "asdf1234");
|
||||
assert_eq!(account.revocation_code.expose_secret(), "R12345");
|
||||
assert_eq!(
|
||||
account.shared_secret,
|
||||
steamguard::token::TwoFactorSecret::parse_shared_secret(
|
||||
"zvIayp3JPvtvX/QGHqsqKBk/44s=".into()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_load_manifest_v1() -> anyhow::Result<()> {
|
||||
#[derive(Debug)]
|
||||
struct Test {
|
||||
manifest: &'static str,
|
||||
passkey: Option<SecretString>,
|
||||
}
|
||||
let cases = vec![
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/manifest-v1/1-account/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/manifest-v1/1-account-encrypted/manifest.json",
|
||||
passkey: Some(SecretString::new("password".into())),
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/manifest-v1/2-account/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/manifest-v1/missing-account-name/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let mut manager = AccountManager::load(Path::new(case.manifest))?;
|
||||
manager.submit_passkey(case.passkey.clone());
|
||||
manager.load_accounts()?;
|
||||
assert_eq!(manager.manifest.version, CURRENT_MANIFEST_VERSION);
|
||||
assert_eq!(manager.manifest.entries[0].account_name, "example");
|
||||
assert_eq!(manager.manifest.entries[0].steam_id, 1234);
|
||||
let account = manager.get_account("example").unwrap();
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "example");
|
||||
assert_eq!(account.steam_id, 1234);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
185
src/accountmanager/legacy.rs
Normal file
185
src/accountmanager/legacy.rs
Normal file
|
@ -0,0 +1,185 @@
|
|||
#![allow(deprecated)]
|
||||
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufReader, Read},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use log::debug;
|
||||
use secrecy::{CloneableSecret, DebugSecret, ExposeSecret};
|
||||
use serde::Deserialize;
|
||||
use steamguard::{token::TwoFactorSecret, SecretString, SteamGuardAccount};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||
|
||||
use crate::encryption::{EntryEncryptor, LegacySdaCompatible};
|
||||
|
||||
use super::{EncryptionScheme, EntryLoader, ManifestAccountLoadError, ManifestEntry, ManifestV1};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SdaManifest {
|
||||
#[serde(default)]
|
||||
pub version: u32,
|
||||
pub entries: Vec<SdaManifestEntry>,
|
||||
/// Not really used, kept mostly for compatibility with SDA.
|
||||
pub encrypted: bool,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub first_run: bool,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub periodic_checking: bool,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub periodic_checking_interval: i32,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub periodic_checking_checkall: bool,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub auto_confirm_market_transactions: bool,
|
||||
/// Not implemented, kept for compatibility with SDA.
|
||||
pub auto_confirm_trades: bool,
|
||||
}
|
||||
|
||||
impl From<SdaManifest> for ManifestV1 {
|
||||
fn from(sda: SdaManifest) -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
entries: sda.entries.into_iter().map(|e| e.into()).collect(),
|
||||
keyring_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SdaManifestEntry {
|
||||
pub filename: String,
|
||||
#[serde(default, rename = "steamid")]
|
||||
pub steam_id: u64,
|
||||
#[serde(default, flatten)]
|
||||
pub encryption: Option<SdaEntryEncryptionParams>,
|
||||
}
|
||||
|
||||
impl From<SdaManifestEntry> for ManifestEntry {
|
||||
fn from(sda: SdaManifestEntry) -> Self {
|
||||
Self {
|
||||
filename: sda.filename,
|
||||
steam_id: sda.steam_id,
|
||||
account_name: Default::default(),
|
||||
encryption: sda.encryption.map(|e| e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryLoader<SdaAccount> for SdaManifestEntry {
|
||||
fn load(
|
||||
&self,
|
||||
path: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
encryption_params: Option<&EncryptionScheme>,
|
||||
) -> anyhow::Result<SdaAccount, ManifestAccountLoadError> {
|
||||
debug!("loading entry: {:?}", path);
|
||||
let file = File::open(path)?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let account: SdaAccount = match (&passkey, encryption_params.as_ref()) {
|
||||
(Some(passkey), Some(scheme)) => {
|
||||
let mut ciphertext: Vec<u8> = vec![];
|
||||
reader.read_to_end(&mut ciphertext)?;
|
||||
let plaintext = scheme.decrypt(passkey.expose_secret(), ciphertext)?;
|
||||
if plaintext[0] != b'{' && plaintext[plaintext.len() - 1] != b'}' {
|
||||
return Err(ManifestAccountLoadError::IncorrectPasskey);
|
||||
}
|
||||
let s = std::str::from_utf8(&plaintext).unwrap();
|
||||
let mut deser = serde_json::Deserializer::from_str(s);
|
||||
serde_path_to_error::deserialize(&mut deser)?
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
return Err(ManifestAccountLoadError::MissingPasskey);
|
||||
}
|
||||
(_, None) => {
|
||||
let mut deser = serde_json::Deserializer::from_reader(reader);
|
||||
serde_path_to_error::deserialize(&mut deser)?
|
||||
}
|
||||
};
|
||||
Ok(account)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SdaEntryEncryptionParams {
|
||||
#[serde(rename = "encryption_iv")]
|
||||
pub iv: String,
|
||||
#[serde(rename = "encryption_salt")]
|
||||
pub salt: String,
|
||||
}
|
||||
|
||||
impl From<SdaEntryEncryptionParams> for EncryptionScheme {
|
||||
fn from(sda: SdaEntryEncryptionParams) -> Self {
|
||||
EncryptionScheme::LegacySdaCompatible(LegacySdaCompatible {
|
||||
iv: sda.iv,
|
||||
salt: sda.salt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SdaAccount {
|
||||
pub account_name: String,
|
||||
pub serial_number: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub revocation_code: SecretString,
|
||||
pub shared_secret: TwoFactorSecret,
|
||||
pub token_gid: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub identity_secret: SecretString,
|
||||
#[serde(default)]
|
||||
pub server_time: u64,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub uri: SecretString,
|
||||
#[serde(default)]
|
||||
pub fully_enrolled: bool,
|
||||
pub device_id: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub secret_1: SecretString,
|
||||
#[serde(default, rename = "Session")]
|
||||
pub session: Option<secrecy::Secret<Session>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
|
||||
#[deprecated(note = "this is not used anymore, the closest equivalent is `Tokens`")]
|
||||
pub struct Session {
|
||||
#[serde(default, rename = "SessionID")]
|
||||
pub session_id: Option<String>,
|
||||
#[serde(default, rename = "SteamLogin")]
|
||||
pub steam_login: Option<String>,
|
||||
#[serde(default, rename = "SteamLoginSecure")]
|
||||
pub steam_login_secure: Option<String>,
|
||||
#[serde(default, rename = "WebCookie")]
|
||||
pub web_cookie: Option<String>,
|
||||
#[serde(default, rename = "OAuthToken")]
|
||||
pub token: Option<String>,
|
||||
#[serde(rename = "SteamID")]
|
||||
pub steam_id: Option<u64>,
|
||||
}
|
||||
|
||||
impl CloneableSecret for Session {}
|
||||
impl DebugSecret for Session {}
|
||||
|
||||
impl From<SdaAccount> for SteamGuardAccount {
|
||||
fn from(value: SdaAccount) -> Self {
|
||||
let steam_id = value
|
||||
.session
|
||||
.as_ref()
|
||||
.and_then(|s| s.expose_secret().steam_id)
|
||||
.unwrap_or(0);
|
||||
Self {
|
||||
account_name: value.account_name,
|
||||
steam_id,
|
||||
serial_number: value.serial_number,
|
||||
revocation_code: value.revocation_code,
|
||||
shared_secret: value.shared_secret,
|
||||
token_gid: value.token_gid,
|
||||
identity_secret: value.identity_secret,
|
||||
uri: value.uri,
|
||||
device_id: value.device_id,
|
||||
secret_1: value.secret_1,
|
||||
tokens: None,
|
||||
}
|
||||
}
|
||||
}
|
33
src/accountmanager/manifest.rs
Normal file
33
src/accountmanager/manifest.rs
Normal file
|
@ -0,0 +1,33 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::EncryptionScheme;
|
||||
|
||||
pub const CURRENT_MANIFEST_VERSION: u32 = 1;
|
||||
pub type Manifest = ManifestV1;
|
||||
pub type ManifestEntry = ManifestEntryV1;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ManifestV1 {
|
||||
pub version: u32,
|
||||
pub entries: Vec<ManifestEntry>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub keyring_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ManifestEntryV1 {
|
||||
pub filename: String,
|
||||
pub steam_id: u64,
|
||||
pub account_name: String,
|
||||
pub encryption: Option<EncryptionScheme>,
|
||||
}
|
||||
|
||||
impl Default for ManifestV1 {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
entries: vec![],
|
||||
keyring_id: None,
|
||||
}
|
||||
}
|
||||
}
|
518
src/accountmanager/migrate.rs
Normal file
518
src/accountmanager/migrate.rs
Normal file
|
@ -0,0 +1,518 @@
|
|||
use std::{fs::File, io::Read, path::Path};
|
||||
|
||||
use log::*;
|
||||
use secrecy::SecretString;
|
||||
use serde::{de::Error, Deserialize};
|
||||
use steamguard::SteamGuardAccount;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::encryption::EncryptionScheme;
|
||||
|
||||
use super::{
|
||||
legacy::{SdaAccount, SdaManifest},
|
||||
manifest::ManifestV1,
|
||||
steamv2::SteamMobileV2,
|
||||
winauth::parse_winauth_exports,
|
||||
EntryLoader, Manifest,
|
||||
};
|
||||
|
||||
pub(crate) fn load_and_migrate(
|
||||
manifest_path: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
||||
backup_file(manifest_path)?;
|
||||
let parent = manifest_path.parent().unwrap();
|
||||
parent.read_dir()?.for_each(|e| {
|
||||
let entry = e.unwrap();
|
||||
if entry.file_type().unwrap().is_file() {
|
||||
let path = entry.path();
|
||||
let Some(ext) = path.extension() else {
|
||||
return;
|
||||
};
|
||||
if ext == "maFile" {
|
||||
backup_file(&path).unwrap();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
do_migrate(manifest_path, passkey)
|
||||
}
|
||||
|
||||
fn do_migrate(
|
||||
manifest_path: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
) -> Result<(Manifest, Vec<SteamGuardAccount>), MigrationError> {
|
||||
let mut file = File::open(manifest_path)?;
|
||||
let mut buffer = String::new();
|
||||
file.read_to_string(&mut buffer)?;
|
||||
let mut manifest: MigratingManifest =
|
||||
deserialize_manifest(buffer).map_err(MigrationError::ManifestDeserializeFailed)?;
|
||||
|
||||
if manifest.is_encrypted() && passkey.is_none() {
|
||||
return Err(MigrationError::MissingPasskey { keyring_id: None });
|
||||
} else if !manifest.is_encrypted() && passkey.is_some() {
|
||||
// no custom error because this is an edge case, mostly user error
|
||||
return Err(MigrationError::UnexpectedError(anyhow::anyhow!("A passkey was provided but the manifest is not encrypted. Aborting migration because it would encrypt the maFiles, and you probably didn't mean to do that.")));
|
||||
}
|
||||
|
||||
let folder = manifest_path.parent().unwrap();
|
||||
let mut accounts = manifest.load_all_accounts(folder, passkey)?;
|
||||
|
||||
while !manifest.is_latest() {
|
||||
manifest = manifest.upgrade();
|
||||
|
||||
for account in accounts.iter_mut() {
|
||||
*account = account.clone().upgrade();
|
||||
}
|
||||
}
|
||||
|
||||
// HACK: force account names onto manifest entries
|
||||
let mut manifest: Manifest = manifest.into();
|
||||
let accounts: Vec<SteamGuardAccount> = accounts.into_iter().map(|a| a.into()).collect();
|
||||
for (i, entry) in manifest.entries.iter_mut().enumerate() {
|
||||
entry.account_name = accounts[i].account_name.to_lowercase();
|
||||
}
|
||||
|
||||
Ok((manifest, accounts))
|
||||
}
|
||||
|
||||
fn backup_file(path: &Path) -> anyhow::Result<()> {
|
||||
let backup_path = Path::join(
|
||||
path.parent().unwrap(),
|
||||
format!("{}.bak", path.file_name().unwrap().to_str().unwrap()),
|
||||
);
|
||||
std::fs::copy(path, backup_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(crate) enum MigrationError {
|
||||
#[error("Passkey is required to decrypt manifest")]
|
||||
MissingPasskey { keyring_id: Option<String> },
|
||||
#[error("Failed to deserialize manifest: {0}")]
|
||||
ManifestDeserializeFailed(serde_path_to_error::Error<serde_json::Error>),
|
||||
#[error("IO error when upgrading manifest: {0}")]
|
||||
IoError(#[from] std::io::Error),
|
||||
#[error("An unexpected error occurred during manifest migration: {0}")]
|
||||
UnexpectedError(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum MigratingManifest {
|
||||
Sda(SdaManifest),
|
||||
ManifestV1(ManifestV1),
|
||||
}
|
||||
|
||||
impl MigratingManifest {
|
||||
pub fn upgrade(self) -> Self {
|
||||
match self {
|
||||
Self::Sda(sda) => Self::ManifestV1(sda.into()),
|
||||
Self::ManifestV1(_) => self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_latest(&self) -> bool {
|
||||
matches!(self, Self::ManifestV1(_))
|
||||
}
|
||||
|
||||
pub fn is_encrypted(&self) -> bool {
|
||||
match self {
|
||||
Self::Sda(manifest) => manifest.entries.iter().any(|e| e.encryption.is_some()),
|
||||
Self::ManifestV1(manifest) => manifest.entries.iter().any(|e| e.encryption.is_some()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_all_accounts(
|
||||
&self,
|
||||
folder: &Path,
|
||||
passkey: Option<&SecretString>,
|
||||
) -> anyhow::Result<Vec<MigratingAccount>> {
|
||||
debug!("loading all accounts for migration");
|
||||
let accounts = match self {
|
||||
Self::Sda(sda) => {
|
||||
let (accounts, errors) = sda
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let params: Option<EncryptionScheme> =
|
||||
e.encryption.clone().map(|e| e.into());
|
||||
e.load(&Path::join(folder, &e.filename), passkey, params.as_ref())
|
||||
})
|
||||
.partition::<Vec<_>, _>(Result::is_ok);
|
||||
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
|
||||
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Failed to load some accounts: {:?}",
|
||||
errors
|
||||
));
|
||||
}
|
||||
accounts
|
||||
.into_iter()
|
||||
.map(ExternalAccount::Sda)
|
||||
.map(MigratingAccount::External)
|
||||
.collect()
|
||||
}
|
||||
Self::ManifestV1(manifest) => {
|
||||
let (accounts, errors) = manifest
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
e.load(
|
||||
&Path::join(folder, &e.filename),
|
||||
passkey,
|
||||
e.encryption.as_ref(),
|
||||
)
|
||||
})
|
||||
.partition::<Vec<_>, _>(Result::is_ok);
|
||||
let accounts: Vec<_> = accounts.into_iter().map(Result::unwrap).collect();
|
||||
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Failed to load some accounts: {:?}",
|
||||
errors
|
||||
));
|
||||
}
|
||||
accounts
|
||||
.into_iter()
|
||||
.map(MigratingAccount::ManifestV1)
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
Ok(accounts)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MigratingManifest> for Manifest {
|
||||
fn from(migrating: MigratingManifest) -> Self {
|
||||
match migrating {
|
||||
MigratingManifest::ManifestV1(manifest) => manifest,
|
||||
_ => panic!("Manifest is not at the latest version!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct JustVersion {
|
||||
version: Option<u32>,
|
||||
}
|
||||
|
||||
fn deserialize_manifest(
|
||||
text: String,
|
||||
) -> Result<MigratingManifest, serde_path_to_error::Error<serde_json::Error>> {
|
||||
let mut deser = serde_json::Deserializer::from_str(&text);
|
||||
let version: JustVersion = serde_path_to_error::deserialize(&mut deser)?;
|
||||
|
||||
debug!("deserializing manifest: version {:?}", version.version);
|
||||
let mut deser = serde_json::Deserializer::from_str(&text);
|
||||
|
||||
match version.version {
|
||||
Some(1) => {
|
||||
let manifest: ManifestV1 = serde_path_to_error::deserialize(&mut deser)?;
|
||||
Ok(MigratingManifest::ManifestV1(manifest))
|
||||
}
|
||||
None => {
|
||||
let manifest: SdaManifest = serde_path_to_error::deserialize(&mut deser)?;
|
||||
Ok(MigratingManifest::Sda(manifest))
|
||||
}
|
||||
_ => {
|
||||
// HACK: there's no way to construct the Path type, so we create it by forcing a deserialize error
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Dummy;
|
||||
impl<'de> Deserialize<'de> for Dummy {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
|
||||
Err(D::Error::custom("Unknown manifest version".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
let mut deser = serde_json::Deserializer::from_str("");
|
||||
let err = serde_path_to_error::deserialize::<_, Dummy>(&mut deser).unwrap_err();
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum MigratingAccount {
|
||||
External(ExternalAccount),
|
||||
ManifestV1(SteamGuardAccount),
|
||||
}
|
||||
|
||||
impl MigratingAccount {
|
||||
pub fn upgrade(self) -> Self {
|
||||
match self {
|
||||
Self::External(account) => Self::ManifestV1(account.into()),
|
||||
Self::ManifestV1(_) => self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_latest(&self) -> bool {
|
||||
matches!(self, Self::ManifestV1(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MigratingAccount> for SteamGuardAccount {
|
||||
fn from(migrating: MigratingAccount) -> Self {
|
||||
match migrating {
|
||||
MigratingAccount::ManifestV1(account) => account,
|
||||
_ => panic!("Account is not at the latest version!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_and_upgrade_external_accounts(path: &Path) -> anyhow::Result<Vec<SteamGuardAccount>> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut buf = vec![];
|
||||
file.read_to_end(&mut buf)?;
|
||||
let mut deser = serde_json::Deserializer::from_slice(&buf);
|
||||
let accounts = match serde_path_to_error::deserialize(&mut deser) {
|
||||
Ok(account) => {
|
||||
vec![MigratingAccount::External(account)]
|
||||
}
|
||||
Err(json_err) => {
|
||||
// the file is not JSON, so it's probably a winauth export
|
||||
match parse_winauth_exports(buf) {
|
||||
Ok(accounts) => accounts
|
||||
.into_iter()
|
||||
.map(MigratingAccount::External)
|
||||
.collect(),
|
||||
Err(winauth_err) => {
|
||||
bail!(
|
||||
"Failed to parse as JSON: {}\nFailed to parse as Winauth export: {}",
|
||||
json_err,
|
||||
winauth_err
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(accounts
|
||||
.into_iter()
|
||||
.map(|mut account| {
|
||||
while !account.is_latest() {
|
||||
account = account.upgrade();
|
||||
}
|
||||
account.into()
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub(crate) enum ExternalAccount {
|
||||
Sda(SdaAccount),
|
||||
SteamMobileV2(SteamMobileV2),
|
||||
}
|
||||
|
||||
impl From<ExternalAccount> for SteamGuardAccount {
|
||||
fn from(account: ExternalAccount) -> Self {
|
||||
match account {
|
||||
ExternalAccount::Sda(account) => account.into(),
|
||||
ExternalAccount::SteamMobileV2(account) => account.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tempfile::TempDir;
|
||||
|
||||
use crate::{accountmanager::CURRENT_MANIFEST_VERSION, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn should_migrate_to_latest_version() -> anyhow::Result<()> {
|
||||
#[derive(Debug)]
|
||||
struct Test {
|
||||
manifest: &'static str,
|
||||
passkey: Option<SecretString>,
|
||||
}
|
||||
let cases = vec![
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/1-account/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/1-account-encrypted/manifest.json",
|
||||
passkey: Some(SecretString::new("password".into())),
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/2-account/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/missing-account-name/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/no-webcookie/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/null-oauthtoken/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/difficult-migration/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
manifest: "src/fixtures/maFiles/compat/missing-unnecessary/manifest.json",
|
||||
passkey: None,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let (manifest, accounts) = do_migrate(Path::new(case.manifest), case.passkey.as_ref())?;
|
||||
assert_eq!(manifest.version, CURRENT_MANIFEST_VERSION);
|
||||
assert_eq!(manifest.entries[0].account_name, "example");
|
||||
assert_eq!(manifest.entries[0].steam_id, 1234);
|
||||
assert_eq!(accounts[0].account_name, "example");
|
||||
assert_eq!(accounts[0].steam_id, 1234);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_migrate_single_accounts() -> anyhow::Result<()> {
|
||||
#[derive(Debug)]
|
||||
struct Test {
|
||||
mafile: &'static str,
|
||||
account_name: &'static str,
|
||||
steam_id: u64,
|
||||
}
|
||||
let cases = vec![
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/1-account/1234.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/2-account/1234.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/2-account/5678.maFile",
|
||||
account_name: "example2",
|
||||
steam_id: 5678,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/missing-account-name/1234.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/no-webcookie/nowebcookie.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/null-oauthtoken/nulloauthtoken.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/steamv2/sample.maFile",
|
||||
account_name: "afarihm",
|
||||
steam_id: 76561199441992970,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/winauth/exports.txt",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
Test {
|
||||
mafile: "src/fixtures/maFiles/compat/missing-unnecessary/1234.maFile",
|
||||
account_name: "example",
|
||||
steam_id: 1234,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let accounts = load_and_upgrade_external_accounts(Path::new(case.mafile))?;
|
||||
let account = accounts[0].clone();
|
||||
assert_eq!(account.account_name, case.account_name);
|
||||
assert_eq!(account.steam_id, case.steam_id);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_migrate_to_latest_version_save_and_load_again() -> anyhow::Result<()> {
|
||||
#[derive(Debug)]
|
||||
struct Test {
|
||||
dir: &'static str,
|
||||
passkey: Option<SecretString>,
|
||||
}
|
||||
let cases = vec![
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/1-account/",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/1-account-encrypted/",
|
||||
passkey: Some(SecretString::new("password".into())),
|
||||
},
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/2-account/",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/missing-account-name/",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/no-webcookie/",
|
||||
passkey: None,
|
||||
},
|
||||
Test {
|
||||
dir: "src/fixtures/maFiles/compat/null-oauthtoken/",
|
||||
passkey: None,
|
||||
},
|
||||
];
|
||||
for case in cases {
|
||||
eprintln!("testing: {:?}", case);
|
||||
let temp = TempDir::new()?;
|
||||
for file in std::fs::read_dir(case.dir)? {
|
||||
let file = file?;
|
||||
let path = file.path();
|
||||
let dest = temp.path().join(path.file_name().unwrap());
|
||||
std::fs::copy(&path, dest)?;
|
||||
}
|
||||
|
||||
let (manifest, accounts) = do_migrate(
|
||||
Path::join(temp.path(), "manifest.json").as_path(),
|
||||
case.passkey.as_ref(),
|
||||
)?;
|
||||
assert_eq!(manifest.version, CURRENT_MANIFEST_VERSION);
|
||||
assert_eq!(manifest.entries[0].account_name, "example");
|
||||
assert_eq!(manifest.entries[0].steam_id, 1234);
|
||||
assert_eq!(accounts[0].account_name, "example");
|
||||
assert_eq!(accounts[0].steam_id, 1234);
|
||||
|
||||
let mut manager =
|
||||
AccountManager::from_manifest(manifest, temp.path().to_str().unwrap().to_owned());
|
||||
manager.submit_passkey(case.passkey.clone());
|
||||
manager.register_accounts(accounts);
|
||||
manager.save()?;
|
||||
|
||||
let path = Path::join(temp.path(), "manifest.json");
|
||||
let mut manager = AccountManager::load(path.as_path())?;
|
||||
manager.submit_passkey(case.passkey.clone());
|
||||
manager.load_accounts()?;
|
||||
let account = manager.get_or_load_account("example")?;
|
||||
let account = account.lock().unwrap();
|
||||
assert_eq!(account.account_name, "example");
|
||||
assert_eq!(account.steam_id, 1234);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
73
src/accountmanager/steamv2.rs
Normal file
73
src/accountmanager/steamv2.rs
Normal file
|
@ -0,0 +1,73 @@
|
|||
use secrecy::SecretString;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
use steamguard::{token::TwoFactorSecret, SteamGuardAccount};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Defines the schema for loading steamguard accounts extracted from backups of the official Steam app (v2).
|
||||
///
|
||||
/// ```json
|
||||
/// {
|
||||
/// "steamid": "X",
|
||||
/// "shared_secret": "X",
|
||||
/// "serial_number": "X",
|
||||
/// "revocation_code": "X",
|
||||
/// "uri": "otpauth:\/\/totp\/Steam:USERNAME?secret=X&issuer=Steam",
|
||||
/// "server_time": "X",
|
||||
/// "account_name": "USERNAME",
|
||||
/// "token_gid": "X",
|
||||
/// "identity_secret": "X",
|
||||
/// "secret_1": "X",
|
||||
/// "status": 1,
|
||||
/// "steamguard_scheme": "2"
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SteamMobileV2 {
|
||||
#[serde(deserialize_with = "de_parse_number")]
|
||||
pub steamid: u64,
|
||||
pub shared_secret: TwoFactorSecret,
|
||||
pub serial_number: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub revocation_code: SecretString,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub uri: SecretString,
|
||||
pub server_time: Option<serde_json::Value>,
|
||||
pub account_name: String,
|
||||
pub token_gid: String,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub identity_secret: SecretString,
|
||||
#[serde(with = "crate::secret_string")]
|
||||
pub secret_1: SecretString,
|
||||
pub status: Option<serde_json::Value>,
|
||||
pub steamguard_scheme: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl From<SteamMobileV2> for SteamGuardAccount {
|
||||
fn from(account: SteamMobileV2) -> Self {
|
||||
Self {
|
||||
shared_secret: account.shared_secret,
|
||||
identity_secret: account.identity_secret,
|
||||
revocation_code: account.revocation_code,
|
||||
uri: account.uri,
|
||||
account_name: account.account_name,
|
||||
token_gid: account.token_gid,
|
||||
serial_number: account.serial_number,
|
||||
steam_id: account.steamid,
|
||||
// device_id is unknown, so we just make one up
|
||||
device_id: format!("android:{}", Uuid::new_v4()),
|
||||
secret_1: account.secret_1,
|
||||
tokens: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn de_parse_number<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
||||
Ok(match Value::deserialize(deserializer)? {
|
||||
Value::String(s) => s.parse().map_err(serde::de::Error::custom)?,
|
||||
Value::Number(num) => num
|
||||
.as_u64()
|
||||
.ok_or(serde::de::Error::custom("Invalid number"))?,
|
||||
_ => return Err(serde::de::Error::custom("wrong type")),
|
||||
})
|
||||
}
|
50
src/accountmanager/winauth.rs
Normal file
50
src/accountmanager/winauth.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
//! Accounts exported from Winauth are in the following format:
|
||||
//!
|
||||
//! One account per line, with each account represented as a URL.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! otpauth://totp/Steam:<steamaccountname>?secret=<ABCDEFG1234_secret_dunno_what_for>&digits=5&issuer=Steam&deviceid=<URL_Escaped_device_name>&data=<url_encoded_data_json>
|
||||
//! ```
|
||||
//!
|
||||
//! The `data` field is a URL encoded JSON object with the following fields:
|
||||
//!
|
||||
//! ```json
|
||||
//! {"steamid":"<steam_id>","status":1,"shared_secret":"<shared_secret>","serial_number":"<serial_number>","revocation_code":"<revocation_code>","uri":"<uri>","server_time":"<server_time>","account_name":"<steam_login_name>","token_gid":"<token_gid>","identity_secret":"<identity_secret>","secret_1":"<secret_1>","steamguard_scheme":"2"}
|
||||
//! ```
|
||||
|
||||
use anyhow::Context;
|
||||
use log::*;
|
||||
use reqwest::Url;
|
||||
|
||||
use super::migrate::ExternalAccount;
|
||||
|
||||
pub(crate) fn parse_winauth_exports(buf: Vec<u8>) -> anyhow::Result<Vec<ExternalAccount>> {
|
||||
let buf = String::from_utf8(buf)?;
|
||||
let mut accounts = Vec::new();
|
||||
for line in buf.split('\n') {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let url = Url::parse(line).context("parsing as winauth export URL")?;
|
||||
let mut query = url.query_pairs();
|
||||
let issuer = query
|
||||
.find(|(key, _)| key == "issuer")
|
||||
.context("missing issuer field")?
|
||||
.1;
|
||||
if issuer != "Steam" {
|
||||
debug!("skipping non-Steam account: {}", issuer);
|
||||
continue;
|
||||
}
|
||||
let data = query
|
||||
.find(|(key, _)| key == "data")
|
||||
.context("missing data field")?
|
||||
.1;
|
||||
|
||||
trace!("data: {}", data);
|
||||
|
||||
let mut deser = serde_json::Deserializer::from_str(&data);
|
||||
let account = serde_path_to_error::deserialize(&mut deser)?;
|
||||
accounts.push(account);
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
236
src/commands.rs
Normal file
236
src/commands.rs
Normal file
|
@ -0,0 +1,236 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use clap_complete::Shell;
|
||||
use secrecy::SecretString;
|
||||
use std::str::FromStr;
|
||||
use steamguard::{transport::Transport, SteamGuardAccount};
|
||||
|
||||
use crate::AccountManager;
|
||||
|
||||
pub mod code;
|
||||
pub mod completions;
|
||||
pub mod confirm;
|
||||
pub mod debug;
|
||||
pub mod decrypt;
|
||||
pub mod encrypt;
|
||||
pub mod import;
|
||||
#[cfg(feature = "qr")]
|
||||
pub mod qr;
|
||||
pub mod qr_login;
|
||||
pub mod remove;
|
||||
pub mod setup;
|
||||
|
||||
pub use code::CodeCommand;
|
||||
pub use completions::CompletionsCommand;
|
||||
pub use confirm::ConfirmCommand;
|
||||
pub use debug::DebugCommand;
|
||||
pub use decrypt::DecryptCommand;
|
||||
pub use encrypt::EncryptCommand;
|
||||
pub use import::ImportCommand;
|
||||
#[cfg(feature = "qr")]
|
||||
pub use qr::QrCommand;
|
||||
pub use qr_login::QrLoginCommand;
|
||||
pub use remove::RemoveCommand;
|
||||
pub use setup::SetupCommand;
|
||||
|
||||
/// A command that does not operate on the manifest or individual accounts.
|
||||
pub(crate) trait ConstCommand {
|
||||
fn execute(&self) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
/// A command that operates the manifest as a whole
|
||||
pub(crate) trait ManifestCommand<T>
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
/// A command that operates on individual accounts.
|
||||
pub(crate) trait AccountCommand<T>
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
pub(crate) enum CommandType<T>
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
Const(Box<dyn ConstCommand>),
|
||||
Manifest(Box<dyn ManifestCommand<T>>),
|
||||
Account(Box<dyn AccountCommand<T>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(name="steamguard-cli", bin_name="steamguard", author, version, about = "Generate Steam 2FA codes and confirm Steam trades from the command line.", long_about = None)]
|
||||
pub(crate) struct Args {
|
||||
#[clap(flatten)]
|
||||
pub global: GlobalArgs,
|
||||
|
||||
#[clap(subcommand)]
|
||||
pub sub: Option<Subcommands>,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub code: CodeCommand,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
pub(crate) struct GlobalArgs {
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
conflicts_with = "all",
|
||||
help = "Steam username, case-sensitive.",
|
||||
long_help = "Select the account you want by steam username. Case-sensitive. By default, the first account in the manifest is selected."
|
||||
)]
|
||||
pub username: Option<String>,
|
||||
#[clap(
|
||||
long,
|
||||
conflicts_with = "all",
|
||||
help = "Steam account password. You really shouldn't use this if you can avoid it.",
|
||||
env = "STEAMGUARD_CLI_STEAM_PASSWORD"
|
||||
)]
|
||||
pub password: Option<SecretString>,
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
conflicts_with = "username",
|
||||
help = "Select all accounts in the manifest."
|
||||
)]
|
||||
pub all: bool,
|
||||
/// The path to the maFiles directory.
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
env = "STEAMGUARD_CLI_MAFILES",
|
||||
help = "Specify which folder your maFiles are in. This should be a path to a folder that contains manifest.json. Default: ~/.config/steamguard-cli/maFiles"
|
||||
)]
|
||||
pub mafiles_path: Option<String>,
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
env = "STEAMGUARD_CLI_PASSKEY",
|
||||
help = "Specify your encryption passkey."
|
||||
)]
|
||||
pub passkey: Option<SecretString>,
|
||||
#[clap(short, long, value_enum, default_value_t=Verbosity::Info, help = "Set the log level. Be warned, trace is capable of printing sensitive data.")]
|
||||
pub verbosity: Verbosity,
|
||||
|
||||
#[cfg(feature = "updater")]
|
||||
#[clap(
|
||||
long,
|
||||
help = "Disable checking for updates.",
|
||||
long_help = "Disable checking for updates. By default, steamguard-cli will check for updates every now and then. This can be disabled with this flag."
|
||||
)]
|
||||
pub no_update_check: bool,
|
||||
|
||||
#[clap(
|
||||
long,
|
||||
env = "HTTP_PROXY",
|
||||
help = "Use a proxy for HTTP requests.",
|
||||
long_help = "Use a proxy for HTTP requests. This is useful if you are behind a firewall and need to use a proxy to access the internet."
|
||||
)]
|
||||
pub http_proxy: Option<String>,
|
||||
|
||||
#[clap(
|
||||
long,
|
||||
help = "Credentials to use for proxy authentication in the format username:password."
|
||||
)]
|
||||
pub proxy_credentials: Option<String>,
|
||||
|
||||
#[clap(
|
||||
long,
|
||||
help = "Accept invalid TLS certificates.",
|
||||
long_help = "Accept invalid TLS certificates. Be warned, this is insecure and enables man-in-the-middle attacks."
|
||||
)]
|
||||
pub danger_accept_invalid_certs: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Subcommand)]
|
||||
pub(crate) enum Subcommands {
|
||||
Debug(DebugCommand),
|
||||
Completion(CompletionsCommand),
|
||||
Setup(SetupCommand),
|
||||
Import(ImportCommand),
|
||||
#[clap(alias = "trade")]
|
||||
Confirm(ConfirmCommand),
|
||||
Remove(RemoveCommand),
|
||||
Encrypt(EncryptCommand),
|
||||
Decrypt(DecryptCommand),
|
||||
Code(CodeCommand),
|
||||
#[cfg(feature = "qr")]
|
||||
Qr(QrCommand),
|
||||
QrLogin(QrLoginCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub(crate) enum Verbosity {
|
||||
Error = 0,
|
||||
Warn = 1,
|
||||
Info = 2,
|
||||
Debug = 3,
|
||||
Trace = 4,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Verbosity {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"{}",
|
||||
match self {
|
||||
Verbosity::Error => "error",
|
||||
Verbosity::Warn => "warn",
|
||||
Verbosity::Info => "info",
|
||||
Verbosity::Debug => "debug",
|
||||
Verbosity::Trace => "trace",
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Verbosity {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"error" => Ok(Verbosity::Error),
|
||||
"warn" => Ok(Verbosity::Warn),
|
||||
"info" => Ok(Verbosity::Info),
|
||||
"debug" => Ok(Verbosity::Debug),
|
||||
"trace" => Ok(Verbosity::Trace),
|
||||
_ => Err(anyhow!("Invalid verbosity level: {}", s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HACK: the derive API doesn't support default subcommands, so we are going to make it so that it'll be easier to switch over when it's implemented.
|
||||
// See: https://github.com/clap-rs/clap/issues/3857
|
||||
impl From<Args> for CodeCommand {
|
||||
fn from(args: Args) -> Self {
|
||||
args.code
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verify_cli() {
|
||||
use clap::CommandFactory;
|
||||
Args::command().debug_assert()
|
||||
}
|
||||
}
|
50
src/commands/code.rs
Normal file
50
src/commands/code.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
use std::{
|
||||
sync::{Arc, Mutex},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use log::*;
|
||||
use steamguard::{steamapi, SteamGuardAccount};
|
||||
|
||||
use crate::AccountManager;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Generate 2FA codes")]
|
||||
pub struct CodeCommand {
|
||||
#[clap(
|
||||
long,
|
||||
help = "Assume the computer's time is correct. Don't ask Steam for the time when generating codes."
|
||||
)]
|
||||
pub offline: bool,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for CodeCommand
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
let server_time = if self.offline {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()
|
||||
} else {
|
||||
steamapi::get_server_time(transport)?.server_time()
|
||||
};
|
||||
debug!("Time used to generate codes: {}", server_time);
|
||||
|
||||
for account in accounts {
|
||||
let account = account.lock().unwrap();
|
||||
info!("Generating code for {}", account.account_name);
|
||||
trace!("{:?}", account);
|
||||
let code = account.generate_code(server_time);
|
||||
println!("{}", code);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
23
src/commands/completions.rs
Normal file
23
src/commands/completions.rs
Normal file
|
@ -0,0 +1,23 @@
|
|||
use clap::CommandFactory;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Generate shell completions")]
|
||||
pub struct CompletionsCommand {
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
value_enum,
|
||||
help = "The shell to generate completions for."
|
||||
)]
|
||||
pub shell: Shell,
|
||||
}
|
||||
|
||||
impl ConstCommand for CompletionsCommand {
|
||||
fn execute(&self) -> anyhow::Result<()> {
|
||||
let mut app = Args::command_for_update();
|
||||
clap_complete::generate(self.shell, &mut app, "steamguard", &mut std::io::stdout());
|
||||
Ok(())
|
||||
}
|
||||
}
|
168
src/commands/confirm.rs
Normal file
168
src/commands/confirm.rs
Normal file
|
@ -0,0 +1,168 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::tty::IsTty;
|
||||
use log::*;
|
||||
use steamguard::{Confirmation, Confirmer, ConfirmerError};
|
||||
|
||||
use crate::{tui, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Interactive interface for steam mobile confirmations")]
|
||||
pub struct ConfirmCommand {
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
help = "Accept all open mobile confirmations. Does not open interactive interface."
|
||||
)]
|
||||
pub accept_all: bool,
|
||||
#[clap(
|
||||
short,
|
||||
long,
|
||||
help = "If submitting a confirmation response fails, exit immediately."
|
||||
)]
|
||||
pub fail_fast: bool,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for ConfirmCommand
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
for a in accounts {
|
||||
let mut account = a.lock().unwrap();
|
||||
|
||||
if !account.is_logged_in() {
|
||||
info!("Account does not have tokens, logging in");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
}
|
||||
|
||||
info!("{}: Checking for confirmations", account.account_name);
|
||||
let confirmations: Vec<Confirmation>;
|
||||
loop {
|
||||
let confirmer = Confirmer::new(transport.clone(), &account);
|
||||
|
||||
match confirmer.get_confirmations() {
|
||||
Ok(confs) => {
|
||||
confirmations = confs;
|
||||
break;
|
||||
}
|
||||
Err(ConfirmerError::InvalidTokens) => {
|
||||
info!("obtaining new tokens");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to get confirmations: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if confirmations.is_empty() {
|
||||
info!("{}: No confirmations", account.account_name);
|
||||
continue;
|
||||
}
|
||||
|
||||
let confirmer = Confirmer::new(transport.clone(), &account);
|
||||
let mut any_failed = false;
|
||||
|
||||
fn submit_loop(
|
||||
f: impl Fn() -> Result<(), ConfirmerError>,
|
||||
fail_fast: bool,
|
||||
) -> Result<(), ConfirmerError> {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match f() {
|
||||
Ok(_) => break,
|
||||
Err(ConfirmerError::InvalidTokens) => {
|
||||
error!("Invalid tokens, but they should be valid already. This is weird, stopping.");
|
||||
return Err(ConfirmerError::InvalidTokens);
|
||||
}
|
||||
Err(ConfirmerError::NetworkFailure(err)) => {
|
||||
error!("{}", err);
|
||||
return Err(ConfirmerError::NetworkFailure(err));
|
||||
}
|
||||
Err(ConfirmerError::DeserializeError(err)) => {
|
||||
error!("Failed to deserialize the response, but the submission may have succeeded: {}", err);
|
||||
return Err(ConfirmerError::DeserializeError(err));
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("submit confirmation result: {}", err);
|
||||
if fail_fast || attempts >= 3 {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
let wait = std::time::Duration::from_secs(3 * attempts);
|
||||
info!(
|
||||
"retrying in {} seconds (attempt {})",
|
||||
wait.as_secs(),
|
||||
attempts
|
||||
);
|
||||
std::thread::sleep(wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
if self.accept_all {
|
||||
info!("accepting all confirmations");
|
||||
match submit_loop(
|
||||
|| confirmer.accept_confirmations(&confirmations),
|
||||
self.fail_fast,
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("accept confirmation result: {}", err);
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
} else if std::io::stdout().is_tty() {
|
||||
let (accept, deny) = tui::prompt_confirmation_menu(confirmations)?;
|
||||
match submit_loop(|| confirmer.accept_confirmations(&accept), self.fail_fast) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("accept confirmation result: {}", err);
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
match submit_loop(|| confirmer.deny_confirmations(&deny), self.fail_fast) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
warn!("deny confirmation result: {}", err);
|
||||
if self.fail_fast {
|
||||
return Err(err.into());
|
||||
}
|
||||
any_failed = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("not a tty, not showing menu");
|
||||
for conf in &confirmations {
|
||||
println!("{}", conf.description());
|
||||
}
|
||||
}
|
||||
|
||||
if any_failed {
|
||||
error!("Failed to respond to some confirmations.");
|
||||
}
|
||||
}
|
||||
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
115
src/commands/debug.rs
Normal file
115
src/commands/debug.rs
Normal file
|
@ -0,0 +1,115 @@
|
|||
use log::*;
|
||||
use steamguard::{Confirmation, ConfirmationType};
|
||||
|
||||
use crate::{debug::parse_json_stripped, tui};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser, Default)]
|
||||
#[clap(about = "Debug stuff, not useful for most users.")]
|
||||
pub struct DebugCommand {
|
||||
#[clap(long, help = "Show a text prompt.")]
|
||||
pub demo_prompt: bool,
|
||||
#[clap(long, help = "Show a \"press any key\" prompt.")]
|
||||
pub demo_pause: bool,
|
||||
#[clap(long, help = "Show a character prompt.")]
|
||||
pub demo_prompt_char: bool,
|
||||
#[clap(long, help = "Show an example confirmation menu using dummy data.")]
|
||||
pub demo_conf_menu: bool,
|
||||
|
||||
#[clap(
|
||||
long,
|
||||
help = "Read the specified file, parse it, strip values, and print the result."
|
||||
)]
|
||||
pub print_stripped_json: Option<String>,
|
||||
}
|
||||
|
||||
impl ConstCommand for DebugCommand {
|
||||
fn execute(&self) -> anyhow::Result<()> {
|
||||
if self.demo_prompt {
|
||||
demo_prompt();
|
||||
}
|
||||
if self.demo_pause {
|
||||
demo_pause();
|
||||
}
|
||||
if self.demo_prompt_char {
|
||||
demo_prompt_char();
|
||||
}
|
||||
if self.demo_conf_menu {
|
||||
demo_confirmation_menu();
|
||||
}
|
||||
if let Some(path) = self.print_stripped_json.as_ref() {
|
||||
debug_print_json(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn demo_prompt() {
|
||||
print!("Prompt: ");
|
||||
let result = tui::prompt();
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
|
||||
pub fn demo_pause() {
|
||||
let mut x = 0;
|
||||
loop {
|
||||
tui::pause();
|
||||
x += 1;
|
||||
println!("looped {} times", x);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn demo_prompt_char() {
|
||||
println!("Showing prompt");
|
||||
let result = tui::prompt_char("Continue?", "yn");
|
||||
println!("Result: {}", result);
|
||||
let result = tui::prompt_char("Continue?", "Yn");
|
||||
println!("Result: {}", result);
|
||||
let result = tui::prompt_char("Continue?", "yN");
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
|
||||
pub fn demo_confirmation_menu() {
|
||||
info!("showing demo menu");
|
||||
let (accept, deny) = tui::prompt_confirmation_menu(vec![
|
||||
Confirmation {
|
||||
id: "1234".to_owned(),
|
||||
nonce: "12345".to_owned(),
|
||||
conf_type: ConfirmationType::Trade,
|
||||
creator_id: "09870987".to_owned(),
|
||||
headline: "example confirmation".into(),
|
||||
type_name: "Trade".to_owned(),
|
||||
creation_time: 1687457923,
|
||||
cancel: "Cancel".to_owned(),
|
||||
accept: "Confirm".to_owned(),
|
||||
icon: Some("".to_owned()),
|
||||
multi: false,
|
||||
summary: vec![],
|
||||
},
|
||||
Confirmation {
|
||||
id: "1234".to_owned(),
|
||||
nonce: "12345".to_owned(),
|
||||
conf_type: ConfirmationType::MarketSell,
|
||||
creator_id: "09870987".to_owned(),
|
||||
headline: "example confirmation".into(),
|
||||
type_name: "Market Sell".to_owned(),
|
||||
creation_time: 1687457923,
|
||||
cancel: "Cancel".to_owned(),
|
||||
accept: "Confirm".to_owned(),
|
||||
icon: Some("".to_owned()),
|
||||
multi: false,
|
||||
summary: vec![],
|
||||
},
|
||||
])
|
||||
.expect("confirmation menu demo failed");
|
||||
println!("accept: {}, deny: {}", accept.len(), deny.len());
|
||||
}
|
||||
|
||||
fn debug_print_json(path: &str) -> anyhow::Result<()> {
|
||||
let json = std::fs::read_to_string(path)?;
|
||||
let v = parse_json_stripped(&json)?;
|
||||
println!("{}", serde_json::to_string_pretty(&v)?);
|
||||
|
||||
Ok(())
|
||||
}
|
62
src/commands/decrypt.rs
Normal file
62
src/commands/decrypt.rs
Normal file
|
@ -0,0 +1,62 @@
|
|||
use log::*;
|
||||
|
||||
use crate::{AccountManager, ManifestAccountLoadError};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Decrypt all maFiles")]
|
||||
pub struct DecryptCommand;
|
||||
|
||||
impl<T> ManifestCommand<T> for DecryptCommand
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
load_accounts_with_prompts(manager)?;
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
if let Some(keyring_id) = manager.keyring_id() {
|
||||
match crate::encryption::clear_passkey(keyring_id.clone()) {
|
||||
Ok(_) => {
|
||||
info!("Cleared passkey from keyring");
|
||||
manager.clear_keyring_id();
|
||||
}
|
||||
Err(e) => warn!("Failed to clear passkey from keyring: {}", e),
|
||||
}
|
||||
}
|
||||
for entry in manager.iter_mut() {
|
||||
entry.encryption = None;
|
||||
}
|
||||
manager.submit_passkey(None);
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn load_accounts_with_prompts(manager: &mut AccountManager) -> anyhow::Result<()> {
|
||||
loop {
|
||||
match manager.load_accounts() {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(
|
||||
ManifestAccountLoadError::MissingPasskey
|
||||
| ManifestAccountLoadError::IncorrectPasskey,
|
||||
) => {
|
||||
if manager.has_passkey() {
|
||||
error!("Incorrect passkey");
|
||||
}
|
||||
let passkey = Some(crate::tui::prompt_passkey()?);
|
||||
manager.submit_passkey(passkey);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Could not load accounts: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
75
src/commands/encrypt.rs
Normal file
75
src/commands/encrypt.rs
Normal file
|
@ -0,0 +1,75 @@
|
|||
use log::*;
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use crate::{
|
||||
encryption::{EncryptionScheme, EntryEncryptor},
|
||||
tui, AccountManager,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Encrypt all maFiles")]
|
||||
pub struct EncryptCommand;
|
||||
|
||||
impl<T> ManifestCommand<T> for EncryptCommand
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
if !manager.has_passkey() {
|
||||
let passkey: Option<SecretString>;
|
||||
loop {
|
||||
let passkey1 = tui::prompt_passkey()?;
|
||||
if passkey1.expose_secret().is_empty() {
|
||||
error!("Passkey cannot be empty, try again.");
|
||||
continue;
|
||||
}
|
||||
let passkey_confirm = rpassword::prompt_password("Confirm encryption passkey: ")
|
||||
.map(SecretString::new)?;
|
||||
if passkey1.expose_secret() == passkey_confirm.expose_secret() {
|
||||
passkey = Some(passkey1);
|
||||
break;
|
||||
}
|
||||
error!("Passkeys do not match, try again.");
|
||||
}
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
{
|
||||
if tui::prompt_char(
|
||||
"Would you like to store the passkey in your system keyring?",
|
||||
"yn",
|
||||
) == 'y'
|
||||
{
|
||||
let keyring_id = crate::encryption::generate_keyring_id();
|
||||
match crate::encryption::store_passkey(
|
||||
keyring_id.clone(),
|
||||
passkey.clone().unwrap(),
|
||||
) {
|
||||
Ok(_) => {
|
||||
info!("Stored passkey in keyring");
|
||||
manager.set_keyring_id(keyring_id);
|
||||
}
|
||||
Err(e) => warn!(
|
||||
"Failed to store passkey in keyring, continuing anyway: {}",
|
||||
e
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
manager.submit_passkey(passkey);
|
||||
}
|
||||
manager.load_accounts()?;
|
||||
for entry in manager.iter_mut() {
|
||||
entry.encryption = Some(EncryptionScheme::generate());
|
||||
}
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
71
src/commands/import.rs
Normal file
71
src/commands/import.rs
Normal file
|
@ -0,0 +1,71 @@
|
|||
use std::path::Path;
|
||||
|
||||
use log::*;
|
||||
|
||||
use crate::{accountmanager::ManifestAccountImportError, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser, Default)]
|
||||
#[clap(
|
||||
about = "Import an account with steamguard already set up. It must not be encrypted. If you haven't used steamguard-cli before, you probably don't need to use this command."
|
||||
)]
|
||||
pub struct ImportCommand {
|
||||
#[clap(long, help = "Paths to one or more maFiles, eg. \"./gaben.maFile\"")]
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> ManifestCommand<T> for ImportCommand
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
manager: &mut AccountManager,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut accounts_added = 0;
|
||||
for file_path in self.files.iter() {
|
||||
debug!("loading entry: {:?}", file_path);
|
||||
match manager.import_account(file_path) {
|
||||
Ok(_) => {
|
||||
info!("Imported account: {}", &file_path);
|
||||
}
|
||||
Err(ManifestAccountImportError::AlreadyExists { .. }) => {
|
||||
warn!("Account already exists: {} -- Ignoring", &file_path);
|
||||
}
|
||||
Err(ManifestAccountImportError::DeserializationFailed(orig_err)) => {
|
||||
debug!("Falling back to external account import",);
|
||||
|
||||
let path = Path::new(&file_path);
|
||||
let accounts =
|
||||
match crate::accountmanager::migrate::load_and_upgrade_external_accounts(
|
||||
path,
|
||||
) {
|
||||
Ok(accounts) => accounts,
|
||||
Err(err) => {
|
||||
error!("Failed to import account: {} {}", &file_path, err);
|
||||
error!("The original error was: {}", orig_err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
manager.add_account(account);
|
||||
info!("Imported account: {}", &file_path);
|
||||
accounts_added += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("Failed to import account: {} {}", &file_path, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
if accounts_added > 0 {
|
||||
info!("Imported {} accounts", accounts_added);
|
||||
}
|
||||
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
60
src/commands/qr.rs
Normal file
60
src/commands/qr.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use log::*;
|
||||
use qrcode::QrCode;
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use crate::AccountManager;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Generate QR codes. This *will* print sensitive data to stdout.")]
|
||||
pub struct QrCommand {
|
||||
#[clap(
|
||||
long,
|
||||
help = "Force using ASCII chars to generate QR codes. Useful for terminals that don't support unicode."
|
||||
)]
|
||||
pub ascii: bool,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for QrCommand
|
||||
where
|
||||
T: Transport,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
_transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
_args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
use anyhow::Context;
|
||||
|
||||
info!("Generating QR codes for {} accounts", accounts.len());
|
||||
|
||||
for account in accounts {
|
||||
let account = account.lock().unwrap();
|
||||
let qr = QrCode::new(account.uri.expose_secret())
|
||||
.context(format!("generating qr code for {}", account.account_name))?;
|
||||
|
||||
info!("Printing QR code for {}", account.account_name);
|
||||
let qr_string = if self.ascii {
|
||||
qr.render()
|
||||
.light_color(' ')
|
||||
.dark_color('#')
|
||||
.module_dimensions(2, 1)
|
||||
.build()
|
||||
} else {
|
||||
use qrcode::render::unicode;
|
||||
qr.render::<unicode::Dense1x2>()
|
||||
.dark_color(unicode::Dense1x2::Light)
|
||||
.light_color(unicode::Dense1x2::Dark)
|
||||
.build()
|
||||
};
|
||||
|
||||
println!("{}", qr_string);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
128
src/commands/qr_login.rs
Normal file
128
src/commands/qr_login.rs
Normal file
|
@ -0,0 +1,128 @@
|
|||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use log::*;
|
||||
use rqrr::PreparedImage;
|
||||
use steamguard::{QrApprover, QrApproverError};
|
||||
|
||||
use crate::AccountManager;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Log in to Steam on another device using the QR code that it's displaying.")]
|
||||
pub struct QrLoginCommand {
|
||||
#[clap(flatten)]
|
||||
login_url_source: LoginUrlSource,
|
||||
}
|
||||
|
||||
impl<T> AccountCommand<T> for QrLoginCommand
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
_manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
accounts.len() == 1,
|
||||
"You can only log in to one account at a time."
|
||||
);
|
||||
|
||||
let mut account = accounts[0].lock().unwrap();
|
||||
|
||||
info!("Approving login to {}", account.account_name);
|
||||
|
||||
if account.tokens.is_none() {
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
}
|
||||
|
||||
let url = self.login_url_source.url()?;
|
||||
debug!("Using login URL to approve: {}", url);
|
||||
loop {
|
||||
let Some(tokens) = account.tokens.as_ref() else {
|
||||
error!(
|
||||
"No tokens found for {}. Can't approve login if we aren't logged in ourselves.",
|
||||
account.account_name
|
||||
);
|
||||
return Err(anyhow!("No tokens found for {}", account.account_name));
|
||||
};
|
||||
|
||||
let mut approver = QrApprover::new(transport.clone(), tokens);
|
||||
match approver.approve(&account, url.to_owned()) {
|
||||
Ok(_) => {
|
||||
info!("Login approved.");
|
||||
break;
|
||||
}
|
||||
Err(QrApproverError::Unauthorized) => {
|
||||
warn!("tokens are invalid. Attempting to log in again.");
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to approve login: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, clap::Args)]
|
||||
#[group(required = true, multiple = false)]
|
||||
pub struct LoginUrlSource {
|
||||
/// The URL that would normally open in the Steam app. This is the URL that the QR code is displaying. It should start with \"https://s.team/...\"
|
||||
#[clap(long)]
|
||||
url: Option<String>,
|
||||
/// Path to an image file containing the QR code. The QR code will be scanned from this image.
|
||||
#[clap(long)]
|
||||
image: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LoginUrlSource {
|
||||
fn url(&self) -> anyhow::Result<String> {
|
||||
match self {
|
||||
Self { url: Some(url), .. } => Ok(url.clone()),
|
||||
Self {
|
||||
image: Some(path), ..
|
||||
} => read_qr_image(path),
|
||||
_ => Err(anyhow!(
|
||||
"You must provide either a URL with --url or an image file with --image."
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_qr_image(path: &Path) -> anyhow::Result<String> {
|
||||
use image::io::Reader as ImageReader;
|
||||
let image = ImageReader::open(path)?.decode()?.to_luma8();
|
||||
let mut img = PreparedImage::prepare(image);
|
||||
let grids = img.detect_grids();
|
||||
for grid in grids {
|
||||
let (_meta, text) = grid.decode()?;
|
||||
// a rough validation that the QR code is a Steam login code
|
||||
if text.contains("s.team") {
|
||||
return Ok(text);
|
||||
}
|
||||
}
|
||||
Err(anyhow!("No Steam login url found in the QR code"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn test_read_qr_image() {
|
||||
let path = Path::new("src/fixtures/qr-codes/login-qr.png");
|
||||
let url = read_qr_image(path).unwrap();
|
||||
assert_eq!(url, "https://s.team/q/1/2372462679780599330");
|
||||
}
|
||||
}
|
102
src/commands/remove.rs
Normal file
102
src/commands/remove.rs
Normal file
|
@ -0,0 +1,102 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use log::*;
|
||||
use steamguard::{accountlinker::RemoveAuthenticatorError, transport::TransportError};
|
||||
|
||||
use crate::{errors::UserError, tui, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Remove the authenticator from an account.")]
|
||||
pub struct RemoveCommand;
|
||||
|
||||
impl<T> AccountCommand<T> for RemoveCommand
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
accounts: Vec<Arc<Mutex<SteamGuardAccount>>>,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
eprintln!(
|
||||
"This will remove the mobile authenticator from {} accounts: {}",
|
||||
accounts.len(),
|
||||
accounts
|
||||
.iter()
|
||||
.map(|a| a.lock().unwrap().account_name.clone())
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ")
|
||||
);
|
||||
|
||||
match tui::prompt_char("Do you want to continue?", "yN") {
|
||||
'y' => {}
|
||||
_ => {
|
||||
info!("Aborting!");
|
||||
return Err(UserError::Aborted.into());
|
||||
}
|
||||
}
|
||||
|
||||
let mut successful = vec![];
|
||||
for a in accounts {
|
||||
let mut account = a.lock().unwrap();
|
||||
|
||||
let mut revocation: Option<String> = None;
|
||||
loop {
|
||||
match account.remove_authenticator(transport.clone(), revocation.as_ref()) {
|
||||
Ok(_) => {
|
||||
info!("Removed authenticator from {}", account.account_name);
|
||||
successful.push(account.account_name.clone());
|
||||
break;
|
||||
}
|
||||
Err(RemoveAuthenticatorError::TransportError(TransportError::Unauthorized)) => {
|
||||
error!("Account {} is not logged in", account.account_name);
|
||||
crate::do_login(transport.clone(), &mut account, args.password.clone())?;
|
||||
continue;
|
||||
}
|
||||
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
attempts_remaining,
|
||||
}) => {
|
||||
error!(
|
||||
"Revocation code was incorrect for {} ({} attempts remaining)",
|
||||
account.account_name, attempts_remaining
|
||||
);
|
||||
if attempts_remaining == 0 {
|
||||
error!("No attempts remaining, aborting!");
|
||||
break;
|
||||
}
|
||||
let code = tui::prompt_non_empty(format!(
|
||||
"Enter the revocation code for {}: ",
|
||||
account.account_name
|
||||
));
|
||||
revocation = Some(code);
|
||||
}
|
||||
Err(RemoveAuthenticatorError::MissingRevocationCode) => {
|
||||
let code = tui::prompt_non_empty(format!(
|
||||
"Enter the revocation code for {}: ",
|
||||
account.account_name
|
||||
));
|
||||
revocation = Some(code);
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Unexpected error when removing authenticator from {}: {}",
|
||||
account.account_name, err
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for account_name in successful {
|
||||
manager.remove_account(&account_name);
|
||||
}
|
||||
|
||||
manager.save()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
309
src/commands/setup.rs
Normal file
309
src/commands/setup.rs
Normal file
|
@ -0,0 +1,309 @@
|
|||
use log::*;
|
||||
use phonenumber::PhoneNumber;
|
||||
use secrecy::ExposeSecret;
|
||||
use steamguard::{
|
||||
accountlinker::{AccountLinkConfirmType, AccountLinkSuccess, RemoveAuthenticatorError},
|
||||
phonelinker::PhoneLinker,
|
||||
steamapi::PhoneClient,
|
||||
token::Tokens,
|
||||
AccountLinkError, AccountLinker, FinalizeLinkError,
|
||||
};
|
||||
|
||||
use crate::{tui, AccountManager};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(about = "Set up a new account with steamguard-cli")]
|
||||
pub struct SetupCommand;
|
||||
|
||||
impl<T> ManifestCommand<T> for SetupCommand
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
fn execute(
|
||||
&self,
|
||||
transport: T,
|
||||
manager: &mut AccountManager,
|
||||
args: &GlobalArgs,
|
||||
) -> anyhow::Result<()> {
|
||||
eprintln!("Log in to the account that you want to link to steamguard-cli");
|
||||
eprint!("Username: ");
|
||||
let username = tui::prompt().to_lowercase();
|
||||
let account_name = username.clone();
|
||||
if manager.account_exists(&username) {
|
||||
bail!(
|
||||
"Account {} already exists in manifest, remove it first",
|
||||
username
|
||||
);
|
||||
}
|
||||
info!("Logging in to {}", username);
|
||||
let tokens = crate::do_login_raw(transport.clone(), username, args.password.clone())
|
||||
.expect("Failed to log in. Account has not been linked.");
|
||||
|
||||
info!("Adding authenticator...");
|
||||
let mut linker = AccountLinker::new(transport.clone(), tokens);
|
||||
loop {
|
||||
match linker.link() {
|
||||
Ok(link) => {
|
||||
return Self::add_new_account(link, manager, account_name, linker);
|
||||
}
|
||||
Err(AccountLinkError::MustProvidePhoneNumber) => {
|
||||
// As of Dec 12, 2023, Steam no longer appears to require a phone number to add an authenticator. Keeping this code here just in case.
|
||||
eprintln!("Looks like you don't have a phone number on this account.");
|
||||
do_add_phone_number(transport.clone(), linker.tokens())?;
|
||||
}
|
||||
Err(AccountLinkError::MustConfirmEmail) => {
|
||||
println!("Check your email and click the link.");
|
||||
tui::pause();
|
||||
}
|
||||
Err(AccountLinkError::AuthenticatorPresent) => {
|
||||
eprintln!("It looks like there's already an authenticator on this account. If you want to link it to steamguard-cli, you'll need to remove it first. If you remove it using your revocation code (R#####), you'll get a 15 day trade ban.");
|
||||
eprintln!("However, you can \"transfer\" the authenticator to steamguard-cli if you have access to the phone number associated with your account. This will cause you to get only a 2 day trade ban.");
|
||||
eprintln!("If you were using SDA or WinAuth, you can import it into steamguard-cli with the `import` command, and have no trade ban.");
|
||||
eprintln!("You can't have the same authenticator on steamguard-cli and the steam mobile app at the same time.");
|
||||
|
||||
eprintln!("\nHere are your options:");
|
||||
eprintln!("[T] Transfer authenticator to steamguard-cli (2 day trade ban)");
|
||||
eprintln!("[R] Revoke authenticator with revocation code (15 day trade ban)");
|
||||
eprintln!("[A] Abort setup");
|
||||
let answer = tui::prompt_char("What would you like to do?", "Tra");
|
||||
match answer {
|
||||
't' => return Self::transfer_new_account(linker, manager),
|
||||
'r' => {
|
||||
loop {
|
||||
let revocation_code =
|
||||
tui::prompt_non_empty("Enter your revocation code (R#####): ");
|
||||
match linker.remove_authenticator(Some(&revocation_code)) {
|
||||
Ok(_) => break,
|
||||
Err(RemoveAuthenticatorError::IncorrectRevocationCode {
|
||||
attempts_remaining,
|
||||
}) => {
|
||||
error!(
|
||||
"Revocation code was incorrect ({} attempts remaining)",
|
||||
attempts_remaining
|
||||
);
|
||||
if attempts_remaining == 0 {
|
||||
error!("No attempts remaining, aborting!");
|
||||
bail!("Failed to remove authenticator: no attempts remaining")
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to remove authenticator: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
info!("Aborting account linking.");
|
||||
return Err(AccountLinkError::AuthenticatorPresent.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Failed to link authenticator. Account has not been linked. {}",
|
||||
err
|
||||
);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SetupCommand {
|
||||
/// Add a new account to the manifest after linking has started.
|
||||
fn add_new_account<T>(
|
||||
link: AccountLinkSuccess,
|
||||
manager: &mut AccountManager,
|
||||
account_name: String,
|
||||
mut linker: AccountLinker<T>,
|
||||
) -> Result<(), anyhow::Error>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
let mut server_time = link.server_time();
|
||||
let phone_number_hint = link.phone_number_hint().to_owned();
|
||||
let confirm_type = link.confirm_type();
|
||||
manager.add_account(link.into_account());
|
||||
match manager.save() {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
error!("Aborting the account linking process because we failed to save the manifest. This is really bad. Here is the error: {}", err);
|
||||
eprintln!(
|
||||
"Just in case, here is the account info. Save it somewhere just in case!\n{:#?}",
|
||||
manager.get_account(&account_name).unwrap().lock().unwrap()
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
let account_arc = manager
|
||||
.get_account(&account_name)
|
||||
.expect("account was not present in manifest");
|
||||
let mut account = account_arc.lock().unwrap();
|
||||
eprintln!("Authenticator has not yet been linked. Before continuing with finalization, please take the time to write down your revocation code: {}", account.revocation_code.expose_secret());
|
||||
tui::pause();
|
||||
debug!("attempting link finalization");
|
||||
let confirm_code = match confirm_type {
|
||||
AccountLinkConfirmType::Email => {
|
||||
eprintln!(
|
||||
"A code has been sent to the email address associated with this account."
|
||||
);
|
||||
tui::prompt_non_empty("Enter email code: ")
|
||||
}
|
||||
AccountLinkConfirmType::SMS => {
|
||||
eprintln!(
|
||||
"A code has been sent to your phone number ending in {}.",
|
||||
phone_number_hint
|
||||
);
|
||||
tui::prompt_non_empty("Enter SMS code: ")
|
||||
}
|
||||
AccountLinkConfirmType::Unknown(t) => {
|
||||
error!("Unknown link confirm type: {}", t);
|
||||
bail!("Unknown link confirm type: {}", t);
|
||||
}
|
||||
};
|
||||
let mut tries = 0;
|
||||
loop {
|
||||
match linker.finalize(server_time, &mut account, confirm_code.clone()) {
|
||||
Ok(_) => break,
|
||||
Err(FinalizeLinkError::WantMore { server_time: s }) => {
|
||||
server_time = s;
|
||||
debug!("steam wants more 2fa codes (tries: {})", tries);
|
||||
tries += 1;
|
||||
if tries >= 30 {
|
||||
error!("Failed to finalize: unable to generate valid 2fa codes");
|
||||
bail!("Failed to finalize: unable to generate valid 2fa codes");
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to finalize: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
let revocation_code = account.revocation_code.clone();
|
||||
drop(account);
|
||||
info!("Verifying authenticator status...");
|
||||
let status =
|
||||
linker.query_status(&manager.get_account(&account_name).unwrap().lock().unwrap())?;
|
||||
if status.state() == 0 {
|
||||
debug!(
|
||||
"authenticator state: {} -- did not actually finalize",
|
||||
status.state()
|
||||
);
|
||||
debug!("full status: {:#?}", status);
|
||||
manager.remove_account(&account_name);
|
||||
manager.save()?;
|
||||
bail!("Authenticator finalization was unsuccessful. You may have entered the wrong confirm code in the previous step. Try again.");
|
||||
}
|
||||
info!("Authenticator finalized.");
|
||||
match manager.save() {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
error!(
|
||||
"Failed to save manifest, but we were able to save it before. {}",
|
||||
err
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"Authenticator has been finalized. Please actually write down your revocation code: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer an existing authenticator to steamguard-cli.
|
||||
fn transfer_new_account<T>(
|
||||
mut linker: AccountLinker<T>,
|
||||
manager: &mut AccountManager,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
T: Transport + Clone,
|
||||
{
|
||||
info!("Transferring authenticator to steamguard-cli");
|
||||
linker.transfer_start()?;
|
||||
|
||||
let account: SteamGuardAccount;
|
||||
loop {
|
||||
let sms_code = tui::prompt_non_empty("Enter SMS code: ");
|
||||
match linker.transfer_finish(sms_code) {
|
||||
Ok(acc) => {
|
||||
account = acc;
|
||||
break;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to transfer authenticator: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Transfer successful, adding account to manifest");
|
||||
let revocation_code = account.revocation_code.clone();
|
||||
eprintln!(
|
||||
"Take a moment to write down your revocation code: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
|
||||
manager.add_account(account);
|
||||
|
||||
manager.save()?;
|
||||
|
||||
eprintln!(
|
||||
"Make sure you have your revocation code written down: {}",
|
||||
revocation_code.expose_secret()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn do_add_phone_number<T: Transport>(transport: T, tokens: &Tokens) -> anyhow::Result<()> {
|
||||
let client = PhoneClient::new(transport);
|
||||
|
||||
let linker = PhoneLinker::new(client, tokens.clone());
|
||||
|
||||
let phone_number: PhoneNumber;
|
||||
loop {
|
||||
eprintln!("Enter your phone number, including country code, in this format: +1 1234567890");
|
||||
eprint!("Phone number: ");
|
||||
let number = tui::prompt();
|
||||
match phonenumber::parse(None, &number) {
|
||||
Ok(p) => {
|
||||
phone_number = p;
|
||||
break;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to parse phone number: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resp = linker.set_account_phone_number(phone_number)?;
|
||||
|
||||
eprintln!(
|
||||
"Please click the link in the email sent to {}",
|
||||
resp.confirmation_email_address()
|
||||
);
|
||||
tui::pause();
|
||||
|
||||
debug!("sending phone verification code");
|
||||
linker.send_phone_verification_code(0)?;
|
||||
|
||||
loop {
|
||||
eprint!("Enter the code sent to your phone: ");
|
||||
let code = tui::prompt();
|
||||
|
||||
match linker.verify_account_phone_with_code(code) {
|
||||
Ok(_) => break,
|
||||
Err(err) => {
|
||||
error!("Failed to verify phone number: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!("Successfully added phone number to account");
|
||||
|
||||
Ok(())
|
||||
}
|
27
src/debug.rs
Normal file
27
src/debug.rs
Normal file
|
@ -0,0 +1,27 @@
|
|||
/// Parses a JSON string and prints it in a readable format, with all values stripped and replaced with their types.
|
||||
pub fn parse_json_stripped(json: &str) -> anyhow::Result<serde_json::Value> {
|
||||
let v: serde_json::Value = serde_json::from_str(json)?;
|
||||
let v = strip_json_value(v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
pub fn strip_json_value(v: serde_json::Value) -> serde_json::Value {
|
||||
match v {
|
||||
serde_json::Value::Object(mut map) => {
|
||||
for (_, v) in map.iter_mut() {
|
||||
*v = strip_json_value(v.clone());
|
||||
}
|
||||
serde_json::Value::Object(map)
|
||||
}
|
||||
serde_json::Value::Array(mut arr) => {
|
||||
for v in arr.iter_mut() {
|
||||
*v = strip_json_value(v.clone());
|
||||
}
|
||||
serde_json::Value::Array(arr)
|
||||
}
|
||||
serde_json::Value::String(_) => serde_json::Value::String("string".into()),
|
||||
serde_json::Value::Number(_) => serde_json::Value::Number(0.into()),
|
||||
serde_json::Value::Bool(_) => serde_json::Value::Bool(false),
|
||||
serde_json::Value::Null => serde_json::Value::Null,
|
||||
}
|
||||
}
|
118
src/encryption.rs
Normal file
118
src/encryption.rs
Normal file
|
@ -0,0 +1,118 @@
|
|||
use aes::cipher::InvalidLength;
|
||||
|
||||
use rand::Rng;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
mod argon2id_aes;
|
||||
#[cfg(feature = "keyring")]
|
||||
mod keyring;
|
||||
mod legacy;
|
||||
|
||||
pub use argon2id_aes::*;
|
||||
pub use legacy::*;
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
pub use crate::encryption::keyring::*;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "scheme")]
|
||||
pub enum EncryptionScheme {
|
||||
Argon2idAes256(Argon2idAes256),
|
||||
LegacySdaCompatible(LegacySdaCompatible),
|
||||
}
|
||||
|
||||
pub trait EntryEncryptor {
|
||||
fn generate() -> Self;
|
||||
fn encrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
plaintext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
||||
fn decrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
ciphertext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError>;
|
||||
}
|
||||
|
||||
impl EntryEncryptor for EncryptionScheme {
|
||||
fn generate() -> Self {
|
||||
EncryptionScheme::Argon2idAes256(Argon2idAes256::generate())
|
||||
}
|
||||
|
||||
fn encrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
plaintext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
match self {
|
||||
EncryptionScheme::Argon2idAes256(scheme) => scheme.encrypt(passkey, plaintext),
|
||||
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.encrypt(passkey, plaintext),
|
||||
}
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
ciphertext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
match self {
|
||||
EncryptionScheme::Argon2idAes256(scheme) => scheme.decrypt(passkey, ciphertext),
|
||||
EncryptionScheme::LegacySdaCompatible(scheme) => scheme.decrypt(passkey, ciphertext),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum EntryEncryptionError {
|
||||
#[error("Invalid ciphertext length. The ciphertext must be a multiple of 16 bytes.")]
|
||||
InvalidCipherTextLength,
|
||||
#[error(transparent)]
|
||||
Unknown(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
/// For some reason, these errors do not get converted to `ManifestAccountLoadError`s, even though they get converted into `anyhow::Error` just fine. I am too lazy to figure out why right now.
|
||||
impl From<InvalidLength> for EntryEncryptionError {
|
||||
fn from(error: InvalidLength) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<inout::NotEqualError> for EntryEncryptionError {
|
||||
fn from(error: inout::NotEqualError) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<inout::PadError> for EntryEncryptionError {
|
||||
fn from(error: inout::PadError) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<inout::block_padding::UnpadError> for EntryEncryptionError {
|
||||
fn from(error: inout::block_padding::UnpadError) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<base64::DecodeError> for EntryEncryptionError {
|
||||
fn from(error: base64::DecodeError) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
impl From<std::io::Error> for EntryEncryptionError {
|
||||
fn from(error: std::io::Error) -> Self {
|
||||
Self::Unknown(anyhow::Error::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_keyring_id() -> String {
|
||||
let rng = rand::thread_rng();
|
||||
rng.sample_iter(rand::distributions::Alphanumeric)
|
||||
.take(32)
|
||||
.map(char::from)
|
||||
.collect()
|
||||
}
|
158
src/encryption/argon2id_aes.rs
Normal file
158
src/encryption/argon2id_aes.rs
Normal file
|
@ -0,0 +1,158 @@
|
|||
use aes::cipher::block_padding::Pkcs7;
|
||||
use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use aes::Aes256;
|
||||
use anyhow::Context;
|
||||
use argon2::Argon2;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Argon2idAes256 {
|
||||
pub iv: String,
|
||||
pub salt: String,
|
||||
}
|
||||
|
||||
impl Argon2idAes256 {
|
||||
const KEY_SIZE_BYTES: usize = 32;
|
||||
const IV_LENGTH: usize = 16;
|
||||
const SALT_LENGTH: usize = 16;
|
||||
|
||||
fn get_encryption_key(passkey: &str, salt: &str) -> anyhow::Result<[u8; Self::KEY_SIZE_BYTES]> {
|
||||
let password_bytes = passkey.as_bytes();
|
||||
let salt_bytes = base64::engine::general_purpose::STANDARD.decode(salt)?;
|
||||
let mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
|
||||
let deriver = Argon2::new(
|
||||
argon2::Algorithm::Argon2id,
|
||||
argon2::Version::V0x13,
|
||||
Self::config(),
|
||||
);
|
||||
deriver.hash_password_into(password_bytes, &salt_bytes, &mut full_key)?;
|
||||
|
||||
Ok(full_key)
|
||||
}
|
||||
|
||||
fn config() -> argon2::Params {
|
||||
argon2::Params::new(
|
||||
12 * 1024, // 12MB
|
||||
3,
|
||||
12,
|
||||
Some(Self::KEY_SIZE_BYTES),
|
||||
)
|
||||
.expect("Unable to create Argon2 config.")
|
||||
}
|
||||
|
||||
fn decode_iv(&self) -> anyhow::Result<[u8; Self::IV_LENGTH]> {
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode_slice_unchecked(&self.iv, &mut iv)
|
||||
.context("decoding iv")?;
|
||||
Ok(iv)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryEncryptor for Argon2idAes256 {
|
||||
fn generate() -> Self {
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
let mut salt = [0u8; Self::SALT_LENGTH];
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
rng.fill(&mut salt);
|
||||
rng.fill(&mut iv);
|
||||
Argon2idAes256 {
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
plaintext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
let start = std::time::Instant::now();
|
||||
let key = Self::get_encryption_key(passkey, &self.salt)?;
|
||||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
|
||||
debug!("encryption took: {:?}", start.elapsed());
|
||||
Ok(encoded.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
ciphertext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
let start = std::time::Instant::now();
|
||||
let key = Self::get_encryption_key(passkey, &self.salt)?;
|
||||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let decoded = base64::engine::general_purpose::STANDARD.decode(ciphertext)?;
|
||||
let size: usize = decoded.len() / 16 + (if decoded.len() % 16 == 0 { 0 } else { 1 });
|
||||
let mut buffer = vec![0xffu8; 16 * size];
|
||||
buffer[..decoded.len()].copy_from_slice(&decoded);
|
||||
let decrypted = cipher.decrypt_padded_mut::<Pkcs7>(&mut buffer)?;
|
||||
debug!("decryption took: {:?}", start.elapsed());
|
||||
Ok(decrypted.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_encryption_key() {
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD.encode(
|
||||
Argon2idAes256::get_encryption_key("password", "GMhL0N2hqXg=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
),
|
||||
"DTm3hc95aKyAGmyVMZdLUPfcPjcXN1i1zYObYJg2GzY="
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encryption_key2() {
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD.encode(
|
||||
Argon2idAes256::get_encryption_key("password", "wTzTE9A6aN8=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
),
|
||||
"zwMjXhwggpJWCvkouG/xrSPZRWn2cUUyph3PAViRONA="
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ensure_encryption_symmetric() -> anyhow::Result<()> {
|
||||
let cases = [
|
||||
"foo",
|
||||
"tactical glizzy",
|
||||
"glizzy gladiator",
|
||||
"shadow wizard money gang",
|
||||
"shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells",
|
||||
];
|
||||
let passkey = "password";
|
||||
let scheme = Argon2idAes256::generate();
|
||||
for case in cases {
|
||||
eprintln!("testing case: {} (len {})", case, case.len());
|
||||
let orig = case.as_bytes().to_vec();
|
||||
let encrypted = scheme.encrypt(passkey, orig.clone()).unwrap();
|
||||
let result = scheme.decrypt(passkey, encrypted).unwrap();
|
||||
assert_eq!(orig, result.to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
24
src/encryption/keyring.rs
Normal file
24
src/encryption/keyring.rs
Normal file
|
@ -0,0 +1,24 @@
|
|||
use keyring::Entry;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
const KEYRING_SERVICE: &str = "steamguard-cli";
|
||||
|
||||
pub fn init_keyring(keyring_id: String) -> keyring::Result<Entry> {
|
||||
Entry::new(KEYRING_SERVICE, &keyring_id)
|
||||
}
|
||||
|
||||
pub fn try_passkey_from_keyring(keyring_id: String) -> keyring::Result<Option<SecretString>> {
|
||||
let entry = init_keyring(keyring_id)?;
|
||||
let passkey = entry.get_password()?;
|
||||
Ok(Some(SecretString::new(passkey)))
|
||||
}
|
||||
|
||||
pub fn store_passkey(keyring_id: String, passkey: SecretString) -> keyring::Result<()> {
|
||||
let entry = init_keyring(keyring_id)?;
|
||||
entry.set_password(passkey.expose_secret())
|
||||
}
|
||||
|
||||
pub fn clear_passkey(keyring_id: String) -> keyring::Result<()> {
|
||||
let entry = init_keyring(keyring_id)?;
|
||||
entry.delete_password()
|
||||
}
|
178
src/encryption/legacy.rs
Normal file
178
src/encryption/legacy.rs
Normal file
|
@ -0,0 +1,178 @@
|
|||
use aes::cipher::block_padding::Pkcs7;
|
||||
use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use aes::Aes256;
|
||||
use anyhow::Context;
|
||||
use base64::Engine;
|
||||
use log::*;
|
||||
use sha1::Sha1;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Encryption scheme that is compatible with SteamDesktopAuthenticator.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LegacySdaCompatible {
|
||||
pub iv: String,
|
||||
pub salt: String,
|
||||
}
|
||||
|
||||
impl LegacySdaCompatible {
|
||||
const PBKDF2_ITERATIONS: u32 = 50000; // This is necessary to maintain compatibility with SteamDesktopAuthenticator.
|
||||
const KEY_SIZE_BYTES: usize = 32;
|
||||
const SALT_LENGTH: usize = 8;
|
||||
const IV_LENGTH: usize = 16;
|
||||
|
||||
fn get_encryption_key(passkey: &str, salt: &str) -> anyhow::Result<[u8; Self::KEY_SIZE_BYTES]> {
|
||||
let password_bytes = passkey.as_bytes();
|
||||
let salt_bytes = base64::engine::general_purpose::STANDARD.decode(salt)?;
|
||||
let mut full_key: [u8; Self::KEY_SIZE_BYTES] = [0u8; Self::KEY_SIZE_BYTES];
|
||||
pbkdf2::pbkdf2_hmac::<Sha1>(
|
||||
password_bytes,
|
||||
&salt_bytes,
|
||||
Self::PBKDF2_ITERATIONS,
|
||||
&mut full_key,
|
||||
);
|
||||
Ok(full_key)
|
||||
}
|
||||
|
||||
fn decode_iv(&self) -> anyhow::Result<[u8; Self::IV_LENGTH]> {
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode_slice_unchecked(&self.iv, &mut iv)
|
||||
.context("decoding iv")?;
|
||||
Ok(iv)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryEncryptor for LegacySdaCompatible {
|
||||
fn generate() -> LegacySdaCompatible {
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
let mut salt = [0u8; Self::SALT_LENGTH];
|
||||
let mut iv = [0u8; Self::IV_LENGTH];
|
||||
rng.fill(&mut salt);
|
||||
rng.fill(&mut iv);
|
||||
LegacySdaCompatible {
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
plaintext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
let start = std::time::Instant::now();
|
||||
let key = Self::get_encryption_key(passkey, &self.salt)?;
|
||||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Encryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let ciphertext = cipher.encrypt_padded_vec_mut::<Pkcs7>(&plaintext);
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(ciphertext);
|
||||
debug!("encryption took: {:?}", start.elapsed());
|
||||
Ok(encoded.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&self,
|
||||
passkey: &str,
|
||||
ciphertext: Vec<u8>,
|
||||
) -> anyhow::Result<Vec<u8>, EntryEncryptionError> {
|
||||
let start = std::time::Instant::now();
|
||||
let key = Self::get_encryption_key(passkey, &self.salt)?;
|
||||
debug!("key derivation took: {:?}", start.elapsed());
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let iv = self.decode_iv()?;
|
||||
let cipher =
|
||||
cbc::Decryptor::<Aes256>::new_from_slices(&key, &iv).context("creating cipher")?;
|
||||
let decoded = base64::engine::general_purpose::STANDARD.decode(ciphertext)?;
|
||||
let size: usize = decoded.len() / 16 + (if decoded.len() % 16 == 0 { 0 } else { 1 });
|
||||
let mut buffer = vec![0xffu8; 16 * size];
|
||||
buffer[..decoded.len()].copy_from_slice(&decoded);
|
||||
let decrypted = cipher.decrypt_padded_mut::<Pkcs7>(&mut buffer)?;
|
||||
debug!("decryption took: {:?}", start.elapsed());
|
||||
Ok(decrypted.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// This test ensures compatibility with SteamDesktopAuthenticator and with previous versions of steamguard-cli
|
||||
#[test]
|
||||
fn test_encryption_key() {
|
||||
assert_eq!(
|
||||
LegacySdaCompatible::get_encryption_key("password", "GMhL0N2hqXg=")
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode("KtiRa4/OxW83MlB6URf+Z8rAGj7CBY+pDlwD/NuVo6Y=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
LegacySdaCompatible::get_encryption_key("password", "wTzTE9A6aN8=")
|
||||
.unwrap()
|
||||
.as_slice(),
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode("Dqpej/3DqEat0roJaHmu3luYgDzRCUmzX94n4fqvWj8=")
|
||||
.unwrap()
|
||||
.as_slice()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ensure_encryption_symmetric() -> anyhow::Result<()> {
|
||||
let cases = [
|
||||
"foo",
|
||||
"tactical glizzy",
|
||||
"glizzy gladiator",
|
||||
"shadow wizard money gang",
|
||||
"shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells, shadow wizard money gang, we love casting spells",
|
||||
];
|
||||
let passkey = "password";
|
||||
let scheme = LegacySdaCompatible::generate();
|
||||
for case in cases {
|
||||
eprintln!("testing case: {} (len {})", case, case.len());
|
||||
let orig = case.as_bytes().to_vec();
|
||||
let encrypted = scheme.encrypt(passkey, orig.clone()).unwrap();
|
||||
let result = scheme.decrypt(passkey, encrypted).unwrap();
|
||||
assert_eq!(orig, result.to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
prop_compose! {
|
||||
/// An insecure but reproducible strategy for generating encryption params.
|
||||
fn encryption_params()(salt in any::<[u8; LegacySdaCompatible::SALT_LENGTH]>(), iv in any::<[u8; LegacySdaCompatible::IV_LENGTH]>()) -> LegacySdaCompatible {
|
||||
LegacySdaCompatible {
|
||||
salt: base64::engine::general_purpose::STANDARD.encode(salt),
|
||||
iv: base64::engine::general_purpose::STANDARD.encode(iv),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// proptest! {
|
||||
// #[test]
|
||||
// fn ensure_encryption_symmetric(
|
||||
// passkey in ".{1,}",
|
||||
// params in encryption_params(),
|
||||
// data in any::<Vec<u8>>(),
|
||||
// ) {
|
||||
// prop_assume!(data.len() >= 2);
|
||||
// let mut orig = data;
|
||||
// orig[0] = '{' as u8;
|
||||
// let n = orig.len() - 1;
|
||||
// orig[n] = '}' as u8;
|
||||
// let encrypted = LegacySdaCompatible::encrypt(&passkey.clone().into(), ¶ms, orig.clone()).unwrap();
|
||||
// let result = LegacySdaCompatible::decrypt(&passkey.into(), ¶ms, encrypted).unwrap();
|
||||
// prop_assert_eq!(orig, result.to_vec());
|
||||
// }
|
||||
// }
|
||||
}
|
7
src/errors.rs
Normal file
7
src/errors.rs
Normal file
|
@ -0,0 +1,7 @@
|
|||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(crate) enum UserError {
|
||||
#[error("User aborted the operation.")]
|
||||
Aborted,
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
ZQqJk4KW7pb5bndkra244z3ttIks58UplODn5IgljrOK3bKORSwrnZYb9Iv6YsirmrT0hQ3tx381GhQu4Nyj/PFHHCfFTrduaCoMLRrHDsmsexOW93Yo02acHXNfPSvxtjGfZpsuIZVlhVy8JDH/ESXp88cKn2zqjXQWu6pLnah1YPlpZuTfArw69+Em7V1OH1CoKnsYuhCo/x4u7fXhMNgDlRBvDbO4enGzaixonPu9er5Zp6iNEeuAUqmD0DHASygNmzBhUBHv8Avng8YKbvu611yQVT2KybnIoL+Q11Y36GoFhWskmG3lLwh/1OlReGwJ1iX0lDDthoel/Ygj6EC2+wkR8V7eMQf48R15xdBILYTzcrjtiuLCr9MBc/HM/ToEa3QCGwGkXvshR/meJ1BiqaRARKfvJcj4eMSpiUvhDe1QFXXjfXRdetJcknyJ8Pv6v10G/OV3ELYwdx2dYL5C+Ao4qj9QCjoD8bb/juCjtZoSxMncbm4T7ORbXs/Ulx+TEuOUmRAjxr+zaWzzO7ZfYJMhIPz+LSixKpaVmxP89DEK5LJ1T6jA50QmPft6AbOMuoq99haWH9lMgqrIfBB+ZNNHSEE9PwMUxhX/TQP3oJgmrnZcMV4nBOcovbWM5s+odu2mvzoAcRMHVxEztASbMBwdJ7amJvoRRrXTtp642FQHAe8pFPlW14x1hShXAO4YfYkmmAhLqlujammuQ6bRg7XjBvh0zE88i5UBRiRsH+MV35u3c0ciugUmbrAZ0u9Yfv19MNSMVNMsREDuxQ==
|
|
@ -0,0 +1 @@
|
|||
{"encrypted":true,"first_run":true,"entries":[{"encryption_iv":"ifChnv66eA+/dYqGsQMIOA==","encryption_salt":"O2K8FAOWK9c=","filename":"1234.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
1
src/fixtures/maFiles/compat/1-account/1234.maFile
Normal file
1
src/fixtures/maFiles/compat/1-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
1
src/fixtures/maFiles/compat/1-account/manifest.json
Normal file
1
src/fixtures/maFiles/compat/1-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"1234.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
1
src/fixtures/maFiles/compat/2-account/1234.maFile
Normal file
1
src/fixtures/maFiles/compat/2-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
1
src/fixtures/maFiles/compat/2-account/5678.maFile
Normal file
1
src/fixtures/maFiles/compat/2-account/5678.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R56789","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example2","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":5678}}
|
1
src/fixtures/maFiles/compat/2-account/manifest.json
Normal file
1
src/fixtures/maFiles/compat/2-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"1234.maFile","steamid":1234}, {"encryption_iv":null,"encryption_salt":null,"filename":"5678.maFile","steamid":5678}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
6
src/fixtures/maFiles/compat/difficult-migration/generate.sh
Executable file
6
src/fixtures/maFiles/compat/difficult-migration/generate.sh
Executable file
|
@ -0,0 +1,6 @@
|
|||
#!/bin/bash
|
||||
|
||||
cat "1234.maFile" | jq -r '.Session | keys | .[]' | while read key; do
|
||||
cat "1234.maFile" | jq ".Session[\"$key\"] = null" > "null-$key.maFile"
|
||||
cat "1234.maFile" | jq ". | del(.Session.$key)" > "missing-$key.maFile"
|
||||
done
|
|
@ -0,0 +1,83 @@
|
|||
{
|
||||
"encrypted": false,
|
||||
"first_run": true,
|
||||
"entries": [
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-OAuthToken.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-SessionID.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-SteamID.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-SteamLogin.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-SteamLoginSecure.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "missing-WebCookie.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-OAuthToken.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-SessionID.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-SteamID.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-SteamLogin.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-SteamLoginSecure.maFile",
|
||||
"steamid": 1234
|
||||
},
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "null-WebCookie.maFile",
|
||||
"steamid": 1234
|
||||
}
|
||||
],
|
||||
"periodic_checking": false,
|
||||
"periodic_checking_interval": 5,
|
||||
"periodic_checking_checkall": false,
|
||||
"auto_confirm_market_transactions": false,
|
||||
"auto_confirm_trades": false
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": null,
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": null,
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": null
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": null,
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": null,
|
||||
"WebCookie": ";lkjsed;klfjas98093",
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"shared_secret": "zvIayp3JPvtvX/QGHqsqKBk/44s=",
|
||||
"serial_number": "kljasfhds",
|
||||
"revocation_code": "R12345",
|
||||
"uri": "otpauth://totp/Steam:example?secret=ASDF&issuer=Steam",
|
||||
"server_time": 1602522478,
|
||||
"account_name": "example",
|
||||
"token_gid": "jkkjlhkhjgf",
|
||||
"identity_secret": "kjsdlwowiqe=",
|
||||
"secret_1": "sklduhfgsdlkjhf=",
|
||||
"status": 1,
|
||||
"device_id": "android:99d2ad0e-4bad-4247-b111-26393aae0be3",
|
||||
"fully_enrolled": true,
|
||||
"Session": {
|
||||
"SessionID": "a;lskdjf",
|
||||
"SteamLogin": "983498437543",
|
||||
"SteamLoginSecure": "dlkjdsl;j%7C%32984730298",
|
||||
"WebCookie": null,
|
||||
"OAuthToken": "asdk;lf;dsjlkfd",
|
||||
"SteamID": 1234
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
|
@ -0,0 +1 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"1234.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":";lkjsed;klfjas98093","OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
|
@ -0,0 +1 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"1234.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
1
src/fixtures/maFiles/compat/no-webcookie/manifest.json
Normal file
1
src/fixtures/maFiles/compat/no-webcookie/manifest.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"encrypted":false,"first_run":true,"entries":[{"encryption_iv":null,"encryption_salt":null,"filename":"nowebcookie.maFile","steamid":1234}],"periodic_checking":false,"periodic_checking_interval":5,"periodic_checking_checkall":false,"auto_confirm_market_transactions":false,"auto_confirm_trades":false}
|
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":null,"OAuthToken":"asdk;lf;dsjlkfd","SteamID":1234}}
|
17
src/fixtures/maFiles/compat/null-oauthtoken/manifest.json
Normal file
17
src/fixtures/maFiles/compat/null-oauthtoken/manifest.json
Normal file
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"encrypted": false,
|
||||
"first_run": true,
|
||||
"entries": [
|
||||
{
|
||||
"encryption_iv": null,
|
||||
"encryption_salt": null,
|
||||
"filename": "nulloauthtoken.maFile",
|
||||
"steamid": 1234
|
||||
}
|
||||
],
|
||||
"periodic_checking": false,
|
||||
"periodic_checking_interval": 5,
|
||||
"periodic_checking_checkall": false,
|
||||
"auto_confirm_market_transactions": false,
|
||||
"auto_confirm_trades": false
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
{"shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","serial_number":"kljasfhds","revocation_code":"R12345","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","server_time":1602522478,"account_name":"example","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","secret_1":"sklduhfgsdlkjhf=","status":1,"device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","fully_enrolled":true,"Session":{"SessionID":"a;lskdjf","SteamLogin":"983498437543","SteamLoginSecure":"dlkjdsl;j%7C%32984730298","WebCookie":"asdk;lf;dsjlkfd","OAuthToken":null,"SteamID":1234}}
|
14
src/fixtures/maFiles/compat/steamv2/sample.maFile
Normal file
14
src/fixtures/maFiles/compat/steamv2/sample.maFile
Normal file
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"steamid": "76561199441992970",
|
||||
"shared_secret": "kSJa7hfbr8IvReG9/1Ax13BhTJA=",
|
||||
"serial_number": "5182004572898897156",
|
||||
"revocation_code": "R52260",
|
||||
"uri": "otpauth://totp/Steam:afarihm?secret=SERFV3QX3OX4EL2F4G676UBR25YGCTEQ&issuer=Steam",
|
||||
"server_time": "123",
|
||||
"account_name": "afarihm",
|
||||
"token_gid": "2d5a1b6cdbbfa9cc",
|
||||
"identity_secret": "f62XbJcml4r1j3NcFm0GGTtmcXw=",
|
||||
"secret_1": "BEelQHBr74ahsgiJbGArNV62/Bs=",
|
||||
"status": 1,
|
||||
"steamguard_scheme": "2"
|
||||
}
|
2
src/fixtures/maFiles/compat/winauth/exports.txt
Normal file
2
src/fixtures/maFiles/compat/winauth/exports.txt
Normal file
|
@ -0,0 +1,2 @@
|
|||
otpauth://totp/Steam:example?secret=ASDF&issuer=Steam&data=%7B%22shared%5Fsecret%22%3A%22zvIayp3JPvtvX%2FQGHqsqKBk%2F44s%3D%22%2C%22serial%5Fnumber%22%3A%22kljasfhds%22%2C%22revocation%5Fcode%22%3A%22R12345%22%2C%22uri%22%3A%22otpauth%3A%2F%2Ftotp%2FSteam%3Aexample%3Fsecret%3DASDF%26issuer%3DSteam%22%2C%22server%5Ftime%22%3A1602522478%2C%22account%5Fname%22%3A%22example%22%2C%22token%5Fgid%22%3A%22jkkjlhkhjgf%22%2C%22identity%5Fsecret%22%3A%22kjsdlwowiqe%3D%22%2C%22secret%5F1%22%3A%22sklduhfgsdlkjhf%3D%22%2C%22status%22%3A1%2C%22device%5Fid%22%3A%22android%3A99d2ad0e%2D4bad%2D4247%2Db111%2D26393aae0be3%22%2C%22fully%5Fenrolled%22%3Atrue%2C%22Session%22%3A%7B%22SessionID%22%3A%22a%3Blskdjf%22%2C%22SteamLogin%22%3A%22983498437543%22%2C%22SteamLoginSecure%22%3A%22dlkjdsl%3Bj%257C%2532984730298%22%2C%22WebCookie%22%3A%22%3Blkjsed%3Bklfjas98093%22%2C%22OAuthToken%22%3A%22asdk%3Blf%3Bdsjlkfd%22%2C%22SteamID%22%3A1234%7D%7D
|
||||
otpauth://totp/Steam:example2?secret=ASDF&issuer=Steam&data=%7B%22shared%5Fsecret%22%3A%22zvIayp3JPvtvX%2FQGHqsqKBk%2F44s%3D%22%2C%22serial%5Fnumber%22%3A%22kljasfhds%22%2C%22revocation%5Fcode%22%3A%22R56789%22%2C%22uri%22%3A%22otpauth%3A%2F%2Ftotp%2FSteam%3Aexample%3Fsecret%3DASDF%26issuer%3DSteam%22%2C%22server%5Ftime%22%3A1602522478%2C%22account%5Fname%22%3A%22example2%22%2C%22token%5Fgid%22%3A%22jkkjlhkhjgf%22%2C%22identity%5Fsecret%22%3A%22kjsdlwowiqe%3D%22%2C%22secret%5F1%22%3A%22sklduhfgsdlkjhf%3D%22%2C%22status%22%3A1%2C%22device%5Fid%22%3A%22android%3A99d2ad0e%2D4bad%2D4247%2Db111%2D26393aae0be3%22%2C%22fully%5Fenrolled%22%3Atrue%2C%22Session%22%3A%7B%22SessionID%22%3A%22a%3Blskdjf%22%2C%22SteamLogin%22%3A%22983498437543%22%2C%22SteamLoginSecure%22%3A%22dlkjdsl%3Bj%257C%2532984730298%22%2C%22WebCookie%22%3A%22%3Blkjsed%3Bklfjas98093%22%2C%22OAuthToken%22%3A%22asdk%3Blf%3Bdsjlkfd%22%2C%22SteamID%22%3A5678%7D%7D
|
|
@ -0,0 +1 @@
|
|||
Z0HJDSN9EuFOpKEeBzftCWxTsh0sV6QQriLTVrn37FyGNaXhGgzeHlvPfHgkXKCYbALTgx/B2fLh1CEojKO1/eqEgN+982CadR3EXk+vH1k5AMuGhMXPpsEeIh27ltxrdAEzWdlPlAyentBgOKlTCoN6iF+EZVORvp2pPaMrebyHi8/5Y+XC3HrMgfgmP7lFGpUgZK8f0mKB/pGaW+0/3oVikggBK3MIWlh4s9bC9LlMy5H+oU0n/Iu3P9dpbko1bDMKIbUKEPzS3wHXyQRg32zPIfONR0bswb7QTfAhoKixZrAenQluX3lXRL0JFafNEPzUY4r/DJ1pIMLK9cEvbzqwsPth6jrIZRd+zvgnshfNnGLCblYkPo4fGwePuhX2W2w6qgFMpo69rkSp1Zz6JKC/gH9YyL4a8N768ml9H1so5XBm7eB+fMRIL7bHof+V1CxGXX3z1RvjGRHPwKcrKLvffxTTs/dBHb9UDFtTprlymLZf6C53c5vMBQ/hk4fm
|
|
@ -0,0 +1 @@
|
|||
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":{"iv":"ifChnv66eA+/dYqGsQMIOA==","salt":"O2K8FAOWK9c=","scheme":"LegacySdaCompatible"}}]}
|
1
src/fixtures/maFiles/manifest-v1/1-account/1234.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/1-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}
|
1
src/fixtures/maFiles/manifest-v1/1-account/manifest.json
Normal file
1
src/fixtures/maFiles/manifest-v1/1-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}
|
1
src/fixtures/maFiles/manifest-v1/2-account/1234.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/1234.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}
|
1
src/fixtures/maFiles/manifest-v1/2-account/5678.maFile
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/5678.maFile
Normal file
|
@ -0,0 +1 @@
|
|||
{"account_name":"example2","steam_id":5678,"serial_number":"kljasfhds","revocation_code":"R56789","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}
|
1
src/fixtures/maFiles/manifest-v1/2-account/manifest.json
Normal file
1
src/fixtures/maFiles/manifest-v1/2-account/manifest.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null},{"filename":"5678.maFile","steam_id":5678,"account_name":"example2","encryption":null}]}
|
|
@ -0,0 +1 @@
|
|||
{"account_name":"example","steam_id":1234,"serial_number":"kljasfhds","revocation_code":"R12345","shared_secret":"zvIayp3JPvtvX/QGHqsqKBk/44s=","token_gid":"jkkjlhkhjgf","identity_secret":"kjsdlwowiqe=","uri":"otpauth://totp/Steam:example?secret=ASDF&issuer=Steam","device_id":"android:99d2ad0e-4bad-4247-b111-26393aae0be3","secret_1":"sklduhfgsdlkjhf=","tokens":null}
|
|
@ -0,0 +1 @@
|
|||
{"version":1,"entries":[{"filename":"1234.maFile","steam_id":1234,"account_name":"example","encryption":null}]}
|
BIN
src/fixtures/qr-codes/login-qr.png
Normal file
BIN
src/fixtures/qr-codes/login-qr.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.3 KiB |
219
src/login.rs
Normal file
219
src/login.rs
Normal file
|
@ -0,0 +1,219 @@
|
|||
use std::io::Write;
|
||||
|
||||
use log::*;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use steamguard::{
|
||||
protobufs::steammessages_auth_steamclient::{EAuthSessionGuardType, EAuthTokenPlatformType},
|
||||
refresher::TokenRefresher,
|
||||
steamapi::{self, AuthenticationClient},
|
||||
token::Tokens,
|
||||
transport::Transport,
|
||||
userlogin::UpdateAuthSessionError,
|
||||
DeviceDetails, LoginError, SteamGuardAccount, UserLogin,
|
||||
};
|
||||
|
||||
use crate::tui;
|
||||
|
||||
/// Performs a login, prompting for credentials if necessary.
|
||||
pub fn do_login<T: Transport + Clone>(
|
||||
transport: T,
|
||||
account: &mut SteamGuardAccount,
|
||||
password: Option<SecretString>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(tokens) = account.tokens.as_mut() {
|
||||
info!("Refreshing access token...");
|
||||
let client = AuthenticationClient::new(transport.clone());
|
||||
let mut refresher = TokenRefresher::new(client);
|
||||
match refresher.refresh(account.steam_id, tokens) {
|
||||
Ok(token) => {
|
||||
info!("Successfully refreshed access token, no need to prompt to log in.");
|
||||
tokens.set_access_token(token);
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Failed to refresh access token, prompting for login: {}",
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !account.account_name.is_empty() {
|
||||
info!("Username: {}", account.account_name);
|
||||
} else {
|
||||
eprint!("Username: ");
|
||||
account.account_name = tui::prompt();
|
||||
}
|
||||
let _ = std::io::stdout().flush();
|
||||
let password = if let Some(p) = password {
|
||||
p
|
||||
} else {
|
||||
tui::prompt_password()?
|
||||
};
|
||||
if !password.expose_secret().is_empty() {
|
||||
debug!("password is present");
|
||||
} else {
|
||||
debug!("password is empty");
|
||||
}
|
||||
let tokens = do_login_impl(
|
||||
transport,
|
||||
account.account_name.clone(),
|
||||
password,
|
||||
Some(account),
|
||||
)?;
|
||||
let steam_id = tokens.access_token().decode()?.steam_id();
|
||||
account.set_tokens(tokens);
|
||||
account.steam_id = steam_id;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn do_login_raw<T: Transport + Clone>(
|
||||
transport: T,
|
||||
username: String,
|
||||
password: Option<SecretString>,
|
||||
) -> anyhow::Result<Tokens> {
|
||||
let _ = std::io::stdout().flush();
|
||||
let password = if let Some(p) = password {
|
||||
p
|
||||
} else {
|
||||
tui::prompt_password()?
|
||||
};
|
||||
if !password.expose_secret().is_empty() {
|
||||
debug!("password is present");
|
||||
} else {
|
||||
debug!("password is empty");
|
||||
}
|
||||
do_login_impl(transport, username, password, None)
|
||||
}
|
||||
|
||||
fn do_login_impl<T: Transport + Clone>(
|
||||
transport: T,
|
||||
username: String,
|
||||
password: SecretString,
|
||||
account: Option<&SteamGuardAccount>,
|
||||
) -> anyhow::Result<Tokens> {
|
||||
debug!("starting login");
|
||||
let mut login = UserLogin::new(transport.clone(), build_device_details());
|
||||
|
||||
let mut password = password;
|
||||
let confirmation_methods;
|
||||
loop {
|
||||
match login.begin_auth_via_credentials(&username, password.expose_secret()) {
|
||||
Ok(methods) => {
|
||||
confirmation_methods = methods;
|
||||
break;
|
||||
}
|
||||
Err(LoginError::TooManyAttempts) => {
|
||||
error!("Too many login attempts. Steam is rate limiting you. Please wait a while and try again later.");
|
||||
return Err(LoginError::TooManyAttempts.into());
|
||||
}
|
||||
Err(LoginError::BadCredentials) => {
|
||||
error!("Incorrect password for {username}");
|
||||
password = tui::prompt_password()?;
|
||||
continue;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Unexpected error when trying to log in. If you report this as a bug, please rerun with `-v debug` or `-v trace` and include all output in your issue. {:?}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!(
|
||||
"got {} confirmation methods: {:#?}",
|
||||
confirmation_methods.len(),
|
||||
confirmation_methods
|
||||
);
|
||||
|
||||
for method in confirmation_methods {
|
||||
match method.confirmation_type {
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceConfirmation => {
|
||||
eprintln!("Please confirm this login on your other device.");
|
||||
eprintln!("Press enter when you have confirmed.");
|
||||
tui::pause();
|
||||
}
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_EmailConfirmation => {
|
||||
eprint!("Please confirm this login by clicking the link in your email.");
|
||||
if !method.associated_messsage.is_empty() {
|
||||
eprint!(" ({})", method.associated_messsage);
|
||||
}
|
||||
eprintln!();
|
||||
eprintln!("Press enter when you have confirmed.");
|
||||
tui::pause();
|
||||
}
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
|
||||
| EAuthSessionGuardType::k_EAuthSessionGuardType_EmailCode => {
|
||||
let prompt = if method.confirmation_type
|
||||
== EAuthSessionGuardType::k_EAuthSessionGuardType_DeviceCode
|
||||
{
|
||||
"Enter the 2fa code from your device: "
|
||||
} else {
|
||||
"Enter the 2fa code sent to your email: "
|
||||
};
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
let code = if let Some(account) = account {
|
||||
debug!("Generating 2fa code...");
|
||||
let time = steamapi::get_server_time(transport.clone())?.server_time();
|
||||
account.generate_code(time)
|
||||
} else {
|
||||
tui::prompt_non_empty(prompt).trim().to_owned()
|
||||
};
|
||||
|
||||
match login.submit_steam_guard_code(method.confirmation_type, code) {
|
||||
Ok(_) => break,
|
||||
Err(err) => {
|
||||
error!("Failed to submit code: {}", err);
|
||||
|
||||
match err {
|
||||
UpdateAuthSessionError::TooManyAttempts
|
||||
| UpdateAuthSessionError::SessionExpired
|
||||
| UpdateAuthSessionError::InvalidGuardType => {
|
||||
error!("Error is unrecoverable. Aborting.");
|
||||
return Err(err.into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
attempts += 1;
|
||||
debug!("Attempts: {}/3", attempts);
|
||||
if attempts >= 3 {
|
||||
error!("Too many failed attempts. Aborting.");
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EAuthSessionGuardType::k_EAuthSessionGuardType_None => {
|
||||
debug!("No login confirmation required. Proceeding with login.");
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
warn!("Unknown confirmation method: {:?}", method);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
info!("Polling for tokens... -- If this takes a long time, try logging in again.");
|
||||
let tokens = login.poll_until_tokens()?;
|
||||
|
||||
info!("Logged in successfully!");
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
fn build_device_details() -> DeviceDetails {
|
||||
DeviceDetails {
|
||||
friendly_name: format!(
|
||||
"{} (steamguard-cli)",
|
||||
gethostname::gethostname()
|
||||
.into_string()
|
||||
.expect("failed to get hostname")
|
||||
),
|
||||
platform_type: EAuthTokenPlatformType::k_EAuthTokenPlatformType_MobileApp,
|
||||
os_type: -500,
|
||||
gaming_device_type: 528,
|
||||
}
|
||||
}
|
322
src/main.rs
Normal file
322
src/main.rs
Normal file
|
@ -0,0 +1,322 @@
|
|||
extern crate rpassword;
|
||||
use clap::Parser;
|
||||
use log::*;
|
||||
use secrecy::SecretString;
|
||||
use std::{
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use steamguard::transport::WebApiTransport;
|
||||
use steamguard::SteamGuardAccount;
|
||||
|
||||
use crate::accountmanager::migrate::{load_and_migrate, MigrationError};
|
||||
pub use crate::accountmanager::{AccountManager, ManifestAccountLoadError, ManifestLoadError};
|
||||
use crate::commands::{CommandType, Subcommands};
|
||||
pub use login::*;
|
||||
|
||||
extern crate lazy_static;
|
||||
#[macro_use]
|
||||
extern crate anyhow;
|
||||
extern crate base64;
|
||||
extern crate dirs;
|
||||
#[cfg(test)]
|
||||
extern crate proptest;
|
||||
mod accountmanager;
|
||||
mod commands;
|
||||
mod debug;
|
||||
mod encryption;
|
||||
mod errors;
|
||||
mod login;
|
||||
mod secret_string;
|
||||
pub(crate) mod tui;
|
||||
|
||||
#[cfg(feature = "updater")]
|
||||
mod updater;
|
||||
|
||||
fn main() {
|
||||
let args = commands::Args::parse();
|
||||
|
||||
stderrlog::new()
|
||||
.verbosity(args.global.verbosity as usize)
|
||||
.module(module_path!())
|
||||
.module("steamguard")
|
||||
.init()
|
||||
.unwrap();
|
||||
debug!("{:?}", args);
|
||||
#[cfg(feature = "updater")]
|
||||
let should_do_update_check = !args.global.no_update_check;
|
||||
|
||||
let exit_code = match run(args) {
|
||||
Ok(_) => 0,
|
||||
Err(e) => {
|
||||
error!("{:?}", e);
|
||||
255
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(feature = "updater")]
|
||||
if should_do_update_check {
|
||||
match updater::check_for_update() {
|
||||
Ok(Some(version)) => {
|
||||
eprintln!();
|
||||
info!(
|
||||
"steamguard-cli {} is available. Download it here: https://github.com/dyc3/steamguard-cli/releases",
|
||||
version
|
||||
);
|
||||
}
|
||||
Ok(None) => {
|
||||
debug!("No update available");
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to check for updates: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
fn run(args: commands::Args) -> anyhow::Result<()> {
|
||||
let globalargs = args.global;
|
||||
|
||||
let cmd: CommandType<WebApiTransport> = match args.sub.unwrap_or(Subcommands::Code(args.code)) {
|
||||
Subcommands::Debug(args) => CommandType::Const(Box::new(args)),
|
||||
Subcommands::Completion(args) => CommandType::Const(Box::new(args)),
|
||||
Subcommands::Setup(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Import(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Encrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Decrypt(args) => CommandType::Manifest(Box::new(args)),
|
||||
Subcommands::Confirm(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::Remove(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::Code(args) => CommandType::Account(Box::new(args)),
|
||||
#[cfg(feature = "qr")]
|
||||
Subcommands::Qr(args) => CommandType::Account(Box::new(args)),
|
||||
Subcommands::QrLogin(args) => CommandType::Account(Box::new(args)),
|
||||
};
|
||||
|
||||
if let CommandType::Const(cmd) = cmd {
|
||||
return cmd.execute();
|
||||
}
|
||||
|
||||
let mafiles_dir = if let Some(mafiles_path) = &globalargs.mafiles_path {
|
||||
mafiles_path.clone()
|
||||
} else {
|
||||
get_mafiles_dir()
|
||||
};
|
||||
info!("reading manifest from {}", mafiles_dir);
|
||||
let path = Path::new(&mafiles_dir).join("manifest.json");
|
||||
let mut passkey = globalargs.passkey.clone();
|
||||
|
||||
let mut manager: accountmanager::AccountManager;
|
||||
if !path.exists() {
|
||||
error!("Did not find manifest in {}", mafiles_dir);
|
||||
if tui::prompt_char(
|
||||
format!("Would you like to create a manifest in {} ?", mafiles_dir).as_str(),
|
||||
"Yn",
|
||||
) == 'n'
|
||||
{
|
||||
info!("Aborting!");
|
||||
return Err(errors::UserError::Aborted.into());
|
||||
}
|
||||
std::fs::create_dir_all(mafiles_dir)?;
|
||||
|
||||
manager = accountmanager::AccountManager::new(path.as_path());
|
||||
manager.save()?;
|
||||
} else {
|
||||
manager = match accountmanager::AccountManager::load(path.as_path()) {
|
||||
Ok(m) => m,
|
||||
Err(ManifestLoadError::MigrationNeeded) => {
|
||||
info!("Migrating manifest");
|
||||
let manifest;
|
||||
let accounts;
|
||||
loop {
|
||||
match load_and_migrate(path.as_path(), passkey.as_ref()) {
|
||||
Ok((m, a)) => {
|
||||
manifest = m;
|
||||
accounts = a;
|
||||
break;
|
||||
}
|
||||
Err(MigrationError::MissingPasskey { keyring_id }) => {
|
||||
if passkey.is_some() {
|
||||
error!("Incorrect passkey");
|
||||
}
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
if let Some(keyring_id) = keyring_id {
|
||||
if passkey.is_none() {
|
||||
info!("Attempting to load encryption passkey from keyring");
|
||||
let entry = encryption::init_keyring(keyring_id)?;
|
||||
let raw = entry.get_password()?;
|
||||
passkey = Some(SecretString::new(raw));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
passkey = Some(tui::prompt_passkey()?);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to migrate manifest: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut manager = AccountManager::from_manifest(manifest, mafiles_dir);
|
||||
manager.register_accounts(accounts);
|
||||
manager.submit_passkey(passkey.clone());
|
||||
manager.save()?;
|
||||
manager
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Failed to load manifest: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "keyring")]
|
||||
if let Some(keyring_id) = manager.keyring_id() {
|
||||
if passkey.is_none() {
|
||||
info!("Attempting to load encryption passkey from keyring");
|
||||
match encryption::try_passkey_from_keyring(keyring_id.clone()) {
|
||||
Ok(k) => passkey = k,
|
||||
Err(e) => {
|
||||
warn!("Failed to load encryption passkey from keyring: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
manager.submit_passkey(passkey);
|
||||
|
||||
loop {
|
||||
match manager.auto_upgrade() {
|
||||
Ok(upgraded) => {
|
||||
if upgraded {
|
||||
info!("Manifest auto-upgraded");
|
||||
manager.save()?;
|
||||
} else {
|
||||
debug!("Manifest is up to date");
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(
|
||||
accountmanager::ManifestAccountLoadError::MissingPasskey
|
||||
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
|
||||
) => {
|
||||
if manager.has_passkey() {
|
||||
error!("Incorrect passkey");
|
||||
}
|
||||
passkey = Some(tui::prompt_passkey()?);
|
||||
manager.submit_passkey(passkey);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Could not load accounts: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut http_client = reqwest::blocking::Client::builder();
|
||||
if let Some(proxy) = &globalargs.http_proxy {
|
||||
let mut proxy = reqwest::Proxy::all(proxy)?;
|
||||
if let Some(proxy_creds) = &globalargs.proxy_credentials {
|
||||
let mut creds = proxy_creds.splitn(2, ':');
|
||||
proxy = proxy.basic_auth(creds.next().unwrap(), creds.next().unwrap());
|
||||
}
|
||||
http_client = http_client.proxy(proxy);
|
||||
}
|
||||
if globalargs.danger_accept_invalid_certs {
|
||||
http_client = http_client.danger_accept_invalid_certs(true);
|
||||
}
|
||||
let http_client = http_client.build()?;
|
||||
let transport = WebApiTransport::new(http_client);
|
||||
|
||||
if let CommandType::Manifest(cmd) = cmd {
|
||||
cmd.execute(transport, &mut manager, &globalargs)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>>;
|
||||
loop {
|
||||
match get_selected_accounts(&globalargs, &mut manager) {
|
||||
Ok(accounts) => {
|
||||
selected_accounts = accounts;
|
||||
break;
|
||||
}
|
||||
Err(
|
||||
accountmanager::ManifestAccountLoadError::MissingPasskey { .. }
|
||||
| accountmanager::ManifestAccountLoadError::IncorrectPasskey,
|
||||
) => {
|
||||
if manager.has_passkey() {
|
||||
error!("Incorrect passkey");
|
||||
}
|
||||
passkey = Some(tui::prompt_passkey()?);
|
||||
manager.submit_passkey(passkey);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Could not load accounts: {}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!(
|
||||
"selected accounts: {:?}",
|
||||
selected_accounts
|
||||
.iter()
|
||||
.map(|a| a.lock().unwrap().account_name.clone())
|
||||
.collect::<Vec<String>>()
|
||||
);
|
||||
|
||||
if let CommandType::Account(cmd) = cmd {
|
||||
return cmd.execute(transport, &mut manager, selected_accounts, &globalargs);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_selected_accounts(
|
||||
args: &commands::GlobalArgs,
|
||||
manifest: &mut accountmanager::AccountManager,
|
||||
) -> anyhow::Result<Vec<Arc<Mutex<SteamGuardAccount>>>, ManifestAccountLoadError> {
|
||||
let mut selected_accounts: Vec<Arc<Mutex<SteamGuardAccount>>> = vec![];
|
||||
|
||||
if args.all {
|
||||
manifest.load_accounts()?;
|
||||
for entry in manifest.iter() {
|
||||
selected_accounts.push(manifest.get_account(&entry.account_name).unwrap().clone());
|
||||
}
|
||||
} else {
|
||||
let entry = if let Some(username) = &args.username {
|
||||
manifest.get_entry(username)
|
||||
} else {
|
||||
manifest
|
||||
.iter()
|
||||
.next()
|
||||
.ok_or(ManifestAccountLoadError::MissingManifestEntry)
|
||||
}?;
|
||||
|
||||
let account_name = entry.account_name.clone();
|
||||
let account = manifest.get_or_load_account(&account_name)?;
|
||||
selected_accounts.push(account);
|
||||
}
|
||||
Ok(selected_accounts)
|
||||
}
|
||||
|
||||
fn get_mafiles_dir() -> String {
|
||||
let mut paths = vec![
|
||||
Path::new(&dirs::config_dir().unwrap()).join("steamguard-cli/maFiles"),
|
||||
Path::new(&dirs::home_dir().unwrap()).join("maFiles"),
|
||||
];
|
||||
if let Ok(current_exe) = std::env::current_exe() {
|
||||
paths.push(current_exe.parent().unwrap().join("maFiles"));
|
||||
}
|
||||
|
||||
for path in &paths {
|
||||
if path.join("manifest.json").is_file() {
|
||||
return path.to_str().unwrap().into();
|
||||
}
|
||||
}
|
||||
|
||||
return paths[0].to_str().unwrap().into();
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue