├── .github └── workflows │ ├── go.yml │ └── release.yml ├── Dockerfile ├── LICENSE ├── README.md ├── cli ├── .gitignore └── main.go ├── docs ├── init.d │ ├── goauthing │ └── goauthing@ └── systemd │ ├── system │ ├── goauthing.service │ ├── goauthing6.service │ ├── goauthing6@.service │ └── goauthing@.service │ └── user │ ├── goauthing.service │ └── goauthing6.service ├── go.mod ├── go.sum └── libauth ├── coding.go ├── coding_test.go ├── messages.go ├── requests.go ├── requests_test.go └── urls.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Set up Go 1.x 16 | uses: actions/setup-go@v5 17 | with: 18 | go-version: '1.23' 19 | 20 | - name: Check out code into the Go module directory 21 | uses: actions/checkout@v4 22 | 23 | - name: Get dependencies 24 | run: go get -v -t -d ./... 25 | 26 | - name: Test building with vendoring (#35) 27 | run: go mod vendor && go build -mod=vendor ./cli/main.go 28 | 29 | - name: Build 30 | run: | 31 | CGO_ENABLED=0 GOARCH=amd64 GOOS=darwin go build -ldflags="-s -w" -o auth-thu.macos.x86_64 ./cli/main.go 32 | CGO_ENABLED=0 GOARCH=arm64 GOOS=darwin go build -ldflags="-s -w" -o auth-thu.macos.arm64 ./cli/main.go 33 | CGO_ENABLED=0 GOARCH=amd64 GOOS=windows go build -ldflags="-s -w" -o auth-thu.win64.exe ./cli/main.go 34 | CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.x86_64 ./cli/main.go 35 | CGO_ENABLED=0 GOARCH=arm64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.arm64 ./cli/main.go 36 | CGO_ENABLED=0 GOARCH=arm GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.arm ./cli/main.go 37 | CGO_ENABLED=0 GOARCH=arm GOARM=5 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.armv5 ./cli/main.go 38 | CGO_ENABLED=0 GOARCH=arm GOARM=6 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.armv6 ./cli/main.go 39 | CGO_ENABLED=0 GOARCH=mipsle GOOS=linux GOMIPS=softfloat go build -ldflags="-s -w" -o auth-thu.linux.mipsle ./cli/main.go 40 | CGO_ENABLED=0 GOARCH=mips GOOS=linux GOMIPS=softfloat go build -ldflags="-s -w" -o auth-thu.linux.mipsbe ./cli/main.go 41 | CGO_ENABLED=0 GOARCH=ppc64le GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.ppc64le ./cli/main.go 42 | CGO_ENABLED=0 GOARCH=riscv64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.riscv64 ./cli/main.go 43 | CGO_ENABLED=0 GOARCH=loong64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.loong64 ./cli/main.go 44 | 45 | build-image: 46 | name: Build Docker Image 47 | runs-on: ubuntu-latest 48 | needs: build 49 | steps: 50 | - name: Check out code into the Go module directory 51 | uses: actions/checkout@v4 52 | 53 | - name: Set up QEMU 54 | uses: docker/setup-qemu-action@v3 55 | 56 | - name: Set up Docker Buildx 57 | uses: docker/setup-buildx-action@v3 58 | 59 | - name: Build the Docker image 60 | uses: docker/build-push-action@v5 61 | with: 62 | push: false 63 | context: . 64 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | 10 | build: 11 | name: Build 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Set up Go 1.x 15 | uses: actions/setup-go@v5 16 | with: 17 | go-version: '1.23' 18 | 19 | - name: Check out code into the Go module directory 20 | uses: actions/checkout@v4 21 | 22 | - name: Get dependencies 23 | run: go get -v -t -d ./... 24 | 25 | - name: Build 26 | run: | 27 | CGO_ENABLED=0 GOARCH=amd64 GOOS=darwin go build -ldflags="-s -w" -o auth-thu.macos.x86_64 ./cli/main.go 28 | CGO_ENABLED=0 GOARCH=arm64 GOOS=darwin go build -ldflags="-s -w" -o auth-thu.macos.arm64 ./cli/main.go 29 | CGO_ENABLED=0 GOARCH=amd64 GOOS=windows go build -ldflags="-s -w" -o auth-thu.win64.exe ./cli/main.go 30 | CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.x86_64 ./cli/main.go 31 | CGO_ENABLED=0 GOARCH=arm64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.arm64 ./cli/main.go 32 | CGO_ENABLED=0 GOARCH=arm GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.arm ./cli/main.go 33 | CGO_ENABLED=0 GOARCH=arm GOARM=5 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.armv5 ./cli/main.go 34 | CGO_ENABLED=0 GOARCH=arm GOARM=6 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.armv6 ./cli/main.go 35 | CGO_ENABLED=0 GOARCH=mipsle GOOS=linux GOMIPS=softfloat go build -ldflags="-s -w" -o auth-thu.linux.mipsle ./cli/main.go 36 | CGO_ENABLED=0 GOARCH=mips GOOS=linux GOMIPS=softfloat go build -ldflags="-s -w" -o auth-thu.linux.mipsbe ./cli/main.go 37 | CGO_ENABLED=0 GOARCH=ppc64le GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.ppc64le ./cli/main.go 38 | CGO_ENABLED=0 GOARCH=riscv64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.riscv64 ./cli/main.go 39 | CGO_ENABLED=0 GOARCH=loong64 GOOS=linux go build -ldflags="-s -w" -o auth-thu.linux.loong64 ./cli/main.go 40 | 41 | - name: Create Release 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | run: | 45 | tag_name="${GITHUB_REF##*/}" 46 | gh release create "$tag_name" -t "$tag_name" auth-thu.* 47 | 48 | build-image: 49 | name: Build Image 50 | runs-on: ubuntu-latest 51 | needs: build 52 | env: 53 | REGISTRY: ghcr.io 54 | IMAGE_NAME: ${{ github.repository }} 55 | 56 | steps: 57 | - name: Check out code into the Go module directory 58 | uses: actions/checkout@v4 59 | 60 | - name: Set up QEMU 61 | uses: docker/setup-qemu-action@v3 62 | 63 | - name: Set up Docker Buildx 64 | uses: docker/setup-buildx-action@v3 65 | 66 | - name: Log in to the Container Registry 67 | uses: docker/login-action@v3 68 | with: 69 | registry: ${{ env.REGISTRY }} 70 | username: ${{ github.actor }} 71 | password: ${{ secrets.GITHUB_TOKEN }} 72 | 73 | - name: Extract metadata 74 | id: metadata 75 | uses: docker/metadata-action@v5 76 | with: 77 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 78 | 79 | - name: Build and push the Docker image 80 | uses: docker/build-push-action@v5 81 | with: 82 | push: true 83 | context: . 84 | tags: ${{ steps.metadata.outputs.tags }} 85 | labels: ${{ steps.metadata.outputs.labels }} 86 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS builder 2 | 3 | WORKDIR /app 4 | COPY . . 5 | 6 | RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /app/auth-thu /app/cli/main.go 7 | 8 | FROM scratch 9 | 10 | COPY --from=builder /app/auth-thu /auth-thu 11 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt 12 | 13 | ENTRYPOINT [ "/auth-thu" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoAuthing 2 | 3 | [![Build Status](https://github.com/z4yx/GoAuthing/actions/workflows/go.yml/badge.svg)](https://github.com/z4yx/GoAuthing/actions) 4 | ![GPLv3](https://img.shields.io/badge/license-GPLv3-blue.svg) 5 | 6 | A command-line Tunet (auth4/6.tsinghua.edu.cn, Tsinghua-IPv4) authentication tool. 7 | 8 | ## Download Binary 9 | 10 | Download prebuilt binaries from 11 | Or 12 | 13 | ## Usage 14 | 15 | Simply try `./auth-thu`, then enter your user name and password. 16 | 17 | ```help 18 | NAME: 19 | auth-thu - Authenticating utility for Tsinghua 20 | 21 | USAGE: 22 | auth-thu [options] 23 | auth-thu [options] auth [auth_options] 24 | auth-thu [options] deauth [auth_options] 25 | auth-thu [options] online [online_options] 26 | 27 | VERSION: 28 | 2.3.5 29 | 30 | AUTHORS: 31 | Yuxiang Zhang 32 | Nogeek 33 | ZenithalHourlyRate 34 | Jiajie Chen 35 | KomeijiOcean 36 | Sharzy L 37 | 38 | COMMANDS: 39 | auth (default) Auth via auth4/6.tsinghua 40 | OPTIONS: 41 | --ip value authenticating for specified IP address 42 | --no-check, -n skip online checking, always send login request 43 | --logout, -o de-auth of the online account (behaves the same as deauth command, for backward-compatibility) 44 | --ipv6, -6 authenticating for IPv6 (auth6.tsinghua) 45 | --campus-only, -C auth only, no auto-login (v4 only) 46 | --host value use customized hostname of srun4000 47 | --insecure use http instead of https 48 | --keep-online, -k keep online after login 49 | --ac-id value use specified ac_id 50 | deauth De-auth via auth4/6.tsinghua 51 | OPTIONS: 52 | --ip value authenticating for specified IP address 53 | --no-check, -n skip online checking, always send logout request 54 | --ipv6, -6 authenticating for IPv6 (auth6.tsinghua) 55 | --host value use customized hostname of srun4000 56 | --insecure use http instead of https 57 | --ac-id value use specified ac_id 58 | online Keep your computer online 59 | OPTIONS: 60 | --auth, -a keep the Auth online only 61 | --ipv6, -6 keep only ipv6 connection online 62 | 63 | GLOBAL OPTIONS: 64 | --username name, -u name your TUNET account name 65 | --password password, -p password your TUNET password 66 | --config-file path, -c path path to your config file, default ~/.auth-thu 67 | --hook-success value command line to be executed in shell after successful login/out 68 | --daemonize, -D run without reading username/password from standard input; less log 69 | --debug print debug messages 70 | --help, -h print the help 71 | --version, -v print the version 72 | ``` 73 | 74 | The program looks for a config file in `$XDG_CONFIG_HOME/auth-thu`, `~/.config/auth-thu`, `~/.auth-thu` in order. 75 | Write a config file to store your username & password or other options in the following format. 76 | 77 | ```json 78 | { 79 | "username": "your-username", 80 | "password": "your-password", 81 | "host": "", 82 | "ip": "166.xxx.xx.xx", 83 | "debug": false, 84 | "useV6": false, 85 | "noCheck": false, 86 | "insecure": false, 87 | "daemonize": false, 88 | "acId": "", 89 | "campusOnly": false 90 | } 91 | ``` 92 | 93 | Unless you have special need, you can only have `username` and `password` field in your config file. For `host`, the default value defined in code should be sufficient hence there should be no need to fill it. `UseV6` automatically determine the `host` to use. For `ip`, unless you are auth/login the other boxes you have(not the box `auth-thu` is running on), you can leave it blank. For those boxes unable to get correct acid themselves, we can specify the acid for them by using `acId`. Other options are self-explanatory. 94 | 95 | ## Autostart 96 | 97 | It is suggested that one configures and runs it manually first with `debug` flag turned on, which ensures the correctness of one's config, then start it as system service. For `daemonize` flag, it forces the program to only log errors, hence debugging should be done earlier and manually. `daemonize` is automatically turned on for system service (ref to associated systemd unit files). 98 | 99 | ### Systemd 100 | 101 | To configure automatic authentication on systemd-based Linux distro, take a look at `docs/systemd` folder. Just modify the path in configuration files, then copy them to `/etc/systemd` folder. 102 | 103 | Note that the program should have access to the configuration file. 104 | For `system/goauthing.service`, since it is run as `nobody`, `/etc/goauthing.json` can not be read by it, hence you can use the following command to enable access: 105 | 106 | ```shell 107 | setfacl -m u:nobody:r /etc/goauthing.json 108 | ``` 109 | 110 | Or, to be more secure, you can choose `system/goauthing@.service` or `user/goauthing.service` and store the configuration file in the home directory. 111 | 112 | ### OpenWRT 113 | 114 | For OpenWRT users, there are two options available: `goauthing` loading the configuration file, and `goauthing@` interacting with the UCI. The init script should go to the `/etc/init.d/` folder. With the latter, use the following procedure to set up: 115 | 116 | ```shell 117 | touch /etc/config/goauthing 118 | uci set goauthing.config=goauthing 119 | uci set goauthing.config.username='' 120 | uci set goauthing.config.password='' 121 | uci commit goauthing 122 | /etc/init.d/goauthing enable 123 | /etc/init.d/goauthing start 124 | ``` 125 | 126 | ### Docker 127 | 128 | For Docker users, you can run the container with a restart policy. An example docker compose is like this: 129 | 130 | ```yaml 131 | services: 132 | goauthing: 133 | image: ghcr.io/z4yx/goauthing:latest 134 | container_name: goauthing 135 | restart: always 136 | volumes: 137 | - /path/to/your/config:/.auth-thu 138 | command: auth -k 139 | ``` 140 | 141 | ## Build 142 | 143 | Requires Go 1.11 or above 144 | 145 | ```shell 146 | export GO111MODULE=on 147 | go build -o auth-thu github.com/z4yx/GoAuthing/cli 148 | ``` 149 | 150 | ## Acknowledgments 151 | 152 | This project was inspired by the following projects: 153 | 154 | - 155 | - 156 | -------------------------------------------------------------------------------- /cli/.gitignore: -------------------------------------------------------------------------------- 1 | cli 2 | -------------------------------------------------------------------------------- /cli/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "net" 10 | "net/http" 11 | "os" 12 | "os/exec" 13 | "path" 14 | "strings" 15 | "time" 16 | 17 | "github.com/howeyc/gopass" 18 | "github.com/juju/loggo" 19 | "github.com/urfave/cli/v3" 20 | 21 | "github.com/z4yx/GoAuthing/libauth" 22 | ) 23 | 24 | type Settings struct { 25 | Username string `json:"username"` 26 | Password string `json:"password"` 27 | Ip string `json:"ip"` 28 | Host string `json:"host"` 29 | HookSucc string `json:"hook-success"` 30 | NoCheck bool `json:"noCheck"` 31 | KeepOn bool `json:"keepOnline"` 32 | OnIntrvl int `json:"onlineInterval"` 33 | OnRetry int `json:"onlineRetry"` 34 | V6 bool `json:"useV6"` 35 | Insecure bool `json:"insecure"` 36 | Daemon bool `json:"daemonize"` 37 | Debug bool `json:"debug"` 38 | AcID string `json:"acId"` 39 | Campus bool `json:"campusOnly"` 40 | } 41 | 42 | var logger = loggo.GetLogger("auth-thu") 43 | var settings Settings 44 | 45 | func parseSettingsFile(path string) error { 46 | sf, err := os.Open(path) 47 | if err != nil { 48 | return fmt.Errorf("read config file failed (%s)", err) 49 | } 50 | defer sf.Close() 51 | bv, _ := ioutil.ReadAll(sf) 52 | err = json.Unmarshal(bv, &settings) 53 | if err != nil { 54 | return fmt.Errorf("parse config file \"%s\" failed (%s)", path, err) 55 | } 56 | logger.Debugf("Read config file \"%s\" succeeded\n", path) 57 | return nil 58 | } 59 | 60 | func mergeCliSettings(c *cli.Command) { 61 | var merged Settings 62 | merged.Username = c.String("username") 63 | if len(merged.Username) == 0 { 64 | merged.Username = settings.Username 65 | } 66 | merged.Password = c.String("password") 67 | if len(merged.Password) == 0 { 68 | merged.Password = settings.Password 69 | } 70 | merged.Ip = c.String("ip") 71 | if len(merged.Ip) == 0 { 72 | merged.Ip = settings.Ip 73 | } 74 | merged.Host = c.String("host") 75 | if len(merged.Host) == 0 { 76 | merged.Host = settings.Host 77 | } 78 | merged.HookSucc = c.String("hook-success") 79 | if len(merged.HookSucc) == 0 { 80 | merged.HookSucc = settings.HookSucc 81 | } 82 | merged.NoCheck = settings.NoCheck || c.Bool("no-check") 83 | merged.V6 = settings.V6 || c.Bool("ipv6") 84 | merged.KeepOn = settings.KeepOn || c.Bool("keep-online") 85 | merged.OnIntrvl = c.Int("online-interval") 86 | if !c.IsSet("online-interval") && settings.OnIntrvl != 0 { 87 | // if no cmd arg but has settings item, settings precedes. 88 | merged.OnIntrvl = settings.OnIntrvl 89 | } 90 | merged.OnRetry = c.Int("r") // online-retry 91 | if !c.IsSet("r") && settings.OnRetry != 0 { 92 | merged.OnRetry = settings.OnRetry 93 | } 94 | merged.Insecure = settings.Insecure || c.Bool("insecure") 95 | merged.Daemon = settings.Daemon || c.Bool("daemonize") 96 | merged.Debug = settings.Debug || c.Bool("debug") 97 | merged.AcID = c.String("ac-id") 98 | if len(merged.AcID) == 0 { 99 | merged.AcID = settings.AcID 100 | } 101 | merged.Campus = settings.Campus || c.Bool("campus-only") 102 | settings = merged 103 | logger.Debugf("Settings Username: \"%s\"\n", settings.Username) 104 | logger.Debugf("Settings Ip: \"%s\"\n", settings.Ip) 105 | logger.Debugf("Settings Host: \"%s\"\n", settings.Host) 106 | logger.Debugf("Settings HookSucc: \"%s\"\n", settings.HookSucc) 107 | logger.Debugf("Settings NoCheck: %t\n", settings.NoCheck) 108 | logger.Debugf("Settings V6: %t\n", settings.V6) 109 | logger.Debugf("Settings KeepOn: %t\n", settings.KeepOn) 110 | logger.Debugf("Settings OnIntrvl: %v\n", settings.OnIntrvl) 111 | logger.Debugf("Settings OnRetry: %v\n", settings.OnRetry) 112 | logger.Debugf("Settings Insecure: %t\n", settings.Insecure) 113 | logger.Debugf("Settings Daemon: %t\n", settings.Daemon) 114 | logger.Debugf("Settings Debug: %t\n", settings.Debug) 115 | logger.Debugf("Settings AcID: \"%s\"\n", settings.AcID) 116 | logger.Debugf("Settings Campus: %t\n", settings.Campus) 117 | } 118 | 119 | func requestUser() (err error) { 120 | if len(settings.Username) == 0 && !settings.Daemon { 121 | reader := bufio.NewReader(os.Stdin) 122 | fmt.Print("Username: ") 123 | settings.Username, _ = reader.ReadString('\n') 124 | settings.Username = strings.TrimSpace(settings.Username) 125 | } 126 | if len(settings.Username) == 0 { 127 | err = fmt.Errorf("username can't be empty") 128 | } 129 | return 130 | } 131 | 132 | func requestPasswd() (err error) { 133 | if len(settings.Password) == 0 && !settings.Daemon { 134 | var b []byte 135 | fmt.Printf("Password: ") 136 | b, err = gopass.GetPasswdMasked() 137 | if err != nil { 138 | // Handle gopass.ErrInterrupted or getch() read error 139 | err = fmt.Errorf("interrupted") 140 | return 141 | } 142 | settings.Password = string(b) 143 | } 144 | if len(settings.Password) == 0 { 145 | err = fmt.Errorf("password can't be empty") 146 | } 147 | return 148 | } 149 | 150 | func setLoggerLevel(debug bool, daemon bool) { 151 | if daemon { 152 | _ = loggo.ConfigureLoggers("auth-thu=ERROR;libauth=ERROR") 153 | } else if debug { 154 | _ = loggo.ConfigureLoggers("auth-thu=DEBUG;libauth=DEBUG") 155 | } else { 156 | _ = loggo.ConfigureLoggers("auth-thu=INFO;libauth=INFO") 157 | } 158 | } 159 | 160 | func locateConfigFile(c *cli.Command) (cf string) { 161 | cf = c.String("config-file") 162 | if len(cf) != 0 { 163 | return 164 | } 165 | 166 | xdgConfigHome := os.Getenv("XDG_CONFIG_HOME") 167 | homedir, _ := os.UserHomeDir() 168 | if len(xdgConfigHome) == 0 { 169 | xdgConfigHome = path.Join(homedir, ".config") 170 | } 171 | cf = path.Join(xdgConfigHome, "auth-thu") 172 | _, err := os.Stat(cf) 173 | if !os.IsNotExist(err) { 174 | return 175 | } 176 | 177 | cf = path.Join(homedir, ".auth-thu") 178 | _, err = os.Stat(cf) 179 | if !os.IsNotExist(err) { 180 | return 181 | } 182 | 183 | return "" 184 | } 185 | 186 | func parseSettings(c *cli.Command) (err error) { 187 | if c.Bool("help") { 188 | cli.ShowAppHelpAndExit(c, 0) 189 | } 190 | // Early debug flag setting (have debug messages when access config file) 191 | setLoggerLevel(c.Bool("debug"), c.Bool("daemonize")) 192 | 193 | cf := locateConfigFile(c) 194 | if len(cf) == 0 && c.Bool("daemonize") { 195 | return fmt.Errorf("cannot find config file (it is necessary in daemon mode)") 196 | } 197 | if len(cf) != 0 { 198 | err = parseSettingsFile(cf) 199 | if err != nil { 200 | return err 201 | } 202 | } 203 | mergeCliSettings(c) 204 | // Late debug flag setting 205 | setLoggerLevel(settings.Debug, settings.Daemon) 206 | return 207 | } 208 | 209 | func runHook(c *cli.Command) { 210 | if settings.HookSucc != "" { 211 | logger.Debugf("Run hook \"%s\"\n", settings.HookSucc) 212 | cmd := exec.Command(settings.HookSucc) 213 | if err := cmd.Run(); err != nil { 214 | logger.Errorf("Hook execution failed: %v\n", err) 215 | } 216 | } 217 | } 218 | 219 | func keepAliveLoop(c *cli.Command, campusOnly bool) (ret error) { 220 | logger.Infof("Accessing websites periodically to keep you online") 221 | 222 | accessTarget := func(url string, ipv6 bool) (ret error) { 223 | network := "tcp4" 224 | if ipv6 { 225 | network = "tcp6" 226 | } 227 | netClient := &http.Client{ 228 | Timeout: time.Second * 10, 229 | Transport: &http.Transport{ 230 | DialContext: func(ctx context.Context, _network, addr string) (net.Conn, error) { 231 | logger.Debugf("DialContext %s (%s)\n", addr, network) 232 | myDial := &net.Dialer{ 233 | Timeout: 6 * time.Second, 234 | KeepAlive: 0, 235 | FallbackDelay: -1, // disable RFC 6555 Fast Fallback 236 | } 237 | return myDial.DialContext(ctx, network, addr) 238 | }, 239 | }, 240 | } 241 | resp, ret := netClient.Head(url) 242 | if ret != nil { 243 | return 244 | } 245 | defer resp.Body.Close() 246 | logger.Debugf("HTTP status code %d\n", resp.StatusCode) 247 | return 248 | } 249 | targetInside := "https://www.tsinghua.edu.cn/" 250 | targetOutside := "https://www.baidu.com/" 251 | 252 | stop := make(chan int, 1) 253 | defer func() { stop <- 1 }() 254 | go func() { 255 | // Keep IPv6 online, ignore any errors 256 | for { 257 | select { 258 | case <-stop: 259 | break 260 | case <-time.After(13 * time.Minute): 261 | _ = accessTarget(targetInside, true) 262 | } 263 | } 264 | }() 265 | 266 | errorCount := 0 267 | for { 268 | target := targetOutside 269 | if campusOnly || settings.V6 { 270 | target = targetInside 271 | } 272 | if ret = accessTarget(target, settings.V6); ret != nil { 273 | errorCount++ 274 | if errorCount >= settings.OnRetry { 275 | ret = fmt.Errorf("keepAlive request error (re-login might be required): %w\n", ret) 276 | break 277 | } else { 278 | logger.Infof("keepAlive request error (will retry): %s\n", ret) 279 | } 280 | } else { 281 | errorCount = 0 282 | } 283 | // Consumes ~5MB per day when settings.OnIntrvl == 3 284 | time.Sleep(time.Duration(settings.OnIntrvl) * time.Second) 285 | } 286 | return 287 | } 288 | 289 | func authUtil(c *cli.Command, logout bool) error { 290 | err := parseSettings(c) 291 | if err != nil { 292 | return err 293 | } 294 | acID := "1" 295 | if len(settings.AcID) != 0 { 296 | acID = settings.AcID 297 | } 298 | domain := settings.Host 299 | if len(settings.Host) == 0 { 300 | if settings.V6 { 301 | domain = "auth6.tsinghua.edu.cn" 302 | } else { 303 | domain = "auth4.tsinghua.edu.cn" 304 | } 305 | } 306 | 307 | if len(settings.Ip) == 0 && len(settings.AcID) == 0 { 308 | // Probe the ac_id parameter 309 | // We do this only in Tsinghua, since it requires access to usereg.t.e.c/net.t.e.c 310 | retAcID, err := libauth.GetAcID(settings.V6) 311 | if err != nil || retAcID == "1" { 312 | logger.Debugf("Failed to get ac_id: %v", err) 313 | logger.Debugf("Login may fail with '找不到符合条件的控制策略'.") 314 | } 315 | acID = retAcID 316 | } 317 | 318 | host := libauth.NewUrlProvider(domain, settings.Insecure) 319 | if len(settings.Ip) == 0 && !settings.NoCheck { 320 | online, _, username := libauth.IsOnline(host, acID) 321 | if logout && online { 322 | settings.Username = username 323 | } 324 | if online && !logout { 325 | logger.Infof("Currently online!") 326 | if settings.KeepOn { 327 | return keepAliveLoop(c, settings.Campus) 328 | } 329 | return nil 330 | } else if !online && logout { 331 | logger.Infof("Currently offline!") 332 | return nil 333 | } 334 | } 335 | err = requestUser() 336 | if err != nil { 337 | return err 338 | } 339 | if !logout { 340 | err = requestPasswd() 341 | if err != nil { 342 | return err 343 | } 344 | if len(settings.Ip) != 0 && len(settings.Host) == 0 && len(settings.AcID) == 0 { 345 | // Auth for another IP requires correct NAS ID since July 2020 346 | // Tsinghua only 347 | if retNasID, err := libauth.GetNasID(settings.Ip, settings.Username, settings.Password); err == nil { 348 | acID = retNasID 349 | } 350 | } 351 | } 352 | 353 | if settings.Campus { 354 | settings.Username += "@tsinghua" 355 | } 356 | 357 | err = libauth.LoginLogout(settings.Username, settings.Password, host, logout, settings.Ip, acID) 358 | action := "Login" 359 | if logout { 360 | action = "Logout" 361 | } 362 | if err == nil { 363 | logger.Infof("%s Successfully!\n", action) 364 | runHook(c) 365 | if settings.KeepOn { 366 | if len(settings.Ip) != 0 { 367 | logger.Errorf("Cannot keep another IP online\n") 368 | } else { 369 | return keepAliveLoop(c, settings.Campus) 370 | } 371 | } 372 | } else { 373 | err = fmt.Errorf("%s Failed: %w", action, err) 374 | } 375 | return err 376 | } 377 | 378 | func cmdAuth(ctx context.Context, c *cli.Command) error { 379 | logout := c.Bool("logout") 380 | err := authUtil(c, logout) 381 | if err != nil { 382 | logger.Errorf("Auth error: %s", err) 383 | os.Exit(1) 384 | } 385 | return nil 386 | } 387 | 388 | func cmdDeauth(ctx context.Context, c *cli.Command) error { 389 | err := authUtil(c, true) 390 | if err != nil { 391 | logger.Errorf("Deauth error: %s\n", err) 392 | os.Exit(1) 393 | } 394 | return nil 395 | } 396 | 397 | func cmdKeepalive(ctx context.Context, c *cli.Command) error { 398 | err := parseSettings(c) 399 | if err != nil { 400 | logger.Errorf("Parse setting error: %s\n", err) 401 | os.Exit(1) 402 | } 403 | err = keepAliveLoop(c, c.Bool("campus-only")) 404 | if err != nil { 405 | logger.Errorf("Keepalive error: %s\n", err) 406 | os.Exit(1) 407 | } 408 | return nil 409 | } 410 | 411 | func main() { 412 | cmd := &cli.Command{ 413 | Name: "auth-thu", 414 | UsageText: `auth-thu [options] 415 | auth-thu [options] auth [auth_options] 416 | auth-thu [options] deauth [auth_options] 417 | auth-thu [options] online [online_options]`, 418 | Usage: "Authenticating utility for Tsinghua", 419 | Version: "2.3.5", 420 | HideHelp: true, 421 | Flags: []cli.Flag{ 422 | &cli.StringFlag{Name: "username", Aliases: []string{"u"}, Usage: "your TUNET account `name`"}, 423 | &cli.StringFlag{Name: "password", Aliases: []string{"p"}, Usage: "your TUNET `password`"}, 424 | &cli.StringFlag{Name: "config-file", Aliases: []string{"c"}, Usage: "`path` to your config file, default ~/.auth-thu"}, 425 | &cli.StringFlag{Name: "hook-success", Usage: "command line to be executed in shell after successful login/out"}, 426 | &cli.IntFlag{Name: "online-interval", Aliases: []string{"I"}, Usage: "the interval between each keepAlive request (s)", Value: 3}, 427 | &cli.BoolFlag{Name: "daemonize", Aliases: []string{"D"}, Usage: "run without reading username/password from standard input; less log"}, 428 | &cli.BoolFlag{Name: "debug", Usage: "print debug messages"}, 429 | &cli.BoolFlag{Name: "help, h", Usage: "print the help"}, 430 | }, 431 | Commands: []*cli.Command{ 432 | { 433 | Name: "auth", 434 | Usage: "(default) Auth via auth4/6.tsinghua", 435 | Flags: []cli.Flag{ 436 | &cli.StringFlag{Name: "ip", Usage: "authenticating for specified IP address"}, 437 | &cli.BoolFlag{Name: "no-check", Aliases: []string{"n"}, Usage: "skip online checking, always send login request"}, 438 | &cli.BoolFlag{Name: "logout", Aliases: []string{"o"}, Usage: "de-auth of the online account (behaves the same as deauth command, for backward-compatibility)"}, 439 | &cli.BoolFlag{Name: "ipv6", Aliases: []string{"6"}, Usage: "authenticating for IPv6 (auth6.tsinghua)"}, 440 | &cli.BoolFlag{Name: "campus-only", Aliases: []string{"C"}, Usage: "auth only, no auto-login (v4 only)"}, 441 | &cli.StringFlag{Name: "host", Usage: "use customized hostname of srun4000"}, 442 | &cli.BoolFlag{Name: "insecure", Usage: "use http instead of https"}, 443 | &cli.BoolFlag{Name: "keep-online", Aliases: []string{"k"}, Usage: "keep online after login"}, 444 | &cli.IntFlag{Name: "keep-online-retry", Aliases: []string{"r"}, Usage: "the repeat times of failed keepAlive requests before keepAliveLoop exits with error. Only available when --keep-online set", Value: 2}, 445 | &cli.StringFlag{Name: "ac-id", Usage: "use specified ac_id"}, 446 | }, 447 | Action: cmdAuth, 448 | }, 449 | { 450 | Name: "deauth", 451 | Usage: "De-auth via auth4/6.tsinghua", 452 | Flags: []cli.Flag{ 453 | &cli.StringFlag{Name: "ip", Usage: "authenticating for specified IP address"}, 454 | &cli.BoolFlag{Name: "no-check", Aliases: []string{"n"}, Usage: "skip online checking, always send logout request"}, 455 | &cli.BoolFlag{Name: "ipv6", Aliases: []string{"6"}, Usage: "authenticating for IPv6 (auth6.tsinghua)"}, 456 | &cli.StringFlag{Name: "host", Usage: "use customized hostname of srun4000"}, 457 | &cli.BoolFlag{Name: "insecure", Usage: "use http instead of https"}, 458 | &cli.StringFlag{Name: "ac-id", Usage: "use specified ac_id"}, 459 | }, 460 | Action: cmdDeauth, 461 | }, 462 | { 463 | Name: "online", 464 | Usage: "Keep your computer online", 465 | Flags: []cli.Flag{ 466 | &cli.BoolFlag{Name: "campus-only", Aliases: []string{"C", "auth", "a"}, Usage: "keep alive by requesting in-campus site instead of Internet site"}, 467 | &cli.BoolFlag{Name: "ipv6", Aliases: []string{"6"}, Usage: "keep only ipv6 connection online"}, 468 | &cli.IntFlag{Name: "retry", Aliases: []string{"r"}, Usage: "the repeat times of failed keepAlive requests before keepAliveLoop exits with error", Value: 2}, 469 | }, 470 | Action: cmdKeepalive, 471 | }, 472 | }, 473 | Action: func(ctx context.Context, c *cli.Command) error { 474 | if c.NArg() > 0 { 475 | fmt.Printf("Command not found: %v\n\n", c.Args().Get(0)) 476 | cli.ShowAppHelpAndExit(c, 0) 477 | } else { // when no command, default to auth 478 | cmdAuth(ctx, c) 479 | } 480 | return nil 481 | }, 482 | Authors: []any{ 483 | "Yuxiang Zhang ", 484 | "Nogeek ", 485 | "ZenithalHourlyRate ", 486 | "Jiajie Chen ", 487 | "KomeijiOcean ", 488 | "Sharzy L ", 489 | }, 490 | } 491 | 492 | if err := cmd.Run(context.Background(), os.Args); err != nil { 493 | logger.Errorf("Got error: %s", err) 494 | os.Exit(1) 495 | } 496 | } 497 | -------------------------------------------------------------------------------- /docs/init.d/goauthing: -------------------------------------------------------------------------------- 1 | #!/bin/sh /etc/rc.common 2 | # Authenticating utility for auth.tsinghua.edu.cn 3 | # This init script is used explicitly with OpenWRT 4 | 5 | USE_PROCD=1 6 | START=98 7 | PROG="/usr/bin/goauthing" # cp script to this path first 8 | CONF="/etc/goauthing.json" 9 | 10 | generate_command() { 11 | CMD="\ 12 | \"$PROG\" -c \"$CONF\" -D deauth; \ 13 | \"$PROG\" -c \"$CONF\" -D auth; \ 14 | \"$PROG\" -c \"$CONF\" online; \ 15 | " 16 | } 17 | 18 | start_service() { 19 | generate_command 20 | procd_open_instance 21 | procd_set_param command sh 22 | procd_append_param command -c "$CMD" 23 | procd_set_param stderr 1 24 | procd_set_param respawn 25 | procd_close_instance 26 | } 27 | 28 | stop_service() { 29 | "$PROG" -c "$CONF" -D deauth 30 | } 31 | -------------------------------------------------------------------------------- /docs/init.d/goauthing@: -------------------------------------------------------------------------------- 1 | #!/bin/sh /etc/rc.common 2 | # Authenticating utility for auth.tsinghua.edu.cn 3 | # This init script is used explicitly with OpenWRT 4 | 5 | USE_PROCD=1 6 | START=98 7 | PROG="/usr/bin/goauthing" 8 | SERV=goauthing # UCI config at /etc/config/goauthing 9 | 10 | generate_command() { 11 | CMD="\ 12 | \"$PROG\" $1 deauth; \ 13 | \"$PROG\" $1 auth; \ 14 | \"$PROG\" $1 online; \ 15 | " 16 | } 17 | 18 | start_instance() { 19 | local username password 20 | config_get username config username 21 | config_get password config password 22 | local args="-u $username -p $password" 23 | 24 | generate_command "$args" 25 | 26 | procd_open_instance 27 | procd_set_param command sh 28 | procd_append_param command -c "$CMD" 29 | procd_set_param stderr 1 30 | procd_set_param respawn 31 | procd_close_instance 32 | } 33 | 34 | start_service() { 35 | config_load "$SERV" 36 | start_instance 37 | } 38 | 39 | stop_service() { 40 | "$PROG" deauth 41 | } 42 | -------------------------------------------------------------------------------- /docs/systemd/system/goauthing.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec=0 4 | 5 | [Service] 6 | ExecStartPre=-/usr/local/bin/auth-thu -c /etc/goauthing.json -D deauth 7 | ExecStartPre=-/usr/local/bin/auth-thu -c /etc/goauthing.json -D auth 8 | ExecStart=/usr/local/bin/auth-thu -c /etc/goauthing.json online 9 | User=nobody 10 | Restart=always 11 | RestartSec=5 12 | 13 | [Install] 14 | WantedBy = multi-user.target 15 | -------------------------------------------------------------------------------- /docs/systemd/system/goauthing6.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec=0 4 | 5 | [Service] 6 | ExecStartPre=-/usr/local/bin/auth-thu -c /etc/goauthing.json -D deauth -6 7 | ExecStartPre=-/usr/local/bin/auth-thu -c /etc/goauthing.json -D auth -6 8 | ExecStart=/usr/local/bin/auth-thu -c /etc/goauthing.json online -6 9 | User=nobody 10 | Restart=always 11 | RestartSec=5 12 | 13 | [Install] 14 | WantedBy = multi-user.target 15 | -------------------------------------------------------------------------------- /docs/systemd/system/goauthing6@.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec=0 4 | 5 | [Service] 6 | # default config is in ~/.auth-thu 7 | ExecStartPre=-/usr/local/bin/auth-thu -D deauth -6 8 | ExecStartPre=-/usr/local/bin/auth-thu -D auth -6 9 | ExecStart=/usr/local/bin/auth-thu online -6 10 | User=%i 11 | Restart=always 12 | RestartSec=5 13 | 14 | [Install] 15 | WantedBy = multi-user.target 16 | -------------------------------------------------------------------------------- /docs/systemd/system/goauthing@.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec=0 4 | 5 | [Service] 6 | # default config is in ~/.auth-thu 7 | ExecStartPre=-/usr/local/bin/auth-thu -D deauth 8 | ExecStartPre=-/usr/local/bin/auth-thu -D auth 9 | ExecStart=/usr/local/bin/auth-thu online 10 | User=%i 11 | Restart=always 12 | RestartSec=5 13 | 14 | [Install] 15 | WantedBy = multi-user.target 16 | -------------------------------------------------------------------------------- /docs/systemd/user/goauthing.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description = Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec = 0 4 | 5 | [Service] 6 | ExecStartPre = -/usr/local/bin/auth-thu -D deauth 7 | ExecStartPre = -/usr/local/bin/auth-thu -D auth 8 | ExecStart = /usr/local/bin/auth-thu online 9 | Restart = always 10 | RestartSec = 5 11 | 12 | [Install] 13 | WantedBy = default.target 14 | -------------------------------------------------------------------------------- /docs/systemd/user/goauthing6.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description = Authenticating utility for auth.tsinghua.edu.cn 3 | StartLimitIntervalSec = 0 4 | 5 | [Service] 6 | ExecStartPre = -/usr/local/bin/auth-thu -D deauth -6 7 | ExecStartPre = -/usr/local/bin/auth-thu -D auth -6 8 | ExecStart = /usr/local/bin/auth-thu online -6 9 | Restart = always 10 | RestartSec = 5 11 | 12 | [Install] 13 | WantedBy = multi-user.target 14 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/z4yx/GoAuthing 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.24.2 6 | 7 | require ( 8 | github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef 9 | github.com/juju/loggo v1.0.0 10 | github.com/smartystreets/goconvey v1.6.4 11 | github.com/urfave/cli/v3 v3.2.0 12 | ) 13 | 14 | require ( 15 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect 16 | github.com/jtolds/gls v4.20.0+incompatible // indirect 17 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect 18 | golang.org/x/crypto v0.37.0 // indirect 19 | golang.org/x/sys v0.32.0 // indirect 20 | golang.org/x/term v0.31.0 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= 4 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 5 | github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c h1:aY2hhxLhjEAbfXOx2nRJxCXezC6CO2V/yN+OCr1srtk= 6 | github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs= 7 | github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef h1:A9HsByNhogrvm9cWb28sjiS3i7tcKCkflWFEkHfuAgM= 8 | github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs= 9 | github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= 10 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= 11 | github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU= 12 | github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4 h1:NO5tuyw++EGLnz56Q8KMyDZRwJwWO8jQnj285J3FOmY= 13 | github.com/juju/loggo v0.0.0-20210728185423-eebad3a902c4/go.mod h1:NIXFioti1SmKAlKNuUwbMenNdef59IF52+ZzuOmHYkg= 14 | github.com/juju/loggo v1.0.0 h1:Y6ZMQOGR9Aj3BGkiWx7HBbIx6zNwNkxhVNOHU2i1bl0= 15 | github.com/juju/loggo v1.0.0/go.mod h1:NIXFioti1SmKAlKNuUwbMenNdef59IF52+ZzuOmHYkg= 16 | github.com/lunixbochs/vtclean v0.0.0-20160125035106-4fbf7632a2c6/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= 17 | github.com/mattn/go-colorable v0.0.6/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= 18 | github.com/mattn/go-isatty v0.0.0-20160806122752-66b8e73f3f5c/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= 19 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 20 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 21 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= 22 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= 23 | github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= 24 | github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= 25 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 26 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 27 | github.com/urfave/cli/v3 v3.2.0 h1:m8WIXY0U9LCuUl5r+0fqLWDhNYWt6qvlW+GcF4EoXf8= 28 | github.com/urfave/cli/v3 v3.2.0/go.mod h1:FJSKtM/9AiiTOJL4fJ6TbMUkxBXn7GO9guZqoZtpYpo= 29 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 30 | golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= 31 | golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= 32 | golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= 33 | golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= 34 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 35 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 36 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= 37 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 38 | golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= 39 | golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 40 | golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= 41 | golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= 42 | golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= 43 | golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= 44 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 45 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 46 | gopkg.in/check.v1 v1.0.0-20160105164936-4f90aeace3a2 h1:+j1SppRob9bAgoYmsdW9NNBdKZfgYuWpqnYHv78Qt8w= 47 | gopkg.in/check.v1 v1.0.0-20160105164936-4f90aeace3a2/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 48 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 49 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 50 | -------------------------------------------------------------------------------- /libauth/coding.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | import ( 4 | "bytes" 5 | "crypto/md5" 6 | "crypto/sha1" 7 | "fmt" 8 | "io" 9 | ) 10 | 11 | const base64N = "LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA" 12 | 13 | func sha1sum(input string) string { 14 | h := sha1.New() 15 | io.WriteString(h, input) 16 | return fmt.Sprintf("%x", h.Sum(nil)) 17 | } 18 | 19 | func md5sum(input string) string { 20 | h := md5.New() 21 | io.WriteString(h, input) 22 | return fmt.Sprintf("%x", h.Sum(nil)) 23 | } 24 | 25 | func QuirkBase64Encode(t string) string { 26 | a := len(t) 27 | len := a / 3 * 4 28 | if a%3 != 0 { 29 | len += 4 30 | } 31 | u := make([]byte, len) 32 | r := byte('=') 33 | ui := 0 34 | for o := 0; o < a; o += 3 { 35 | var p [3]byte 36 | p[2] = t[o] 37 | if o+1 < a { 38 | p[1] = t[o+1] 39 | } else { 40 | p[1] = 0 41 | } 42 | if o+2 < a { 43 | p[0] = t[o+2] 44 | } else { 45 | p[0] = 0 46 | } 47 | h := int(p[2])<<16 | int(p[1])<<8 | int(p[0]) 48 | for i := 0; i < 4; i++ { 49 | if o*8+i*6 > a*8 { 50 | u[ui] = r 51 | } else { 52 | u[ui] = base64N[h>>uint(6*(3-i))&0x3F] 53 | } 54 | ui++ 55 | } 56 | } 57 | return string(u[:len]) 58 | } 59 | 60 | func XEncode(str, key string) *string { 61 | 62 | S := func(a string, b bool) []uint32 { 63 | c := len(a) 64 | v := make([]uint32, (c+3)/4) 65 | for i := 0; i < c; i += 4 { 66 | t := uint32(0) 67 | for j := 0; j+i < c && j < 4; j++ { 68 | t |= uint32(a[j+i]) << (uint32(j) * 8) 69 | } 70 | v[i>>2] = t 71 | } 72 | if b { 73 | v = append(v, uint32(c)) 74 | } 75 | return v 76 | } 77 | L := func(a []uint32, b bool) *string { 78 | d := len(a) 79 | c := (d - 1) << 2 80 | if b { 81 | m := int(a[d-1]) 82 | if (m < c-3) || (m > c) { 83 | return nil 84 | } 85 | c = m 86 | } 87 | var buffer bytes.Buffer 88 | for i := 0; i < d; i++ { 89 | buffer.Write([]byte{byte(a[i] & 0xff), byte(a[i] >> 8 & 0xff), byte(a[i] >> 16 & 0xff), byte(a[i] >> 24 & 0xff)}) 90 | } 91 | var s string 92 | if b { 93 | s = buffer.String()[:c] 94 | } else { 95 | s = buffer.String() 96 | } 97 | return &s 98 | } 99 | 100 | if len(str) == 0 { 101 | empty := "" 102 | return &empty 103 | } 104 | v := S(str, true) 105 | k := S(key, false) 106 | n := len(v) - 1 107 | z := v[n] 108 | y := v[0] 109 | d := uint32(0) 110 | for q := 6 + 52/(n+1); q > 0; q-- { 111 | d += 0x9E3779B9 112 | e := (d >> 2) & 3 113 | for p := 0; p <= n; p++ { 114 | if p == n { 115 | y = v[0] 116 | } else { 117 | y = v[p+1] 118 | } 119 | m := (z >> 5) ^ (y << 2) 120 | m += (y >> 3) ^ (z << 4) ^ (d ^ y) 121 | m += k[(p&3)^int(e)] ^ z 122 | v[p] += m 123 | z = v[p] 124 | } 125 | } 126 | return L(v, false) 127 | } 128 | -------------------------------------------------------------------------------- /libauth/coding_test.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | import ( 4 | "testing" 5 | 6 | . "github.com/smartystreets/goconvey/convey" 7 | ) 8 | 9 | func TestQuirkBase64Encode(t *testing.T) { 10 | Convey("QuirkBase64Encode should work", t, func() { 11 | So(QuirkBase64Encode("1"), ShouldEqual, "9+==") 12 | So(QuirkBase64Encode("2"), ShouldEqual, "9S==") 13 | So(QuirkBase64Encode("34"), ShouldEqual, "9z+=") 14 | So(QuirkBase64Encode("567"), ShouldEqual, "0FZ7") 15 | So(QuirkBase64Encode("\x00"), ShouldEqual, "LL==") 16 | So(QuirkBase64Encode("\x00\x00"), ShouldEqual, "LLL=") 17 | So(QuirkBase64Encode("\xff\x00\x00"), ShouldEqual, "AvLL") 18 | So(QuirkBase64Encode("\x01"), ShouldEqual, "L+==") 19 | So(QuirkBase64Encode("\x01==!@#$%^&*()"), ShouldEqual, "LFt52HLkRourRX//8+==") 20 | So(QuirkBase64Encode("\x01aAbB_+=-\x11"), ShouldEqual, "LaiVZYRs8ztfP+==") 21 | }) 22 | } 23 | func TestXEncode(t *testing.T) { 24 | Convey("XEncode should work", t, func() { 25 | So(QuirkBase64Encode(*XEncode("", "aa0edd0fff7dd9f1f0ae4e981ec0114c7b0bf6f67c4895bed4f4ac634e97ecf2")), ShouldEqual, "") 26 | So(QuirkBase64Encode(*XEncode("1", "aa0edd0fff7dd9f1f0ae4e981ec0114c7b0bf6f67c4895bed4f4ac634e97ecf2")), ShouldEqual, "NmsaR0fCm5H=") 27 | So(QuirkBase64Encode(*XEncode("agfawegwq12834eqrge", "aa0edd0fff7dd9f1f0ae4e981ec0114c7b0bf6f67c4895bed4f4ac634e97ecf2")), ShouldEqual, "DAxHygvRUjlDyJjmvChIzuavMsjy7B9L") 28 | So(QuirkBase64Encode(*XEncode("agfawegwq12834eqrge", "0000000000000000000000000000000000000000000000000000000000000000")), ShouldEqual, "TOdQ9ggF2y/mskS6Orkg+eUZIok9vqJr") 29 | So(QuirkBase64Encode(*XEncode("9$02%8r89)(&22{}we[f]|s", "aa0edd0fff7dd9f1f0ae4e981ec0114c7b0bf6f67c4895bed4f4ac634e97ecf2")), ShouldEqual, "kCG+xmvGAhCV717Y80Fk0o1YJ8SYvBdnUmQoqS==") 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /libauth/messages.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | var PortalError = map[string]string{ 4 | "E3001": "流量或时长已用尽", 5 | "E3002": "计费策略条件不匹配", 6 | "E3003": "控制策略条件不匹配", 7 | "E3004": "余额不足", 8 | "E3005": "在线变更计费策略", 9 | "E3006": "在线变更控制策略", 10 | "E3007": "超时", 11 | "E3008": "连线数超额,挤出在线表。", 12 | "E3009": "有代理行为", 13 | "E3010": "无流量超时", 14 | "E3101": "心跳包超时", 15 | "E4001": "Radius表DM下线", 16 | "E4002": "DHCP表DM下线", 17 | "E4003": "Juniper IPOE COA上线", 18 | "E4004": "Juniper IPOE COA下线", 19 | "E4005": "proxy表DM下线", 20 | "E4006": "COA在线更改带宽", 21 | "E4007": "本地下线", 22 | "E4008": "虚拟下线", 23 | "E4009": "策略切换时下发COA", 24 | "E4011": "结算时虚拟下线", 25 | "E4012": "下发COA", 26 | "E4101": "来自radius模块的DM下线(挤出在线表)", 27 | "E4102": "来自系统设置(8081)的DM下线", 28 | "E4103": "来自后台管理(8080)的DM下线", 29 | "E4104": "来自自服务(8800)的DM下线", 30 | "E4112": "来自系统设置(8081)的本地下线", 31 | "E4113": "来自后台管理(8080)的本地下线", 32 | "E4114": "来自自服务(8800)的本地下线", 33 | "E4122": "来自系统设置(8081)的虚拟下线", 34 | "E4123": "来自后台管理(8080)的虚拟下线", 35 | "E4124": "来自自服务(8800)的虚拟下线", 36 | "E2531": "用户不存在", 37 | "E2532": "两次认证的间隔太短", 38 | "E2533": "尝试次数过于频繁", 39 | "E2534": "有代理行为被暂时禁用", 40 | "E2535": "认证系统已关闭", 41 | "E2536": "系统授权已过期", 42 | "E2553": "密码错误", 43 | "E2601": "不是专用客户端", 44 | "E2606": "用户被禁用", 45 | "E2611": "MAC绑定错误", 46 | "E2612": "MAC在黑名单中", 47 | "E2613": "NAS PORT绑定错误", 48 | "E2614": "VLAN ID绑定错误", 49 | "E2615": "IP绑定错误", 50 | "E2616": "已欠费", 51 | "E2620": "已经在线了", 52 | "E2806": "找不到符合条件的产品", 53 | "E2807": "找不到符合条件的计费策略", 54 | "E2808": "找不到符合条件的控制策略", 55 | "E2833": "IP地址异常,请重新拿地址", 56 | "E5990": "数据不完整", 57 | "E5991": "无效的参数", 58 | "E5992": "找不到这个用户", 59 | "E5993": "用户已存在", 60 | "E5001": "用户创建成功", 61 | "E5002": "用户创建失败", 62 | "E5010": "修改用户成功", 63 | "E5011": "修改用户失败", 64 | "E5020": "修改用户成功", 65 | "E5021": "修改用户失败", 66 | "E5030": "转组成功", 67 | "E5031": "转组失败", 68 | "E5040": "购买套餐成功", 69 | "E5041": "购买套餐失败", 70 | "E5042": "找不到套餐", 71 | "E5050": "绑定MAC认证成功", 72 | "E5051": "解绑MAC认证成功", 73 | "E5052": "绑定MAC成功", 74 | "E5053": "解绑MAC成功", 75 | "E5054": "绑定nas port成功", 76 | "E5055": "解绑nas port成功", 77 | "E5056": "绑定vlan id成功", 78 | "E5057": "解绑vlan id成功", 79 | "E5058": "绑定ip成功", 80 | "E5059": "解绑ip成功", 81 | "E6001": "用户缴费成功", 82 | "E6002": "用户缴费失败", 83 | //结算日志 84 | "E7001": "用户不存在", 85 | "E7002": "添加待结算队列失败", 86 | "E7003": "结算成功", 87 | "E7004": "添加已结算队列失败", 88 | "E7005": "扣除产品实例结算金额失败", 89 | "E7006": "没有找到产品实例", 90 | "E7007": "没有对该用户进行手动结算的权限", 91 | "E7008": "没有对该产品进行手动结算的权限", 92 | "E7009": "由于使用流量小于该产品结算设置而不扣费", 93 | "E7010": "由于使用时长小于该产品结算设置而不扣费", 94 | "E7011": "由于产品余额不足,根据结算设置而不扣费", 95 | "E7012": "由于产品余额不足,根据结算设置余额扣为0", 96 | "E7013": "由于产品余额不足,根据结算设置余额扣为负值", 97 | "E7014": "删除过期套餐操作成功", 98 | "E7015": "删除过期套餐操作失败", 99 | "E7016": "自动购买套餐成功", 100 | "E7017": "自动购买套餐失败", 101 | "E7018": "产品结算模式错误", 102 | // 103 | "vcode_error": "验证码错误", 104 | } 105 | -------------------------------------------------------------------------------- /libauth/requests.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | "net/url" 11 | "regexp" 12 | "time" 13 | 14 | "github.com/juju/loggo" 15 | ) 16 | 17 | var logger = loggo.GetLogger("libauth") 18 | 19 | func extractJSONFromJSONP(jsonp, callbackName string) (string, error) { 20 | l := len(callbackName) 21 | if len(jsonp) < l+2 { 22 | return "", errors.New("JSONP string too short") 23 | } 24 | if jsonp[:l] != callbackName || jsonp[l] != '(' || jsonp[len(jsonp)-1] != ')' { 25 | return "", errors.New("Invalid format") 26 | } 27 | return jsonp[l+1 : len(jsonp)-1], nil 28 | } 29 | 30 | func buildChallengeParams(username string, anotherIP string) url.Values { 31 | 32 | challParams := url.Values{ 33 | "username": []string{username}, 34 | "ip": []string{anotherIP}, 35 | "double_stack": []string{"1"}, 36 | } 37 | 38 | return challParams 39 | } 40 | 41 | func buildLoginParams(username, password, token string, logout bool, anotherIP string, acID string) (loginParams url.Values, err error) { 42 | ip := anotherIP 43 | //Required by wireless network only 44 | hmd5 := fmt.Sprintf("%032x", md5.Sum([]byte(password))) 45 | 46 | action := "login" 47 | rawInfo := map[string]string{ 48 | "username": username, 49 | "password": password, 50 | "ip": ip, 51 | "acid": acID, 52 | "enc_ver": "s" + "run" + "_bx1", 53 | } 54 | if logout { 55 | action = "logout" 56 | delete(rawInfo, "password") 57 | } 58 | infoJSON, _ := json.Marshal(rawInfo) 59 | // fmt.Printf("infoJSON: %s\n", infoJSON) 60 | 61 | loginParams = url.Values{ 62 | "action": []string{action}, 63 | "ac_id": []string{acID}, 64 | "n": []string{"200"}, 65 | "type": []string{"1"}, 66 | "ip": []string{ip}, 67 | "double_stack": []string{"1"}, 68 | "username": []string{username}, 69 | } 70 | if !logout { 71 | loginParams.Add("password", "{MD5}"+hmd5) 72 | } 73 | encoded := XEncode(string(infoJSON), token) 74 | if encoded == nil { 75 | err = errors.New("XEncode failed") 76 | return 77 | } 78 | loginParams.Add("info", "{SRBX1}"+QuirkBase64Encode(*encoded)) 79 | // fmt.Printf("chksum(raw): %v\n", token+username+token + hmd5+token+acID+token+ip+token+loginParams.Get("n")+token+loginParams.Get("type")+token+loginParams.Get("info")) 80 | if logout { 81 | loginParams.Add("chksum", sha1sum(token+username+token+acID+token+ip+token+loginParams.Get("n")+token+loginParams.Get("type")+token+loginParams.Get("info"))) 82 | } else { 83 | loginParams.Add("chksum", sha1sum(token+username+token+hmd5+token+acID+token+ip+token+loginParams.Get("n")+token+loginParams.Get("type")+token+loginParams.Get("info"))) 84 | } 85 | // fmt.Printf("loginParams: %v\n", loginParams) 86 | return 87 | } 88 | 89 | func GetJSON(baseUrl string, params url.Values) (string, error) { 90 | const CB = "C_a_l_l_b_a_c_k" 91 | params.Set("callback", CB) 92 | var netClient = &http.Client{ 93 | Timeout: time.Second * 2, 94 | } 95 | url := baseUrl + "?" + params.Encode() 96 | logger.Debugf("GET \"%s\"\n", url) 97 | resp, err := netClient.Get(url) 98 | if err != nil { 99 | return "", err 100 | } 101 | defer resp.Body.Close() 102 | body, err := ioutil.ReadAll(resp.Body) 103 | if err != nil { 104 | return "", err 105 | } 106 | return extractJSONFromJSONP(string(body), CB) 107 | } 108 | 109 | func IsOnline(host *UrlProvider, acID string) (online bool, err error, username string) { 110 | logger.Debugf("Check if online\n") 111 | var netClient = &http.Client{ 112 | Timeout: time.Second * 2, 113 | } 114 | online = false 115 | params := url.Values{ 116 | "ac_id": []string{acID}, 117 | } 118 | uri := host.OnlineCheckUriBase() + "?" + params.Encode() 119 | logger.Debugf("GET \"%s\"\n", uri) 120 | resp, err := netClient.Get(uri) 121 | if err != nil { 122 | return 123 | } 124 | defer resp.Body.Close() 125 | 126 | // find public ip from response 127 | body, err := ioutil.ReadAll(resp.Body) 128 | if err != nil { 129 | return 130 | } 131 | regexMatchIP := regexp.MustCompile(`ip\s+:\s"([0-9.]+)"`) 132 | matches := regexMatchIP.FindStringSubmatch(string(body)) 133 | if len(matches) < 2 { 134 | err = errors.New("ip not found") 135 | return 136 | } 137 | ip := matches[1] 138 | logger.Debugf("ip=%s\n", ip) 139 | 140 | // Get user info 141 | logger.Debugf("Get user info\n") 142 | params = url.Values{ 143 | "ip": []string{ip}, 144 | } 145 | info, err := GetJSON(host.UserInfoUriBase(), params) 146 | 147 | var infoResp map[string]interface{} 148 | err = json.Unmarshal([]byte(info), &infoResp) 149 | logger.Debugf("Get user info %v\n", infoResp) 150 | if err != nil { 151 | return 152 | } 153 | 154 | res, valid := infoResp["error"].(string) 155 | if valid && res == "ok" { 156 | online = true 157 | logger.Debugf("User is online\n") 158 | } 159 | 160 | res, valid = infoResp["user_name"].(string) 161 | if valid { 162 | username = res 163 | logger.Debugf("User name is \"%s\"\n", username) 164 | } 165 | 166 | return 167 | } 168 | 169 | func GetNasID(IP, user, password string) (nasID string, err error) { 170 | err = errors.New("Not implemented for usereg 2025") 171 | return 172 | } 173 | 174 | func GetAcID(V6 bool) (acID string, err error) { 175 | logger.Debugf("Get AC ID\n") 176 | var netClient = &http.Client{ 177 | Timeout: time.Second * 2, 178 | CheckRedirect: func(req *http.Request, via []*http.Request) error { 179 | logger.Debugf("REDIRECT \"%v\"\n", req.URL) 180 | return errors.New("should not redirect") 181 | }, 182 | } 183 | acID = "" 184 | var resp *http.Response 185 | var body []byte 186 | url := "http://login.tsinghua.edu.cn/index_1.html" 187 | if V6 { 188 | url = "http://mirrors6.tuna.tsinghua.edu.cn/" 189 | } 190 | logger.Debugf("GET \"%s\"\n", url) 191 | resp, err = netClient.Get(url) 192 | if err != nil { 193 | return 194 | } 195 | defer resp.Body.Close() 196 | body, err = ioutil.ReadAll(resp.Body) 197 | if err != nil { 198 | return 199 | } 200 | regexMatchAcID := regexp.MustCompile(`(ac_id=|index_)([0-9]+)`) 201 | matches := regexMatchAcID.FindStringSubmatch(string(body)) 202 | if len(matches) < 3 { 203 | err = errors.New("ac_id not found") 204 | return 205 | } 206 | acID = matches[2] 207 | logger.Debugf("ac_id=%s\n", acID) 208 | return 209 | } 210 | 211 | func LoginLogout(username, password string, host *UrlProvider, logout bool, anotherIP string, acID string) (err error) { 212 | logger.Debugf("Getting challenge...\n") 213 | body, err := GetJSON(host.ChallengeUriBase(), buildChallengeParams(username, anotherIP)) 214 | if err != nil { 215 | return 216 | } 217 | logger.Debugf("Challenge response: %v\n", body) 218 | 219 | var challResp map[string]interface{} 220 | err = json.Unmarshal([]byte(body), &challResp) 221 | if err != nil { 222 | return 223 | } 224 | res, valid := challResp["res"].(string) 225 | if !valid || res != "ok" { 226 | err = errors.New("Failed to get challenge: " + res) 227 | return 228 | } 229 | token, valid := challResp["challenge"].(string) 230 | if !valid { 231 | err = errors.New("No challenge field") 232 | return 233 | } 234 | 235 | loginParams, err := buildLoginParams(username, password, token, logout, anotherIP, acID) 236 | if err != nil { 237 | return 238 | } 239 | logger.Debugf("Sending login request...\n") 240 | body, err = GetJSON(host.LoginUriBase(), loginParams) 241 | if err != nil { 242 | return 243 | } 244 | logger.Debugf("Login response: %v\n", body) 245 | var loginResp map[string]interface{} 246 | err = json.Unmarshal([]byte(body), &loginResp) 247 | if err != nil { 248 | return 249 | } 250 | res, valid = loginResp["error"].(string) 251 | if !valid { 252 | err = errors.New("No error field") 253 | return 254 | } 255 | 256 | if res == "ok" { 257 | err = nil 258 | } else { 259 | ecode, _ := loginResp["ecode"].(string) 260 | if strerr, exist := PortalError[ecode]; exist { 261 | err = errors.New(strerr) 262 | } else { 263 | err = errors.New(res) 264 | } 265 | } 266 | 267 | return 268 | } 269 | -------------------------------------------------------------------------------- /libauth/requests_test.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | import ( 4 | "testing" 5 | 6 | . "github.com/smartystreets/goconvey/convey" 7 | ) 8 | 9 | func TestExtractJSONFromJSONP(t *testing.T) { 10 | 11 | Convey("Extracting JSON from JSONP...", t, func() { 12 | json, err := extractJSONFromJSONP("cb()", "cb") 13 | So(err, ShouldBeNil) 14 | So(json, ShouldEqual, "") 15 | json, err = extractJSONFromJSONP("C({})", "C") 16 | So(err, ShouldBeNil) 17 | So(json, ShouldEqual, "{}") 18 | json, err = extractJSONFromJSONP(`jQuery({"key1": 1234})`, "jQuery") 19 | So(err, ShouldBeNil) 20 | So(json, ShouldEqual, `{"key1": 1234}`) 21 | json, err = extractJSONFromJSONP("C({})", "") 22 | So(err, ShouldNotBeNil) 23 | json, err = extractJSONFromJSONP("C({})", "Q") 24 | So(err, ShouldNotBeNil) 25 | json, err = extractJSONFromJSONP("C({}", "C") 26 | So(err, ShouldNotBeNil) 27 | json, err = extractJSONFromJSONP("", "C") 28 | So(err, ShouldNotBeNil) 29 | }) 30 | } 31 | 32 | // func TestBuildLoginParams(t *testing.T) { 33 | // loggo.ConfigureLoggers("libauth=DEBUG") 34 | // buildLoginParams("hello", "pass", "32f23b9c2229fd034f6d5160d8b4536496af550efc45113635689d2d8f12ffad") 35 | // } 36 | -------------------------------------------------------------------------------- /libauth/urls.go: -------------------------------------------------------------------------------- 1 | package libauth 2 | 3 | type UrlProvider struct { 4 | protocol, host string 5 | } 6 | 7 | func NewUrlProvider(host string, insecure bool) *UrlProvider { 8 | u := new(UrlProvider) 9 | u.host = host 10 | if insecure { 11 | u.protocol = "http://" 12 | } else { 13 | u.protocol = "https://" 14 | } 15 | return u 16 | } 17 | 18 | func (u *UrlProvider) LoginUriBase() string { 19 | return u.protocol + u.host + "/cgi-bin/srun_portal" 20 | } 21 | 22 | func (u *UrlProvider) OnlineCheckUriBase() string { 23 | return u.protocol + u.host + "/srun_portal_pc" 24 | } 25 | 26 | func (u *UrlProvider) ChallengeUriBase() string { 27 | return u.protocol + u.host + "/cgi-bin/get_challenge" 28 | } 29 | 30 | func (u *UrlProvider) UserInfoUriBase() string { 31 | return u.protocol + u.host + "/cgi-bin/rad_user_info" 32 | } --------------------------------------------------------------------------------