Initial commit: Complete WebSocket SSH tunneling system

- WebSocket SSH Daemon (wssshd) with web management interface
- WebSocket SSH Client (wssshc) with password authentication
- SSH wrapper (wsssh) with intelligent hostname parsing
- SCP wrapper (wsscp) with tunneling support
- Professional web UI with user management and HTML5 terminal
- SQLite database for persistent user storage
- Role-based access control (admin/normal users)
- SSL certificate auto-generation during build
- Automated build system with venv management
- Comprehensive documentation and examples
parents
Pipeline #183 canceled with stages
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2024-09-12
### Added
- **Initial release** of WebSocket SSH tunneling system
- **wssshd**: WebSocket SSH Daemon for managing client connections and tunnel routing
- **wssshc**: WebSocket SSH Client for registering machines with the daemon
- **wsssh**: SSH command wrapper with automatic hostname parsing and tunnel establishment
- **wsscp**: SCP command wrapper with WebSocket tunneling support
- **Intelligent hostname parsing**: Support for `<CLIENT_ID>.<HOST>[:<PORT>]` format
- **Automatic port detection**: Priority-based port resolution (hostname suffix > command options > defaults)
- **SSL/TLS encryption**: Secure WebSocket communications with self-signed certificates
- **Client registration system**: Unique client identification and persistent connections
- **Build system**: Automated binary creation using PyInstaller
- **Cross-platform support**: Linux, macOS, and Windows compatibility
- **Comprehensive documentation**: README, installation guides, and usage examples
### Features
- **Drop-in SSH/SCP replacement**: Use `wsssh` and `wsscp` as direct replacements for standard commands
- **Multi-client routing**: Route connections to different registered clients based on hostname
- **Automatic tunnel management**: Dynamic local port allocation and tunnel lifecycle management
- **Debug mode**: Detailed logging for troubleshooting connections and tunnels
- **Reconnection logic**: Automatic reconnection for client registration
### Technical Details
- **WebSocket-based architecture**: Real-time bidirectional communication
- **Async I/O**: High-performance asynchronous operations using asyncio
- **Binary distribution**: Standalone executables with embedded dependencies
- **Certificate management**: Automatic SSL certificate generation and embedding
- **Protocol parsing**: SSH protocol inspection for user authentication routing
### Security
- **Encrypted communications**: All WebSocket traffic protected by SSL/TLS
- **Client authentication**: Unique identifier-based client verification
- **Secure tunneling**: Isolated tunnel sessions per connection
## [0.1.0] - 2024-09-11
### Added
- **Proof of concept** implementation
- Basic WebSocket SSH tunneling functionality
- Initial client-server architecture
- Command-line interface foundation
- SSL certificate generation
- Build system setup
### Changed
- Initial architecture design
- Basic protocol implementation
### Fixed
- Initial connection handling
- Basic error management
---
## Types of changes
- `Added` for new features
- `Changed` for changes in existing functionality
- `Deprecated` for soon-to-be removed features
- `Removed` for now removed features
- `Fixed` for any bug fixes
- `Security` in case of vulnerabilities
## Versioning
This project uses [Semantic Versioning](https://semver.org/).
Given a version number MAJOR.MINOR.PATCH, increment the:
- **MAJOR** version when you make incompatible API changes
- **MINOR** version when you add functionality in a backwards compatible manner
- **PATCH** version when you make backwards compatible bug fixes
Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.
---
## Development Notes
### Upcoming Features (Roadmap)
- **Enhanced security**: Certificate pinning and mutual TLS authentication
- **Load balancing**: Multi-server daemon support with automatic failover
- **Performance optimization**: Connection pooling and multiplexing
- **GUI client**: Desktop application for easier management
- **REST API**: HTTP API for programmatic tunnel management
- **Container support**: Docker images and Kubernetes integration
- **Monitoring**: Metrics collection and health monitoring
- **Plugin system**: Extensible architecture for custom protocols
### Known Issues
- Self-signed certificate warnings in browsers/clients
- Limited Windows testing (primarily developed on Linux)
- No built-in rate limiting or DDoS protection
- Basic error handling (room for improvement)
### Contributing
Please see [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines and contribution procedures.
\ No newline at end of file
# WebSocket SSH Documentation
## Table of Contents
1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Protocol Specification](#protocol-specification)
4. [API Reference](#api-reference)
5. [Configuration](#configuration)
6. [Security](#security)
7. [Troubleshooting](#troubleshooting)
8. [Development](#development)
## Overview
WebSocket SSH (wsssh) is a tunneling system that enables secure SSH/SCP access to remote machines through WebSocket-based intermediaries. Unlike traditional SSH jump hosts, wsssh uses WebSocket connections for real-time, bidirectional communication between clients and servers.
### Key Components
- **wssshd**: WebSocket SSH Daemon - Central server managing connections
- **wssshc**: WebSocket SSH Client - Registers machines with the daemon
- **wsssh**: SSH wrapper - Provides SSH access through tunnels
- **wsscp**: SCP wrapper - Provides SCP access through tunnels
### Core Features
- **Intelligent Hostname Parsing**: Automatic detection of client IDs and server endpoints
- **SSL/TLS Encryption**: Secure WebSocket communications
- **Multi-client Support**: Route connections to different registered clients
- **Drop-in Replacement**: Compatible with existing SSH/SCP workflows
- **Cross-platform**: Works on Linux, macOS, and Windows
## Architecture
### System Architecture
```
┌─────────────────┐ WebSocket (WSS) ┌─────────────────┐
│ SSH/SCP │◄────────────────────►│ wssshd │
│ Client │ │ (Daemon) │
└─────────────────┘ └─────────────────┘
│ WebSocket (WSS)
┌─────────────────┐
│ wssshc │
│ (Client) │
│ │
│ ┌─────────────┐ │
│ │ SSH Server │ │
│ │ (sshd) │ │
│ └─────────────┘ │
└─────────────────┘
```
### Data Flow
1. **Registration Phase**:
- wssshc connects to wssshd via WebSocket
- Registers with unique client ID
- Maintains persistent connection
2. **Connection Phase**:
- User runs `wsssh ssh user@client.domain`
- wsssh parses hostname to extract client ID and server endpoint
- wsssh connects to wssshd and requests tunnel to client
- wssshd forwards request to appropriate wssshc
- wssshc establishes local tunnel to SSH server
- wsssh launches SSH client to local tunnel port
3. **Data Transfer Phase**:
- SSH traffic flows: SSH Client ↔ wsssh ↔ wssshd ↔ wssshc ↔ SSH Server
- All WebSocket connections are encrypted with SSL/TLS
## Protocol Specification
### WebSocket Message Format
All messages are JSON-encoded with the following structure:
```json
{
"type": "message_type",
"request_id": "uuid_string",
"client_id": "client_identifier",
"data": "base64_encoded_data"
}
```
### Message Types
#### Client Registration Messages
**Register Client** (wssshc → wssshd):
```json
{
"type": "register",
"id": "client_unique_id"
}
```
**Registration Acknowledgment** (wssshd → wssshc):
```json
{
"type": "registered",
"id": "client_unique_id"
}
```
#### Tunnel Management Messages
**Request Tunnel** (wsssh → wssshd):
```json
{
"type": "tunnel_request",
"client_id": "target_client_id",
"request_id": "unique_request_uuid"
}
```
**Tunnel Acknowledgment** (wssshd → wsssh):
```json
{
"type": "tunnel_ack",
"request_id": "unique_request_uuid"
}
```
**Tunnel Error** (wssshd → wsssh):
```json
{
"type": "tunnel_error",
"request_id": "unique_request_uuid",
"error": "error_description"
}
```
**Forward Tunnel Request** (wssshd → wssshc):
```json
{
"type": "tunnel_request",
"request_id": "unique_request_uuid"
}
```
#### Data Transfer Messages
**Tunnel Data** (bidirectional):
```json
{
"type": "tunnel_data",
"request_id": "unique_request_uuid",
"data": "base64_encoded_binary_data"
}
```
**Close Tunnel** (wsssh → wssshd → wssshc):
```json
{
"type": "tunnel_close",
"request_id": "unique_request_uuid"
}
```
### Hostname Parsing Algorithm
The hostname parsing follows this algorithm:
```
Input: hostname (e.g., "myclient.example.com:9898")
1. Split by ':' to separate port
host_part = "myclient.example.com"
port_part = "9898" (optional)
2. Split host_part by '.' to get parts
parts = ["myclient", "example", "com"]
3. If parts.length >= 2:
client_id = parts[0] // "myclient"
wssshd_host = parts[1:].join('.') // "example.com"
Else:
client_id = host_part // fallback
wssshd_host = "localhost" // fallback
4. Determine wssshd_port:
if port_part exists: use port_part
elif ssh_port specified: use ssh_port
else: use 22 (default)
```
## API Reference
### wssshd (WebSocket SSH Daemon)
#### Command Line Options
```bash
wssshd --host HOST --port PORT --domain DOMAIN [--debug]
```
- `--host HOST`: Bind address for WebSocket server (default: 0.0.0.0)
- `--port PORT`: WebSocket server port (required)
- `--domain DOMAIN`: Domain suffix for hostname parsing (required)
- `--debug`: Enable debug output
#### WebSocket Endpoints
- `ws://HOST:PORT/`: Main WebSocket endpoint for client connections
### wssshc (WebSocket SSH Client)
#### Command Line Options
```bash
wssshc --server-ip IP --port PORT --id ID [--interval SEC] [--debug]
```
- `--server-ip IP`: wssshd server IP address (required)
- `--port PORT`: wssshd server port (required)
- `--id ID`: Unique client identifier (required)
- `--interval SEC`: Reconnection interval in seconds (default: 30)
- `--debug`: Enable debug output
### wsssh (SSH Wrapper)
#### Command Line Options
```bash
wsssh [--local-port PORT] [--debug] ssh [SSH_OPTIONS...] user@host [COMMAND...]
```
- `--local-port PORT`: Local tunnel port (default: auto-assign)
- `--debug`: Enable debug output
#### Environment Variables
- None
### wsscp (SCP Wrapper)
#### Command Line Options
```bash
wsscp [--local-port PORT] [--debug] scp [SCP_OPTIONS...] SOURCE... DESTINATION
```
- `--local-port PORT`: Local tunnel port (default: auto-assign)
- `--debug`: Enable debug output
## Configuration
### SSL Certificate Configuration
The system uses SSL/TLS certificates for WebSocket encryption:
- **Certificate File**: `cert.pem` (X.509 certificate)
- **Private Key File**: `key.pem` (RSA/ECDSA private key)
Certificates are automatically generated during the build process using OpenSSL:
```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
-days 365 -nodes -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
```
### Client Configuration
Each client machine requires:
1. **Unique Client ID**: Identifier for routing connections
2. **Network Access**: Ability to connect to wssshd server
3. **SSH Server**: Running SSH daemon (sshd) on the client machine
### Server Configuration
The wssshd server requires:
1. **Network Interface**: IP address and port for WebSocket connections
2. **Domain Configuration**: Domain suffix for hostname parsing
3. **SSL Certificates**: Valid certificate and private key files
## Security
### Encryption
- **WebSocket Transport**: All WebSocket connections use SSL/TLS encryption
- **Certificate Validation**: Clients verify server certificates
- **Data in Transit**: All tunnel data is encrypted end-to-end
### Authentication
- **Client Registration**: Unique client IDs prevent unauthorized access
- **SSH Authentication**: Standard SSH authentication mechanisms
- **Connection Isolation**: Each tunnel session is isolated
### Security Considerations
1. **Certificate Management**:
- Use proper CA-signed certificates in production
- Regularly rotate certificates
- Implement certificate pinning if required
2. **Network Security**:
- Restrict wssshd access to trusted networks
- Use firewalls to limit exposure
- Implement rate limiting
3. **Client Security**:
- Use strong, unique client IDs
- Regularly rotate client registrations
- Monitor client connection logs
4. **SSH Security**:
- Disable password authentication
- Use key-based authentication
- Implement SSH hardening practices
### Known Security Limitations
- Self-signed certificates may trigger warnings
- No built-in DDoS protection
- Basic client authentication (ID-based only)
- No session encryption beyond SSL/TLS
## Troubleshooting
### Common Issues
#### Connection Refused
**Symptoms**: "Connection refused" when connecting to wssshd
**Causes**:
- wssshd not running
- Firewall blocking port
- Incorrect host/port configuration
**Solutions**:
```bash
# Check if wssshd is running
netstat -tlnp | grep :9898
# Test WebSocket connection
curl -I https://localhost:9898
```
#### Client Not Registered
**Symptoms**: "Client not registered" error
**Causes**:
- wssshc not running on target machine
- Incorrect client ID in hostname
- Network connectivity issues
**Solutions**:
```bash
# Check client registration
./wssshc --server-ip <ip> --port 9898 --id <client_id>
# Verify client appears in wssshd logs
tail -f wssshd.log
```
#### SSL Certificate Errors
**Symptoms**: SSL verification failures
**Causes**:
- Self-signed certificates
- Expired certificates
- Certificate hostname mismatch
**Solutions**:
```bash
# Regenerate certificates
./build.sh
# Check certificate validity
openssl x509 -in cert.pem -text -noout
```
#### Tunnel Connection Issues
**Symptoms**: SSH/SCP connections hang or fail
**Causes**:
- Local SSH server not running
- Port conflicts
- Firewall blocking local ports
**Solutions**:
```bash
# Check local SSH server
systemctl status sshd
# Test local SSH connection
ssh localhost
# Check port availability
netstat -tlnp | grep :22
```
### Debug Mode
Enable debug output for detailed troubleshooting:
```bash
# wssshd debug
./wssshd --debug --host 0.0.0.0 --port 9898 --domain example.com
# wssshc debug
./wssshc --debug --server-ip <ip> --port 9898 --id client1
# wsssh debug
./wsssh --debug ssh user@client.example.com
# wsscp debug
./wsscp --debug scp file user@client.example.com:/path/
```
### Log Analysis
Key log messages to monitor:
- **Registration**: "Client X registered"
- **Tunnel Requests**: "Tunnel request for client X"
- **Connection Issues**: "Connection failed" or "SSL verification failed"
- **Data Transfer**: "Forwarding X bytes"
## Development
### Project Structure
```
wsssh/
├── wssshd.py # WebSocket SSH Daemon
├── wssshc.py # WebSocket SSH Client
├── wsssh.py # SSH wrapper
├── wsscp.py # SCP wrapper
├── build.sh # Build script
├── clean.sh # Clean script
├── cert.pem # SSL certificate
├── key.pem # SSL private key
├── LICENSE.md # GPLv3 license
├── README.md # Main documentation
├── CHANGELOG.md # Version history
└── DOCUMENTATION.md # This file
```
### Dependencies
- **Python 3.7+**
- **websockets**: WebSocket client/server library
- **ssl**: SSL/TLS support (built-in)
- **asyncio**: Asynchronous I/O (built-in)
- **subprocess**: Process management (built-in)
- **socket**: Network sockets (built-in)
### Building from Source
```bash
# Install dependencies
pip3 install websockets
# Run tests
python3 -m pytest tests/
# Build binaries
./build.sh
# Clean build artifacts
./clean.sh
```
### Testing
```bash
# Unit tests
python3 -m pytest tests/test_*.py
# Integration tests
python3 -m pytest tests/integration/
# Manual testing
./test/manual_test.sh
```
### Code Style
- Follow PEP 8 style guidelines
- Use type hints for function parameters
- Include docstrings for all public functions
- Use descriptive variable names
### Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### Release Process
1. Update version in all relevant files
2. Update CHANGELOG.md
3. Create git tag
4. Build release binaries
5. Create GitHub release
6. Update documentation
---
## Support
For support and questions:
- **GitHub Issues**: Bug reports and feature requests
- **Documentation**: This comprehensive guide
- **Community**: Join discussions and get help
## License
This project is licensed under the GNU General Public License v3.0 (GPLv3).
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
See [LICENSE.md](LICENSE.md) for the full license text.
\ No newline at end of file
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a way requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, without transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which exist only as aggregate whole for convenience of
distribution, is not a (copyrighted) work based on the Program, and
neither requires nor permits licensing of the aggregate under the
terms of this License.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under subsection 6d must be accompanied
by Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, contained in a covered work,
that you add or that you receive from third parties.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, copyrights, or trademarks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a copy of the covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, in which
the contributor contributes, of making, using, or selling its
contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor
version. For purposes of this definition, "control" includes the right
to grant patent sublicenses in a manner consistent with the requirements
of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an express agreement or commitment not to
enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to also be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the patent business, where the third party's business model is to
license patents, and in connection with which you convey the work, or
propagate by procuring conveyance of, grant, or induce any third party
to grant, any patent license involving the covered work, except as
expressly permitted under this License.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you can satisfy both those terms and this
License is to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional permissions appear to be granted
by any later version for the Program itself.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, except for the acts of willful misconduct by the copyright
holder or another party.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you can redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
\ No newline at end of file
# WebSocket SSH (wsssh)
A modern SSH tunneling system that uses WebSocket connections to securely route SSH/SCP traffic through registered client machines. This allows you to access remote servers through intermediate "jump hosts" using WebSocket-based tunnels.
## Features
- **WebSocket-based Tunneling**: Secure SSH/SCP access through WebSocket connections
- **Client Registration**: Register client machines with the WebSocket daemon
- **Password Authentication**: Secure client registration with configurable passwords
- **Web Management Interface**: Professional admin panel with user management and HTML5 terminal
- **Intelligent Hostname Parsing**: `<CLIENT_ID>.<WSSSHD_HOST>` format with `-p`/`-P` port options
- **Drop-in SSH/SCP Replacement**: Use `wsssh` and `wsscp` as direct replacements for `ssh` and `scp`
- **SSL/TLS Encryption**: All WebSocket communications are encrypted
- **Multi-client Support**: Route connections to different registered clients
- **Cross-platform**: Works on Linux, macOS, and Windows
## Architecture
The system consists of four main components:
1. **`wssshd`** - WebSocket SSH Daemon (server)
- Manages WebSocket connections
- Handles client registrations with password authentication
- Routes tunnel requests to appropriate clients
- Optional web management interface with user administration
- HTML5 terminal interface for SSH connections
2. **`wssshc`** - WebSocket SSH Client (registration)
- Registers client machines with the daemon
- Maintains persistent WebSocket connection
3. **`wsssh`** - SSH wrapper with tunneling
- Parses SSH commands and hostnames
- Establishes WebSocket tunnels
- Launches SSH to local tunnel port
4. **`wsscp`** - SCP wrapper with tunneling
- Similar to wsssh but for SCP operations
- Handles file transfers through tunnels
## Installation
### From Source
```bash
# Clone the repository
git clone https://github.com/your-repo/wsssh.git
cd wsssh
# Install dependencies
pip3 install -r requirements.txt
# Build binaries (optional)
./build.sh
```
### Using Pre-built Binaries
Download the latest release binaries for your platform from the releases page.
## Quick Start
### 1. Start the WebSocket Daemon
```bash
./wssshd --host 0.0.0.0 --port 9898 --domain example.com
```
### 2. Register a Client
On the client machine you want to access through:
```bash
./wssshc --server-ip <daemon_ip> --port 9898 --id myclient
```
### 3. Connect via SSH
```bash
./wsssh ssh user@myclient.example.com
```
This automatically:
- Parses `myclient.example.com` to extract client ID `myclient`
- Connects to wssshd at `example.com:22` (default SSH port)
- Requests tunnel to client `myclient`
- Opens local port and launches `ssh user@localhost`
## Hostname Format
The system uses intelligent hostname parsing:
```
<CLIENT_ID>.<WSSSHD_HOST>
```
Port is specified using `-p` (SSH) or `-P` (SCP) options.
### Examples:
- `remote.example.com -p 9898` → Client: `remote`, Server: `example.com:9898`
- `server.datacenter.com -P 2222` → Client: `server`, Server: `datacenter.com:2222`
- `test.localhost -p 8080` → Client: `test`, Server: `localhost:8080`
## Port Detection Priority
1. **Hostname suffix**: `host:port` in the target hostname
2. **SSH/SCP port option**: `-p <port>` (SSH) or `-P <port>` (SCP)
3. **Default**: `22` (standard SSH port)
## Detailed Usage
### wssshd (WebSocket SSH Daemon)
```bash
./wssshd --host 0.0.0.0 --port 9898 --domain example.com --password mysecret [--web-host 0.0.0.0 --web-port 8080] [--debug]
```
**Options:**
- `--host`: Bind address (default: 0.0.0.0)
- `--port`: WebSocket port (required)
- `--domain`: Domain suffix for hostname parsing
- `--password`: Registration password (required)
- `--web-host`: Web interface bind address (optional)
- `--web-port`: Web interface port (optional)
- `--debug`: Enable debug output
**Web Interface:**
When `--web-host` and `--web-port` are specified, a web management interface is available with:
- User authentication (default: admin/admin123)
- Client connection overview
- User management (admin only)
- HTML5 terminal interface
### wssshc (WebSocket SSH Client)
```bash
./wssshc --server-ip <ip> --port 9898 --id client1 --password mysecret [--interval 30] [--debug]
```
**Options:**
- `--server-ip`: wssshd server IP address (required)
- `--port`: wssshd server port (required)
- `--id`: Unique client identifier (required)
- `--password`: Registration password (required)
- `--interval`: Reconnection interval in seconds (default: 30)
- `--debug`: Enable debug output
### wsssh (SSH Wrapper)
```bash
./wsssh [options] ssh user@client.domain [ssh_options...]
```
**Options:**
- `--local-port`: Local tunnel port (default: auto)
- `--debug`: Enable debug output
**Examples:**
```bash
# Basic SSH connection
./wsssh ssh -p 9898 user@myclient.example.com
# SSH with custom port
./wsssh ssh -p 2222 user@myclient.example.com
# SSH with options
./wsssh ssh -p 9898 -i ~/.ssh/key user@myclient.example.com ls -la
```
### wsscp (SCP Wrapper)
```bash
./wsscp [options] scp [scp_options...] source destination
```
**Options:**
- `--local-port`: Local tunnel port (default: auto)
- `--debug`: Enable debug output
**Examples:**
```bash
# Copy file to remote
./wsscp scp -P 9898 localfile user@myclient.example.com:/remote/path/
# Copy file from remote
./wsscp scp -P 9898 user@myclient.example.com:/remote/file ./localfile
# Copy with custom port
./wsscp scp -P 2222 localfile user@myclient.example.com:/remote/path/
```
## Configuration
### SSL Certificates
The system uses self-signed SSL certificates for WebSocket encryption. Certificates are automatically generated during the build process if they don't exist.
- `cert.pem`: SSL certificate
- `key.pem`: Private key
Certificates are created with:
- 4096-bit RSA key
- Valid for 365 days
- Subject: `/C=US/ST=State/L=City/O=Organization/CN=localhost`
### Client Registration
Each client machine must be registered with wssshd using a unique ID:
```bash
./wssshc --server-ip <daemon_ip> --port <port> --id <unique_id>
```
The client will maintain a persistent WebSocket connection to the daemon.
## Security Considerations
- **SSL/TLS**: All WebSocket communications are encrypted
- **Client Authentication**: Clients are identified by unique IDs
- **Network Security**: Ensure wssshd is only accessible from trusted networks
- **Certificate Validation**: Currently uses self-signed certificates
## Troubleshooting
### Connection Issues
1. **Check wssshd is running**: Verify the daemon is accessible on the specified port
2. **Client registration**: Ensure the client is registered and connected
3. **Firewall rules**: Check that required ports are open
4. **SSL certificates**: Verify certificate files exist and are valid
### Debug Mode
Enable debug output for detailed troubleshooting:
```bash
./wssshd --debug --host 0.0.0.0 --port 9898 --domain example.com
./wssshc --debug --server-ip <ip> --port 9898 --id client1
./wsssh --debug ssh user@client.domain
```
### Common Issues
- **"Client not registered"**: Register the client with wssshc first
- **"Connection refused"**: Check wssshd is running and ports are accessible
- **"SSL verification failed"**: The system uses self-signed certificates
## Development
### Building from Source
```bash
# Install dependencies
pip3 install -r requirements.txt
# Run tests
python3 -m pytest
# Build binaries
./build.sh
# Clean build artifacts
./clean.sh
```
### Project Structure
```
wsssh/
├── wssshd.py # WebSocket SSH Daemon with web interface
├── wssshc.py # WebSocket SSH Client
├── wsssh.py # SSH wrapper
├── wsscp.py # SCP wrapper
├── build.sh # Build script
├── clean.sh # Clean script
├── requirements.txt # Python dependencies
├── cert.pem # SSL certificate
├── key.pem # SSL private key
├── templates/ # Flask HTML templates
│ ├── base.html
│ ├── index.html
│ ├── login.html
│ ├── terminal.html
│ └── users.html
├── static/ # Static web assets
├── LICENSE # GPLv3 license
├── README.md # This file
└── docs/ # Documentation
```
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
## License
This project is licensed under the GNU General Public License v3.0 (GPLv3).
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
See [LICENSE.md](LICENSE.md) for the full license text.
## Support
- **Issues**: Report bugs and request features on GitHub
- **Documentation**: See the [docs/](docs/) directory for detailed documentation
- **Community**: Join our community discussions
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for version history and changes.
\ No newline at end of file
#!/bin/bash
# Check if virtual environment exists, create if not
if [ ! -d "venv" ]; then
echo "Creating virtual environment..."
python3 -m venv venv
fi
# Activate virtual environment
. venv/bin/activate
# Install requirements
echo "Installing requirements..."
pip3 install -r requirements.txt
# Install pyinstaller if not already installed
pip3 install pyinstaller
# Create dist directory if not exists
mkdir -p dist
# Generate SSL certificates if they don't exist
if [ ! -f "cert.pem" ] || [ ! -f "key.pem" ]; then
echo "Generating SSL certificates..."
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
fi
# Build wssshd (server) binary with certificates and web assets
pyinstaller --onefile --distpath dist --add-data "cert.pem:." --add-data "key.pem:." --add-data "templates:templates" --add-data "static:static" --runtime-tmpdir /tmp --clean wssshd.py
# Build wssshc (client) binary
pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wssshc.py
# Build wsssh binary
pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wsssh.py
# Build wsscp binary
pyinstaller --onefile --distpath dist --runtime-tmpdir /tmp --clean wsscp.py
# Deactivate venv
deactivate
echo "Build complete. Binaries are in dist/ directory:"
echo "- dist/wssshd (server with web interface)"
echo "- dist/wssshc (client)"
echo "- dist/wsssh (SSH wrapper)"
echo "- dist/wsscp (SCP wrapper)"
\ No newline at end of file
-----BEGIN CERTIFICATE-----
MIIFjzCCA3egAwIBAgIUQFDaAf1+EIfkMETiI17s2FLbB7swDQYJKoZIhvcNAQEL
BQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVN0YXRlMQ0wCwYDVQQHDARDaXR5
MRUwEwYDVQQKDAxPcmdhbml6YXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0y
NTA5MTExNjM0MjdaFw0yNjA5MTExNjM0MjdaMFcxCzAJBgNVBAYTAlVTMQ4wDAYD
VQQIDAVTdGF0ZTENMAsGA1UEBwwEQ2l0eTEVMBMGA1UECgwMT3JnYW5pemF0aW9u
MRIwEAYDVQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK
AoICAQC4rfzwx9nCgRXyQCCdDTRjeBxOUezdR37zZfypVsoRbhdxA0k6dlnuWdhs
kCeZl9qvfbUcEvjylmQEKMDcf3GS1DpU25MDkAc52Tjx9jRITg8o4DpXAaLb9F+M
fYe9ANhFQx1KKoZn0JgyAHMqE818xanM3saKXp/NP1QZczb5dvbFGFK3knoAWHOU
skJgaAzRVBN7VKSq8M3lc+4cL6Dg3VbJjpq9qLEdNMlhsUfVM/nfFMQvLKIcLo6g
EcOdKsnGlEZnx+e1RfHiVpmEEM4MwVgr4uo6osAwTwMi94xXtPl6L9ulJrZOMWH5
H3CVadfvIAq7Mb44lDdIglapu4QsZAH53kJMU4HzZga7lfYTdJDyZLxEOt2DTcxd
5r8AU+WJw3DK5tN1AmIS2RdqA4NSLqcutrO3nPf6NFwEtVLpTMH8zP6hoBqB/91Q
cafYo2A3+uR+bWcDV9/fOPfGNcvRzWUSejYPgq0iD5AT8eN94LtGq7QYaQu/DJep
7Iz1EtV177Zoey1U+t91ePGhgeSuDhaNO23NXCjeSJUDmC2KBwELfRAbEbpU31cB
EOaljmuz2MP2pbCBWE/0YX0m0lPQqlPIXxG0ZxByBR1jZM8pgBNJNdwNKU7d0e+N
h/FAu9s6TKBGL4z9itt20mzgu1qshM7NL8rHeoe0p8Gj2LRGrQIDAQABo1MwUTAd
BgNVHQ4EFgQUDUnUTD1RyD1nmEnx8ANxCiKgGWowHwYDVR0jBBgwFoAUDUnUTD1R
yD1nmEnx8ANxCiKgGWowDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC
AgEAQGOwX9vnJS9RwyN4PELOHClIZU4GmxWNTbdRm51H8uJ6g7UTS1sqOprujHfr
3mi8PpAvNt/leWmerQ8p7iQcS+gRTaxd+qk/xReJqywRexZQXMduU+7vjOCqfy7f
cJZx20Snxu2T8tu8JpWfxQrM0BeJXimllIOUwyt4KC0Qz4zUhS1CPpYZGR+iLeJB
A1dykzWcDDEYHbJIMVHD0mC/2qIKvPpZXQKQNvTdQK+T7jc1LG3QZ4873bLQ/p9L
o5tLFHmLiwrHJi9Ox1rQEopttwM7x3vGah8MRHcedw2sNjiPqUMXFWOtwtrdoQkv
rgzZh/IsnY22XOAHpP3UaJw8r4UvMjEz5daH4V0EBq0hij4NhrRc3l+Vgzc+Aoom
wDvdi/ptuxzygWPITIvLxWfm6JkiHQzVLXWqBGVNE3GPWNMPgyEEXkENjthtgEfx
B88PNIZdBy33FOdXBlfww2NvpnKe++Crx3pGaus7w35c9PbB/Gk/2qGY9tgTzXC1
qa8V1eqg3HBss4f6VbBfY5QGV28eDttdFHwuIrNromTe9l9dUzxdvM/FPfxEtZ+y
bYJ7EARFQNR0WjaeEb0njZC2u2QsGiX7vT0II+Wu/ZrHSP7yoDnsaNzSWO+C2tpc
7vXS5+GazhAIscBzp5KRoJs6X5DRX6Y6yKYaiVwDOzs4Q9k=
-----END CERTIFICATE-----
#!/bin/bash
# Remove PyInstaller build artifacts
rm -rf build/
rm -rf dist/
rm -f *.spec
# Optionally remove SSL certificates (uncomment if needed)
# rm -f cert.pem key.pem
echo "Clean complete. Build artifacts removed."
echo "Note: SSL certificates (cert.pem, key.pem) preserved. Uncomment lines in clean.sh to remove them."
\ No newline at end of file
-----BEGIN PRIVATE KEY-----
MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQC4rfzwx9nCgRXy
QCCdDTRjeBxOUezdR37zZfypVsoRbhdxA0k6dlnuWdhskCeZl9qvfbUcEvjylmQE
KMDcf3GS1DpU25MDkAc52Tjx9jRITg8o4DpXAaLb9F+MfYe9ANhFQx1KKoZn0Jgy
AHMqE818xanM3saKXp/NP1QZczb5dvbFGFK3knoAWHOUskJgaAzRVBN7VKSq8M3l
c+4cL6Dg3VbJjpq9qLEdNMlhsUfVM/nfFMQvLKIcLo6gEcOdKsnGlEZnx+e1RfHi
VpmEEM4MwVgr4uo6osAwTwMi94xXtPl6L9ulJrZOMWH5H3CVadfvIAq7Mb44lDdI
glapu4QsZAH53kJMU4HzZga7lfYTdJDyZLxEOt2DTcxd5r8AU+WJw3DK5tN1AmIS
2RdqA4NSLqcutrO3nPf6NFwEtVLpTMH8zP6hoBqB/91QcafYo2A3+uR+bWcDV9/f
OPfGNcvRzWUSejYPgq0iD5AT8eN94LtGq7QYaQu/DJep7Iz1EtV177Zoey1U+t91
ePGhgeSuDhaNO23NXCjeSJUDmC2KBwELfRAbEbpU31cBEOaljmuz2MP2pbCBWE/0
YX0m0lPQqlPIXxG0ZxByBR1jZM8pgBNJNdwNKU7d0e+Nh/FAu9s6TKBGL4z9itt2
0mzgu1qshM7NL8rHeoe0p8Gj2LRGrQIDAQABAoICAAKbPN61W1oyCOfmasrYEF1J
luL3OgfHc8AByq+3tREUVi6AEAPebHLtEh06H+POr3w2IsFtmtVqNPJwFIS6bSeO
1ssOOfsmP3BuWncs4rfeO9/S4b2dU/CVL2jj0zj0br2GXHWtSdK/Zx56riVoqkf5
vC6uqDTQJuvtIzykbbNEC3rSMkXNsDPRMFRnsjexq6rs7A5Sm/5V5rDcG8gcxNOO
d5IGOiJsY7QYdh9qoFAexpkU5QTG2dcjjVucQkkjM9A+AsLvfBubDAiqp8okAbfh
XdD7mjf0D6MIC5U3QL9ytXwU59RQynrhB/gpClw5eIugxX8ksaZcV2335zsRTIAm
BSUksC+gWiOUcOdJkuhg2BsVnBLMGdwBfLo4IFrSZD/YuDukkAbHioP3OIlk3qYl
YlNLixMuLBceBWIXK1tSwYBx0zzY+8mZBhToiNOKwEKuC9604Z9/rDemqAue+vYd
BEiU97288HUHAZnmDmgWQoZkba3geNFKuDRA0WDh/sWdlLpP/y9bvbZ3jVUoqAF2
xMw8ZIq6SE5uqzyaa6O0v7XoTmpS0ByL/dT3fzyIs9eQhMOFH1WLTZ+SgaSv0yGb
jsUPSHajUvxEFmW0nmY0Ws+aSHuwK61hEgleXNbHcHVyB6PmyACU6GGF1+B0Lzfp
+boyr8zDrB48UjxAmTchAoIBAQDm7VcdG2Hf1clROZ1+3WOm0Cl77kotwXaI0sKq
CSZu0tPg625VC1Tlzggr4ALyVIvY9N6gFmP9zxEDBF+u8r9UH5Wdw3K+BWxNCCew
4oFxo0CHggcFcs1Z/mF8psRjcYTilVdyFo1z07aaMZzi2ulGSY0erI4yMrY0i8cR
ds09y/bM/f/eWC9uS1fGMxQwcaE0M4iWSsHhDOAwbuyjbyZTtnsMeIgZYYTtB+DL
DkFSgk5dZMyJ4+b1Y/auxI3XnJSAdBVLXzjaNLfID57Rim6V4mxaIRTpD3Fw5cob
kKCLHp+3AYL9AwRt7CmXIVvtrCxuIEFq2+QOu8A+djkH6/adAoIBAQDMuzDyK1EG
8aJ/RD8w9fHODdP13kr69P6d+82SeKhxBiZnWjjm4jnQQ5ijT6DhXgU2qm8z8xDj
qqPFCvxah+I3CXeaE45ZktaQ+f1OZYPBAXfy8h+T/TMpbu8cdlW81w/aqxHZyry5
fQE+v7Mns256/7qrwHY5gKE4RHmdXj2D4OXwqrfEsHlfwqfvVcrdZPDXICpBATR+
H+03u9mlTO9JaDwtDEd8IY4GaLhFeQNb2sWaHzLCf+Ox0QojEqe3fT+6qaffYTX1
tAtQdk8UGXaZU+0ulPXQ9fv6ZYMt7SFohVHVoYydYday5kk8QID4jemB1b27U1pD
9BLQe0eNdItRAoIBAH+BaOo/ZklLJ79biqSz5QQESAOPzRF6ktJ1XNq59qiWbDry
g5cdjKDepBBlvfrDx/vhKNNHyaoonQIHdjWI/y+ZyOi1NDPLlsLpz9CRIFv4gfbQ
SsQtYUlhdb537lPiKDdbsk7iOPRNX7O/1RpFOSyADBV1vYXmDkjxLNdtu2F1ry38
yTyhgH7rxuk+5tTgyNuj4LTrTiXPEDJt7OdIxebPCR4Xpz4sZFLkWLCFjHfcTxyu
PWmdlrbDnT9ec9srL6vFbMSTLTb+iMNELLMSNoE35g/V2E/fIQnvNysFLj/ihtlr
UkIVWmq/TS+PUcznlhiwYq53/3JLJJjYeiDvntkCggEBAIA1RZySFcbkcR+DzJLL
oiaosDELiScJX53tvznXh5xn/orAjFvCFfRfMGotBpG7gEZQix0cPVplVPOjQo8r
AzX2HskFMCLV+rqFYuTCW7T1R3mDuNTDPlPXHbRUQrLkdxA4CxC5jmAWcT4rbHUT
P7+VAABooWC3Nb732rT6/EjnAPgq4LQy039tdh9COa1VdiEyCmP07juBoNtDLzP+
LudoeC65vtZ0aO2IjMUs2DaglRhEK1R0JFIJl3CJUTBuJgeuEOupg9IfcuprfHAY
1hWE4kZGkH3QXYDcKz8Kfd5nhuziox031Ozpm7k4p8t/i1h8UrnJpABkC5g1a4Sh
FFECggEABgo/X6P04AMBubewAzbUy+2s16LsWnRDIc2QxJjR+scmF2fiARJ5PrEP
ZDmqOT9dK9uopUw839C7uytCGBIqyV54NNUj7CuwwT4tkxn2LPdM+7WD0t8wyWw3
zDT6FfJHRmr7qFqPkasPiBizT+t8dXzrdCxlT68+E59MQdzAaHlNdaio16ALMHwW
vLdFndKU5qLkPHZzpsuShJvQSbQ0czj5I1sERxyE4ZRbL2ueReDCoR+ou+O3+TTN
sUGMa+dHsJFeT8LHVLMnD5xw+Jjmaf7MjeNchfJl0Kmm8Z4d1uFd/LicEBG8J2BB
zHTicyzq+uuJYB+ORdwQGoOh9ktNAQ==
-----END PRIVATE KEY-----
websockets>=15.0
paramiko>=4.0
flask>=3.1
flask-login>=0.6
flask-sqlalchemy>=3.1
werkzeug>=3.1
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}WebSocket SSH Daemon{% endblock %}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
.navbar-brand {
font-weight: bold;
}
.client-card {
transition: transform 0.2s;
}
.client-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.terminal-container {
background-color: #1e1e1e;
color: #f8f8f2;
font-family: 'Courier New', monospace;
padding: 20px;
border-radius: 8px;
height: 600px;
overflow-y: auto;
}
.terminal-input {
background: transparent;
border: none;
color: #f8f8f2;
font-family: 'Courier New', monospace;
width: 100%;
outline: none;
}
.terminal-input:focus {
box-shadow: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container">
<a class="navbar-brand" href="#">
<i class="fas fa-terminal"></i> WebSocket SSH Daemon
</a>
<div class="navbar-nav ms-auto">
{% if current_user.is_authenticated %}
<span class="navbar-text me-3">
Welcome, {{ current_user.username }}!
</span>
<a class="nav-link" href="{{ url_for('logout') }}">
<i class="fas fa-sign-out-alt"></i> Logout
</a>
{% endif %}
</div>
</div>
</nav>
<div class="container mt-4">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'info' }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
{% block scripts %}{% endblock %}
</body>
</html>
\ No newline at end of file
{% extends "base.html" %}
{% block title %}Dashboard - WebSocket SSH Daemon{% endblock %}
{% block content %}
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3 class="card-title mb-0">
<i class="fas fa-server"></i> Connected Clients
</h3>
</div>
<div class="card-body">
{% if clients %}
<div class="row">
{% for client in clients %}
<div class="col-md-4 mb-3">
<div class="card client-card h-100">
<div class="card-body text-center">
<i class="fas fa-desktop fa-3x text-success mb-3"></i>
<h5 class="card-title">{{ client }}</h5>
<p class="card-text text-muted">Connected</p>
<a href="{{ url_for('terminal', client_id=client) }}" class="btn btn-primary">
<i class="fas fa-terminal"></i> Connect
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="text-center py-5">
<i class="fas fa-server fa-4x text-muted mb-3"></i>
<h4 class="text-muted">No clients connected</h4>
<p class="text-muted">Clients will appear here when they connect to the daemon.</p>
</div>
{% endif %}
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h3 class="card-title mb-0">
<i class="fas fa-cogs"></i> Quick Actions
</h3>
</div>
<div class="card-body">
{% if current_user.is_admin %}
<a href="{{ url_for('users') }}" class="btn btn-outline-primary btn-sm mb-2 w-100">
<i class="fas fa-users"></i> Manage Users
</a>
{% endif %}
<button class="btn btn-outline-secondary btn-sm w-100" onclick="location.reload()">
<i class="fas fa-sync"></i> Refresh Status
</button>
</div>
</div>
<div class="card mt-3">
<div class="card-header">
<h3 class="card-title mb-0">
<i class="fas fa-info-circle"></i> System Info
</h3>
</div>
<div class="card-body">
<p class="mb-1"><strong>WebSocket Port:</strong> {{ config.WEBSOCKET_PORT or 'N/A' }}</p>
<p class="mb-1"><strong>Domain:</strong> {{ config.DOMAIN or 'N/A' }}</p>
<p class="mb-0"><strong>Connected Clients:</strong> {{ clients|length }}</p>
</div>
</div>
</div>
</div>
{% endblock %}
\ No newline at end of file
{% extends "base.html" %}
{% block title %}Login - WebSocket SSH Daemon{% endblock %}
{% block content %}
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3 class="card-title mb-0"><i class="fas fa-sign-in-alt"></i> Login</h3>
</div>
<div class="card-body">
<form method="post">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-sign-in-alt"></i> Login
</button>
</form>
<div class="mt-3">
<small class="text-muted">
Default credentials: admin / admin123
</small>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
\ No newline at end of file
{% extends "base.html" %}
{% block title %}Terminal - {{ client_id }}{% endblock %}
{% block content %}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h3 class="card-title mb-0">
<i class="fas fa-terminal"></i> SSH Terminal - {{ client_id }}
</h3>
<div>
<input type="text" id="sshUsername" class="form-control form-control-sm d-inline-block w-auto me-2" placeholder="Username" value="root">
<button id="connectBtn" class="btn btn-success btn-sm">
<i class="fas fa-play"></i> Connect
</button>
<button id="disconnectBtn" class="btn btn-danger btn-sm" disabled>
<i class="fas fa-stop"></i> Disconnect
</button>
</div>
</div>
<div class="card-body p-0">
<div id="terminal" class="terminal-container">
<div id="output"></div>
<div class="input-group">
<span class="text-success me-2">$</span>
<input type="text" id="commandInput" class="terminal-input" placeholder="Type your command..." disabled>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
let ws = null;
let connected = false;
document.getElementById('connectBtn').addEventListener('click', connect);
document.getElementById('disconnectBtn').addEventListener('click', disconnect);
document.getElementById('commandInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendCommand();
}
});
function connect() {
const username = document.getElementById('sshUsername').value;
if (!username) {
alert('Please enter a username');
return;
}
// For demo purposes, we'll simulate the connection
// In a real implementation, this would use WebSocket to communicate with wsssh
connected = true;
document.getElementById('connectBtn').disabled = true;
document.getElementById('disconnectBtn').disabled = false;
document.getElementById('commandInput').disabled = false;
document.getElementById('sshUsername').disabled = true;
appendOutput(`Connecting to ${username}@{{ client_id }}...`);
setTimeout(() => {
appendOutput(`Connected successfully!`);
appendOutput(`Welcome to {{ client_id }}`);
appendOutput(`$ `);
}, 1000);
}
function disconnect() {
connected = false;
document.getElementById('connectBtn').disabled = false;
document.getElementById('disconnectBtn').disabled = true;
document.getElementById('commandInput').disabled = true;
document.getElementById('sshUsername').disabled = false;
appendOutput('Disconnected.');
}
function sendCommand() {
if (!connected) return;
const input = document.getElementById('commandInput');
const command = input.value.trim();
if (!command) return;
appendOutput(`$ ${command}`);
// Simulate command execution
setTimeout(() => {
if (command === 'ls') {
appendOutput(`Desktop Documents Downloads Music Pictures Videos`);
} else if (command === 'pwd') {
appendOutput(`/home/${document.getElementById('sshUsername').value}`);
} else if (command === 'whoami') {
appendOutput(document.getElementById('sshUsername').value);
} else if (command === 'exit' || command === 'logout') {
disconnect();
return;
} else {
appendOutput(`Command not found: ${command}`);
}
appendOutput(`$ `);
}, 500);
input.value = '';
}
function appendOutput(text) {
const output = document.getElementById('output');
const line = document.createElement('div');
line.textContent = text;
output.appendChild(line);
output.scrollTop = output.scrollHeight;
}
// Focus on command input when connected
document.addEventListener('keydown', function(e) {
if (connected && e.target.tagName !== 'INPUT') {
document.getElementById('commandInput').focus();
}
});
</script>
{% endblock %}
\ No newline at end of file
{% extends "base.html" %}
{% block title %}User Management - WebSocket SSH Daemon{% endblock %}
{% block content %}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h3 class="card-title mb-0">
<i class="fas fa-users"></i> User Management
</h3>
<button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal">
<i class="fas fa-plus"></i> Add User
</button>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.username }}</td>
<td>
{% if user.is_admin %}
<span class="badge bg-danger">Admin</span>
{% else %}
<span class="badge bg-secondary">User</span>
{% endif %}
</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="editUser({{ user.id }}, '{{ user.username }}', {{ user.is_admin|lower }})">
<i class="fas fa-edit"></i> Edit
</button>
{% if user.username != current_user.username %}
<button class="btn btn-sm btn-outline-danger" onclick="deleteUser({{ user.id }}, '{{ user.username }}')">
<i class="fas fa-trash"></i> Delete
</button>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<form id="addUserForm">
<div class="modal-body">
<div class="mb-3">
<label for="addUsername" class="form-label">Username</label>
<input type="text" class="form-control" id="addUsername" name="username" required>
</div>
<div class="mb-3">
<label for="addPassword" class="form-label">Password</label>
<input type="password" class="form-control" id="addPassword" name="password" required>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="addIsAdmin" name="is_admin">
<label class="form-check-label" for="addIsAdmin">Administrator</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Add User</button>
</div>
</form>
</div>
</div>
</div>
<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<form id="editUserForm">
<input type="hidden" id="editUserId" name="user_id">
<div class="modal-body">
<div class="mb-3">
<label for="editUsername" class="form-label">Username</label>
<input type="text" class="form-control" id="editUsername" name="username" required>
</div>
<div class="mb-3">
<label for="editPassword" class="form-label">New Password (leave empty to keep current)</label>
<input type="password" class="form-control" id="editPassword" name="password">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="editIsAdmin" name="is_admin">
<label class="form-check-label" for="editIsAdmin">Administrator</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Update User</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
function editUser(userId, username, isAdmin) {
document.getElementById('editUserId').value = userId;
document.getElementById('editUsername').value = username;
document.getElementById('editPassword').value = '';
document.getElementById('editIsAdmin').checked = isAdmin;
new bootstrap.Modal(document.getElementById('editUserModal')).show();
}
function deleteUser(userId, username) {
if (confirm(`Are you sure you want to delete user "${username}"?`)) {
fetch(`/delete_user/${userId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
location.reload();
} else {
alert('Error: ' + data.error);
}
});
}
}
document.getElementById('addUserForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
fetch('/add_user', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
location.reload();
} else {
alert('Error: ' + data.error);
}
});
});
document.getElementById('editUserForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const userId = document.getElementById('editUserId').value;
fetch(`/edit_user/${userId}`, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
location.reload();
} else {
alert('Error: ' + data.error);
}
});
});
</script>
{% endblock %}
\ No newline at end of file
#!/usr/bin/env python3
"""
WebSocket SCP (wsscp)
SCP wrapper that uses WebSocket tunnels through wssshd.
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import asyncio
import ssl
import websockets
import json
import socket
import subprocess
import sys
import uuid
debug = False
async def handle_tunnel(ws, local_port, request_id):
"""Handle tunnel data forwarding"""
try:
# Open local TCP listener
server = await asyncio.start_server(
lambda r, w: handle_local_connection(r, w, ws, request_id),
'localhost', local_port
)
if debug: print(f"[DEBUG] Listening on localhost:{local_port}")
async with server:
await server.serve_forever()
except Exception as e:
if debug: print(f"[DEBUG] Tunnel handler error: {e}")
async def handle_local_connection(reader, writer, ws, request_id):
"""Handle connections from local SCP client"""
try:
# Forward data between local connection and WebSocket
async def forward_to_ws():
try:
while True:
data = await reader.read(1024)
if not data:
break
await ws.send(json.dumps({
"type": "tunnel_data",
"request_id": request_id,
"data": data.hex() # Use hex encoding for binary data
}))
except Exception as e:
if debug: print(f"[DEBUG] Local to WS error: {e}")
async def forward_from_ws():
try:
async for message in ws:
data = json.loads(message)
if data.get('type') == 'tunnel_data' and data.get('request_id') == request_id:
# Decode and forward data
tunnel_data = bytes.fromhex(data['data'])
writer.write(tunnel_data)
await writer.drain()
elif data.get('type') == 'tunnel_close' and data.get('request_id') == request_id:
break
except Exception as e:
if debug: print(f"[DEBUG] WS to local error: {e}")
await asyncio.gather(forward_to_ws(), forward_from_ws())
except Exception as e:
if debug: print(f"[DEBUG] Local connection error: {e}")
finally:
writer.close()
await writer.wait_closed()
async def run_scp(server_ip, server_port, client_id, local_port, scp_args):
"""Connect to wssshd and run SCP"""
uri = f"wss://{server_ip}:{server_port}"
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
request_id = str(uuid.uuid4())
try:
async with websockets.connect(uri, ssl=ssl_context) as websocket:
# Request tunnel
await websocket.send(json.dumps({
"type": "tunnel_request",
"client_id": client_id,
"request_id": request_id
}))
# Wait for acknowledgment
response = await websocket.recv()
data = json.loads(response)
if data.get('type') == 'tunnel_ack':
if debug: print(f"[DEBUG] Tunnel request acknowledged: {request_id}")
# Start tunnel handler
tunnel_task = asyncio.create_task(handle_tunnel(websocket, local_port, request_id))
# Launch SCP with modified arguments
scp_cmd = ['scp'] + scp_args + ['-P', str(local_port)]
if debug: print(f"[DEBUG] Launching: {' '.join(scp_cmd)}")
# Run SCP process
process = await asyncio.create_subprocess_exec(
*scp_cmd,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr
)
# Wait for SCP to complete
await process.wait()
# Close tunnel
await websocket.send(json.dumps({
"type": "tunnel_close",
"request_id": request_id
}))
tunnel_task.cancel()
elif data.get('type') == 'tunnel_error':
print(f"Error: {data.get('error', 'Unknown error')}")
return 1
except Exception as e:
print(f"Connection failed: {e}")
return 1
return 0
def parse_hostname(hostname):
"""Parse hostname to extract CLIENT_ID and WSSSHD_HOST"""
# Split by dots to get client_id and wssshd_host
parts = hostname.split('.')
if len(parts) >= 2:
client_id = parts[0]
wssshd_host = '.'.join(parts[1:])
else:
# No domain, assume whole hostname is client_id
client_id = hostname
wssshd_host = 'localhost' # Default fallback
return client_id, wssshd_host
def main():
parser = argparse.ArgumentParser(description='WebSocket SCP (wsscp)', add_help=False)
parser.add_argument('--local-port', type=int, default=0, help='Local port for tunnel (0 = auto)')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
# Parse our arguments first
args, remaining = parser.parse_known_args()
global debug
debug = args.debug
# Find host arguments and -P port option in remaining args (SCP can have multiple host:paths)
hosts = []
scp_port = None
for i, arg in enumerate(remaining):
if arg == '-P' and i + 1 < len(remaining):
try:
scp_port = int(remaining[i + 1])
except ValueError:
pass
elif not arg.startswith('-') and ':' in arg:
# Extract host from host:path format
host_part = arg.split(':', 1)[0]
if '@' in host_part:
host = host_part.split('@', 1)[1]
else:
host = host_part
hosts.append(host)
if not hosts:
print("Error: Could not determine target host(s)")
sys.exit(1)
if not scp_port:
print("Error: Could not determine wssshd port from -P option")
sys.exit(1)
# Use the first host for parsing
host = hosts[0]
# Parse hostname to extract client_id and wssshd_host
client_id, wssshd_host = parse_hostname(host)
if debug:
print(f"[DEBUG] Hosts: {hosts}")
print(f"[DEBUG] Client ID: {client_id}")
print(f"[DEBUG] WSSSHD Host: {wssshd_host}")
print(f"[DEBUG] WSSSHD Port: {scp_port}")
# Find available local port
if args.local_port == 0:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 0))
local_port = s.getsockname()[1]
else:
local_port = args.local_port
if debug: print(f"[DEBUG] Using local port: {local_port}")
# Modify remaining args to use localhost:local_port
modified_args = []
for arg in remaining:
if ':' in arg:
host_part, path_part = arg.split(':', 1)
if '@' in host_part:
user, host_in_arg = host_part.split('@', 1)
if host_in_arg == host: # Only modify the first host
modified_args.append(f"{user}@localhost:{path_part}")
else:
modified_args.append(arg)
else:
if host_part == host: # Only modify the first host
modified_args.append(f"localhost:{path_part}")
else:
modified_args.append(arg)
else:
modified_args.append(arg)
# Add port argument for local tunnel
modified_args.extend(['-P', str(local_port)])
if debug: print(f"[DEBUG] Modified SCP args: {modified_args}")
# Run the async SCP wrapper
exit_code = asyncio.run(run_scp(
wssshd_host, # Use parsed wssshd_host as server_ip
scp_port, # Use -P port as wssshd_port
client_id,
local_port,
modified_args
))
sys.exit(exit_code)
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
"""
WebSocket SSH (wsssh)
SSH wrapper that uses WebSocket tunnels through wssshd.
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import asyncio
import ssl
import websockets
import json
import socket
import subprocess
import sys
import uuid
debug = False
async def handle_tunnel(ws, local_port, request_id):
"""Handle tunnel data forwarding"""
try:
# Open local TCP listener
server = await asyncio.start_server(
lambda r, w: handle_local_connection(r, w, ws, request_id),
'localhost', local_port
)
if debug: print(f"[DEBUG] Listening on localhost:{local_port}")
async with server:
await server.serve_forever()
except Exception as e:
if debug: print(f"[DEBUG] Tunnel handler error: {e}")
async def handle_local_connection(reader, writer, ws, request_id):
"""Handle connections from local SSH client"""
try:
# Forward data between local connection and WebSocket
async def forward_to_ws():
try:
while True:
data = await reader.read(1024)
if not data:
break
await ws.send(json.dumps({
"type": "tunnel_data",
"request_id": request_id,
"data": data.hex() # Use hex encoding for binary data
}))
except Exception as e:
if debug: print(f"[DEBUG] Local to WS error: {e}")
async def forward_from_ws():
try:
async for message in ws:
data = json.loads(message)
if data.get('type') == 'tunnel_data' and data.get('request_id') == request_id:
# Decode and forward data
tunnel_data = bytes.fromhex(data['data'])
writer.write(tunnel_data)
await writer.drain()
elif data.get('type') == 'tunnel_close' and data.get('request_id') == request_id:
break
except Exception as e:
if debug: print(f"[DEBUG] WS to local error: {e}")
await asyncio.gather(forward_to_ws(), forward_from_ws())
except Exception as e:
if debug: print(f"[DEBUG] Local connection error: {e}")
finally:
writer.close()
await writer.wait_closed()
async def run_ssh(server_ip, server_port, client_id, local_port, ssh_args):
"""Connect to wssshd and run SSH"""
uri = f"wss://{server_ip}:{server_port}"
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
request_id = str(uuid.uuid4())
try:
async with websockets.connect(uri, ssl=ssl_context) as websocket:
# Request tunnel
await websocket.send(json.dumps({
"type": "tunnel_request",
"client_id": client_id,
"request_id": request_id
}))
# Wait for acknowledgment
response = await websocket.recv()
data = json.loads(response)
if data.get('type') == 'tunnel_ack':
if debug: print(f"[DEBUG] Tunnel request acknowledged: {request_id}")
# Start tunnel handler
tunnel_task = asyncio.create_task(handle_tunnel(websocket, local_port, request_id))
# Launch SSH with modified arguments
ssh_cmd = ['ssh'] + ssh_args + ['-p', str(local_port), 'localhost']
if debug: print(f"[DEBUG] Launching: {' '.join(ssh_cmd)}")
# Run SSH process
process = await asyncio.create_subprocess_exec(
*ssh_cmd,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr
)
# Wait for SSH to complete
await process.wait()
# Close tunnel
await websocket.send(json.dumps({
"type": "tunnel_close",
"request_id": request_id
}))
tunnel_task.cancel()
elif data.get('type') == 'tunnel_error':
print(f"Error: {data.get('error', 'Unknown error')}")
return 1
except Exception as e:
print(f"Connection failed: {e}")
return 1
return 0
def parse_hostname(hostname):
"""Parse hostname to extract CLIENT_ID and WSSSHD_HOST"""
# Split by dots to get client_id and wssshd_host
parts = hostname.split('.')
if len(parts) >= 2:
client_id = parts[0]
wssshd_host = '.'.join(parts[1:])
else:
# No domain, assume whole hostname is client_id
client_id = hostname
wssshd_host = 'localhost' # Default fallback
return client_id, wssshd_host
def main():
parser = argparse.ArgumentParser(description='WebSocket SSH (wsssh)', add_help=False)
parser.add_argument('--local-port', type=int, default=0, help='Local port for tunnel (0 = auto)')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
# Parse our arguments first
args, remaining = parser.parse_known_args()
global debug
debug = args.debug
# Find the host argument and -p port option in remaining args
host = None
ssh_port = None
for i, arg in enumerate(remaining):
if arg == '-p' and i + 1 < len(remaining):
try:
ssh_port = int(remaining[i + 1])
except ValueError:
pass
elif not arg.startswith('-') and i > 0 and remaining[i-1] in ['-h', '--host']:
host = arg
break
elif not arg.startswith('-') and '@' in arg:
# Handle user@host format
host = arg.split('@', 1)[1]
break
elif not arg.startswith('-') and i == 0:
# First non-option argument might be host
host = arg
break
if not host:
print("Error: Could not determine target host")
sys.exit(1)
if not ssh_port:
print("Error: Could not determine wssshd port from -p option")
sys.exit(1)
# Parse hostname to extract client_id and wssshd_host
client_id, wssshd_host = parse_hostname(host)
if debug:
print(f"[DEBUG] Host: {host}")
print(f"[DEBUG] Client ID: {client_id}")
print(f"[DEBUG] WSSSHD Host: {wssshd_host}")
print(f"[DEBUG] WSSSHD Port: {ssh_port}")
# Find available local port
if args.local_port == 0:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 0))
local_port = s.getsockname()[1]
else:
local_port = args.local_port
if debug: print(f"[DEBUG] Using local port: {local_port}")
# Modify remaining args to use localhost:local_port
modified_args = []
skip_next = False
for i, arg in enumerate(remaining):
if skip_next:
skip_next = False
continue
if arg in ['-h', '--host', '-p', '--port']:
skip_next = True
continue
elif '@' in arg and arg.split('@', 1)[1] == host:
# Replace user@host with user@localhost
user = arg.split('@', 1)[0]
modified_args.append(f"{user}@localhost")
continue
elif arg == host:
modified_args.append('localhost')
continue
else:
modified_args.append(arg)
# Add port argument for local tunnel
modified_args.extend(['-p', str(local_port)])
if debug: print(f"[DEBUG] Modified SSH args: {modified_args}")
# Run the async SSH wrapper
exit_code = asyncio.run(run_ssh(
wssshd_host, # Use parsed wssshd_host as server_ip
ssh_port, # Use -p port as wssshd_port
client_id,
local_port,
modified_args
))
sys.exit(exit_code)
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
"""
WebSocket SSH Client (wssshc)
Connects to wssshd server and registers as a client.
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import asyncio
import ssl
import websockets
import json
debug = False
async def connect_to_server(server_ip, port, client_id, password, interval):
uri = f"wss://{server_ip}:{port}"
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
while True:
try:
async with websockets.connect(uri, ssl=ssl_context) as websocket:
# Register
await websocket.send(json.dumps({"type": "register", "id": client_id, "password": password}))
print(f"Connected and registered as {client_id}")
# Wait for registration acknowledgment
response = await websocket.recv()
data = json.loads(response)
if data.get('type') == 'registered':
print(f"Successfully registered as {client_id}")
elif data.get('type') == 'registration_error':
print(f"Registration failed: {data.get('error', 'Unknown error')}")
return # Exit and retry
async for message in websocket:
if debug: print(f"[DEBUG] WebSocket message: {message[:100]}...")
data = json.loads(message)
if data.get('type') == 'tunnel_request':
print(f"Tunnel request received: {data['request_id']}")
# Client would handle tunnel setup here
elif data.get('type') == 'tunnel_data':
print(f"Tunnel data received: {len(data.get('data', ''))} bytes")
# Client would forward data here
elif data.get('type') == 'tunnel_close':
print(f"Tunnel closed: {data['request_id']}")
# Client would close tunnel here
except Exception as e:
print(f"Connection failed: {e}, retrying in {interval} seconds")
await asyncio.sleep(interval)
def main():
parser = argparse.ArgumentParser(description='WebSocket SSH Client (wssshc)')
parser.add_argument('--server-ip', required=True, help='Server IP address')
parser.add_argument('--port', type=int, required=True, help='Server port')
parser.add_argument('--id', required=True, help='Client ID')
parser.add_argument('--password', required=True, help='Registration password')
parser.add_argument('--interval', type=int, default=30, help='Reconnect interval in seconds (default: 30)')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
args = parser.parse_args()
global debug
debug = args.debug
asyncio.run(connect_to_server(args.server_ip, args.port, args.id, args.password, args.interval))
if __name__ == '__main__':
main()
\ No newline at end of file
#!/usr/bin/env python3
"""
WebSocket SSH Daemon (wssshd)
Handles WebSocket connections from clients and wsssh/wsscp applications.
Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import asyncio
import ssl
import websockets
import json
import sys
import os
import threading
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
# Client registry: id -> websocket
clients = {}
debug = False
server_password = None
# Flask app for web interface
app = Flask(__name__)
app.config['SECRET_KEY'] = 'wsssh-secret-key-change-in-production'
config_dir = os.path.expanduser('~/.config/wssshd')
os.makedirs(config_dir, exist_ok=True)
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{config_dir}/users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
password_hash = db.Column(db.String(150), nullable=False)
is_admin = db.Column(db.Boolean, default=False)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Create database and default admin user
with app.app_context():
db.create_all()
if not User.query.filter_by(username='admin').first():
admin = User(username='admin', password_hash=generate_password_hash('admin123'), is_admin=True)
db.session.add(admin)
db.session.commit()
# Flask routes
@app.route('/')
@login_required
def index():
return render_template('index.html', clients=list(clients.keys()))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user and check_password_hash(user.password_hash, password):
login_user(user)
return redirect(url_for('index'))
flash('Invalid username or password')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/users')
@login_required
def users():
if not current_user.is_admin:
flash('Access denied')
return redirect(url_for('index'))
users = User.query.all()
return render_template('users.html', users=users)
@app.route('/add_user', methods=['POST'])
@login_required
def add_user():
if not current_user.is_admin:
return jsonify({'error': 'Access denied'}), 403
username = request.form.get('username')
password = request.form.get('password')
is_admin = request.form.get('is_admin') == 'on'
if User.query.filter_by(username=username).first():
return jsonify({'error': 'Username already exists'}), 400
user = User(username=username, password_hash=generate_password_hash(password), is_admin=is_admin)
db.session.add(user)
db.session.commit()
return jsonify({'success': True})
@app.route('/edit_user/<int:user_id>', methods=['POST'])
@login_required
def edit_user(user_id):
if not current_user.is_admin:
return jsonify({'error': 'Access denied'}), 403
user = User.query.get_or_404(user_id)
user.username = request.form.get('username')
user.is_admin = request.form.get('is_admin') == 'on'
password = request.form.get('password')
if password:
user.password_hash = generate_password_hash(password)
db.session.commit()
return jsonify({'success': True})
@app.route('/delete_user/<int:user_id>', methods=['POST'])
@login_required
def delete_user(user_id):
if not current_user.is_admin:
return jsonify({'error': 'Access denied'}), 403
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return jsonify({'success': True})
@app.route('/terminal/<client_id>')
@login_required
def terminal(client_id):
if client_id not in clients:
flash('Client not connected')
return redirect(url_for('index'))
return render_template('terminal.html', client_id=client_id)
async def handle_websocket(websocket, path=None):
try:
async for message in websocket:
if debug: print(f"[DEBUG] WebSocket message received: {message[:100]}...")
data = json.loads(message)
if data.get('type') == 'register':
client_id = data['id']
client_password = data.get('password', '')
if client_password == server_password:
clients[client_id] = websocket
print(f"Client {client_id} registered")
await websocket.send(json.dumps({"type": "registered", "id": client_id}))
else:
print(f"Client {client_id} registration failed: invalid password")
await websocket.send(json.dumps({"type": "registration_error", "error": "Invalid password"}))
elif data.get('type') == 'tunnel_request':
client_id = data['client_id']
if client_id in clients:
# Forward tunnel request to client
await clients[client_id].send(json.dumps({
"type": "tunnel_request",
"request_id": data['request_id']
}))
await websocket.send(json.dumps({
"type": "tunnel_ack",
"request_id": data['request_id']
}))
else:
await websocket.send(json.dumps({
"type": "tunnel_error",
"request_id": data['request_id'],
"error": "Client not registered"
}))
elif data.get('type') == 'tunnel_data':
# Forward tunnel data to appropriate client
client_id = data.get('client_id')
if client_id and client_id in clients:
await clients[client_id].send(json.dumps({
"type": "tunnel_data",
"request_id": data['request_id'],
"data": data['data']
}))
elif data.get('type') == 'tunnel_close':
client_id = data.get('client_id')
if client_id and client_id in clients:
await clients[client_id].send(json.dumps({
"type": "tunnel_close",
"request_id": data['request_id']
}))
except websockets.exceptions.ConnectionClosed:
# Remove from registry
for cid, ws in clients.items():
if ws == websocket:
del clients[cid]
print(f"Client {cid} disconnected")
break
async def main():
parser = argparse.ArgumentParser(description='WebSocket SSH Daemon (wssshd)')
parser.add_argument('--host', required=True, help='WebSocket server host')
parser.add_argument('--port', type=int, required=True, help='WebSocket server port')
parser.add_argument('--domain', required=True, help='Base domain name')
parser.add_argument('--password', required=True, help='Registration password')
parser.add_argument('--web-host', help='Web interface host (optional)')
parser.add_argument('--web-port', type=int, help='Web interface port (optional)')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
args = parser.parse_args()
global debug
debug = args.debug
global server_password
server_password = args.password
# Load certificate
if getattr(sys, 'frozen', False):
# Running as bundled executable
bundle_dir = sys._MEIPASS
cert_path = os.path.join(bundle_dir, 'cert.pem')
key_path = os.path.join(bundle_dir, 'key.pem')
else:
# Running as script
cert_path = 'cert.pem'
key_path = 'key.pem'
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(cert_path, key_path)
# Start WebSocket server
ws_server = await websockets.serve(handle_websocket, args.host, args.port, ssl=ssl_context)
print(f"WebSocket SSH Daemon running on {args.host}:{args.port}")
# Start web interface if specified
if args.web_host and args.web_port:
def run_flask():
app.run(host=args.web_host, port=args.web_port, debug=False, use_reloader=False)
flask_thread = threading.Thread(target=run_flask, daemon=True)
flask_thread.start()
print(f"Web interface available at http://{args.web_host}:{args.web_port}")
await ws_server.wait_closed()
if __name__ == '__main__':
asyncio.run(main())
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment