| 1 | package tor |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto" |
| 6 | "crypto/rsa" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "strconv" |
| 10 | |
| 11 | "github.com/cretz/bine/control" |
| 12 | "github.com/cretz/bine/torutil/ed25519" |
| 13 | othered25519 "golang.org/x/crypto/ed25519" |
| 14 | ) |
| 15 | |
| 16 | // OnionService implements net.Listener and net.Addr for an onion service. |
| 17 | type OnionService struct { |
| 18 | // ID is the service ID for this onion service. |
| 19 | ID string |
| 20 | |
| 21 | // Key is the private key for this service. It is either the set key, the |
| 22 | // generated key, or nil if asked to discard the key. If present, it is |
| 23 | // *crypto/rsa.PrivateKey (1024 bit) when Version3 is false or |
| 24 | // github.com/cretz/bine/torutil/ed25519.KeyPair when Version3 is true. |
| 25 | Key crypto.PrivateKey |
| 26 | |
| 27 | // Version3 says whether or not this service is a V3 service. |
| 28 | Version3 bool |
| 29 | |
| 30 | // ClientAuths is the credential set for clients. The keys are username and |
| 31 | // the values are credentials. The credentials will always be present even |
| 32 | // if Tor had to generate them. |
| 33 | ClientAuths map[string]string |
| 34 | |
| 35 | // LocalListener is the local TCP listener. This is always present. |
| 36 | LocalListener net.Listener |
| 37 | |
| 38 | // RemotePorts is the set of remote ports that are forwarded to the local |
| 39 | // listener. This will always have at least one value. |
| 40 | RemotePorts []int |
| 41 | |
| 42 | // CloseLocalListenerOnClose is true if the local listener should be closed |
| 43 | // on Close. This is set to true if a listener was created by Listen and set |
| 44 | // to false of an existing LocalListener was provided to Listen. |
| 45 | CloseLocalListenerOnClose bool |
| 46 | |
| 47 | // The Tor object that created this. Needed for Close. |
| 48 | Tor *Tor |
| 49 | } |
| 50 | |
| 51 | // ListenConf is the configuration for Listen calls. |
| 52 | type ListenConf struct { |
| 53 | // LocalPort is the local port to create a TCP listener on. If the port is |
| 54 | // 0, it is automatically chosen. This is ignored if LocalListener is set. |
| 55 | LocalPort int |
| 56 | |
| 57 | // LocalListener is the specific local listener to back the onion service. |
| 58 | // If this is nil (the default), then a listener is created with LocalPort. |
| 59 | LocalListener net.Listener |
| 60 | |
| 61 | // RemotePorts are the remote ports to serve the onion service on. If empty, |
| 62 | // it is the same as the local port or local listener. This must have at |
| 63 | // least one value if the local listener is not a *net.TCPListener. |
| 64 | RemotePorts []int |
| 65 | |
| 66 | // Key is the private key to use. If not present, a key is generated based |
| 67 | // on whether Version3 is true or false. If present, it must be a |
| 68 | // *crypto/rsa.PrivateKey (1024 bit), a |
| 69 | // github.com/cretz/bine/torutil/ed25519.KeyPair, a |
| 70 | // golang.org/x/crypto/ed25519.PrivateKey, or a |
| 71 | // github.com/cretz/bine/control.Key. |
| 72 | Key crypto.PrivateKey |
| 73 | |
| 74 | // Version3 determines whether, when Key is nil, a version 2 or version 3 |
| 75 | // service/key will be generated. If true it is version 3 (an ed25519 key |
| 76 | // and v3 onion service) and if false it is version 2 (a RSA-1024 key and v2 |
| 77 | // onion service). If Key is not nil, this value is ignored. |
| 78 | Version3 bool |
| 79 | |
| 80 | // ClientAuths is the set of usernames and credentials for client |
| 81 | // authentication. The keys are usernames and the values are credentials. If |
| 82 | // a username is present but the credential is empty, a credential is |
| 83 | // generated by Tor for that user. If this is empty there is no |
| 84 | // authentication. |
| 85 | ClientAuths map[string]string |
| 86 | |
| 87 | // MaxStreams is the maximum number of streams the service will accept. 0 |
| 88 | // means unlimited. |
| 89 | MaxStreams int |
| 90 | |
| 91 | // DiscardKey, if true and Key is nil (meaning a private key is generated), |
| 92 | // tells Tor not to return the generated private key. This value is ignored |
| 93 | // if Key is not nil. |
| 94 | DiscardKey bool |
| 95 | |
| 96 | // Detach, if true, prevents the default behavior of the onion service being |
| 97 | // deleted when this controller connection is closed. |
| 98 | Detach bool |
| 99 | |
| 100 | // NonAnonymous must be true if Tor options HiddenServiceSingleHopMode and |
| 101 | // HiddenServiceNonAnonymousMode are set. Otherwise, it must be false. |
| 102 | NonAnonymous bool |
| 103 | |
| 104 | // MaxStreamsCloseCircuit determines whether to close the circuit when the |
| 105 | // maximum number of streams is exceeded. If true, the circuit is closed. If |
| 106 | // false, the stream is simply not connected but the circuit stays open. |
| 107 | MaxStreamsCloseCircuit bool |
| 108 | |
| 109 | // NoWait if true will not wait until the onion service is published. If |
| 110 | // false, the network will be enabled if it's not and then we will wait |
| 111 | // until the onion service is published. |
| 112 | NoWait bool |
| 113 | } |
| 114 | |
| 115 | // Listen creates an onion service and local listener. The context can be nil. |
| 116 | // If conf is nil, the default struct value is used. Note, if this errors, any |
| 117 | // listeners created here are closed but if a LocalListener is provided it may remain open. |
| 118 | func (t *Tor) Listen(ctx context.Context, conf *ListenConf) (*OnionService, error) { |
| 119 | if ctx == nil { |
| 120 | ctx = context.Background() |
| 121 | } |
| 122 | // Create the service up here and make sure we close it no matter the error within |
| 123 | svc := &OnionService{Tor: t, CloseLocalListenerOnClose: conf.LocalListener == nil} |
| 124 | var err error |
| 125 | |
| 126 | // Create the local listener if necessary |
| 127 | svc.LocalListener = conf.LocalListener |
| 128 | if svc.LocalListener == nil { |
| 129 | if svc.LocalListener, err = net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(conf.LocalPort)); err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // Henceforth, any error requires we close the svc |
| 135 | |
| 136 | // Build the onion request |
| 137 | req := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths} |
| 138 | // Set flags |
| 139 | if conf.DiscardKey { |
| 140 | req.Flags = append(req.Flags, "DiscardPK") |
| 141 | } |
| 142 | if conf.Detach { |
| 143 | req.Flags = append(req.Flags, "Detach") |
| 144 | } |
| 145 | if len(conf.ClientAuths) > 0 { |
| 146 | req.Flags = append(req.Flags, "BasicAuth") |
| 147 | } |
| 148 | if conf.NonAnonymous { |
| 149 | req.Flags = append(req.Flags, "NonAnonymous") |
| 150 | } |
| 151 | if conf.MaxStreamsCloseCircuit { |
| 152 | req.Flags = append(req.Flags, "MaxStreamsCloseCircuit") |
| 153 | } |
| 154 | // Set the key |
| 155 | switch key := conf.Key.(type) { |
| 156 | case nil: |
| 157 | svc.Version3 = conf.Version3 |
| 158 | if conf.Version3 { |
| 159 | req.Key = control.GenKey(control.KeyAlgoED25519V3) |
| 160 | } else { |
| 161 | req.Key = control.GenKey(control.KeyAlgoRSA1024) |
| 162 | } |
| 163 | case control.GenKey: |
| 164 | svc.Version3 = conf.Version3 |
| 165 | req.Key = key |
| 166 | case *rsa.PrivateKey: |
| 167 | svc.Key = key |
| 168 | svc.Version3 = false |
| 169 | if key.N == nil || key.N.BitLen() != 1024 { |
| 170 | err = fmt.Errorf("RSA key must be 1024 bits") |
| 171 | } else { |
| 172 | req.Key = &control.RSAKey{PrivateKey: key} |
| 173 | } |
| 174 | case *control.RSAKey: |
| 175 | svc.Key = key.PrivateKey |
| 176 | svc.Version3 = false |
| 177 | if key.N == nil || key.N.BitLen() != 1024 { |
| 178 | err = fmt.Errorf("RSA key must be 1024 bits") |
| 179 | } else { |
| 180 | req.Key = key |
| 181 | } |
| 182 | case ed25519.KeyPair: |
| 183 | svc.Key = key |
| 184 | svc.Version3 = true |
| 185 | req.Key = &control.ED25519Key{key} |
| 186 | case othered25519.PrivateKey: |
| 187 | properKey := ed25519.FromCryptoPrivateKey(key) |
| 188 | svc.Key = properKey |
| 189 | svc.Version3 = true |
| 190 | req.Key = &control.ED25519Key{properKey} |
| 191 | case *control.ED25519Key: |
| 192 | svc.Key = key.KeyPair |
| 193 | svc.Version3 = true |
| 194 | req.Key = key |
| 195 | default: |
| 196 | err = fmt.Errorf("Unrecognized key type: %T", key) |
| 197 | } |
| 198 | |
| 199 | // Apply the remote ports |
| 200 | if err == nil { |
| 201 | if len(conf.RemotePorts) == 0 { |
| 202 | tcpAddr, ok := svc.LocalListener.Addr().(*net.TCPAddr) |
| 203 | if !ok { |
| 204 | err = fmt.Errorf("Unable to derive local TCP port") |
| 205 | } else { |
| 206 | svc.RemotePorts = []int{tcpAddr.Port} |
| 207 | } |
| 208 | } else { |
| 209 | svc.RemotePorts = make([]int, len(conf.RemotePorts)) |
| 210 | copy(svc.RemotePorts, conf.RemotePorts) |
| 211 | } |
| 212 | } |
| 213 | // Apply the local ports with the remote ports |
| 214 | if err == nil { |
| 215 | localAddr := svc.LocalListener.Addr().String() |
| 216 | if _, ok := svc.LocalListener.(*net.UnixListener); ok { |
| 217 | localAddr = "unix:" + localAddr |
| 218 | } |
| 219 | for _, remotePort := range svc.RemotePorts { |
| 220 | req.Ports = append(req.Ports, &control.KeyVal{Key: strconv.Itoa(remotePort), Val: localAddr}) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // Create the onion service |
| 225 | var resp *control.AddOnionResponse |
| 226 | if err == nil { |
| 227 | resp, err = t.Control.AddOnion(req) |
| 228 | } |
| 229 | |
| 230 | // Apply the response to the service |
| 231 | if err == nil { |
| 232 | svc.ID = resp.ServiceID |
| 233 | switch key := resp.Key.(type) { |
| 234 | case nil: |
| 235 | // Do nothing |
| 236 | case *control.RSAKey: |
| 237 | svc.Key = key.PrivateKey |
| 238 | case *control.ED25519Key: |
| 239 | svc.Key = key.KeyPair |
| 240 | default: |
| 241 | err = fmt.Errorf("Unrecognized result key type: %T", key) |
| 242 | } |
| 243 | // Client auths are the conf and then overridden by results |
| 244 | if len(conf.ClientAuths) > 0 { |
| 245 | svc.ClientAuths = make(map[string]string, len(conf.ClientAuths)) |
| 246 | for k, v := range conf.ClientAuths { |
| 247 | svc.ClientAuths[k] = v |
| 248 | } |
| 249 | for k, v := range resp.ClientAuths { |
| 250 | svc.ClientAuths[k] = v |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // Wait if necessary |
| 256 | if err == nil && !conf.NoWait { |
| 257 | t.Debugf("Enabling network before waiting for publication") |
| 258 | // First make sure network is enabled |
| 259 | if err = t.EnableNetwork(ctx, true); err == nil { |
| 260 | t.Debugf("Waiting for publication") |
| 261 | // Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see |
| 262 | // UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they |
| 263 | // all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing |
| 264 | // the service IDs for UPLOADED so we don't keep a map. |
| 265 | uploadsAttempted := 0 |
| 266 | failures := []string{} |
| 267 | _, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc}, |
| 268 | func(evt control.Event) (bool, error) { |
| 269 | hs, _ := evt.(*control.HSDescEvent) |
| 270 | if hs != nil && hs.Address == svc.ID { |
| 271 | switch hs.Action { |
| 272 | case "UPLOAD": |
| 273 | uploadsAttempted++ |
| 274 | case "FAILED": |
| 275 | failures = append(failures, |
| 276 | fmt.Sprintf("Failed uploading to dir %v - reason: %v", hs.HSDir, hs.Reason)) |
| 277 | if len(failures) == uploadsAttempted { |
| 278 | return false, fmt.Errorf("Failed all uploads, reasons: %v", failures) |
| 279 | } |
| 280 | case "UPLOADED": |
| 281 | return true, nil |
| 282 | } |
| 283 | } |
| 284 | return false, nil |
| 285 | }) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | // Give back err and close if there is an err |
| 290 | if err != nil { |
| 291 | if closeErr := svc.Close(); closeErr != nil { |
| 292 | err = fmt.Errorf("Error on listen: %v (also got error trying to close: %v)", err, closeErr) |
| 293 | } |
| 294 | return nil, err |
| 295 | } |
| 296 | return svc, nil |
| 297 | } |
| 298 | |
| 299 | // Accept implements net.Listener.Accept. |
| 300 | func (o *OnionService) Accept() (net.Conn, error) { |
| 301 | return o.LocalListener.Accept() |
| 302 | } |
| 303 | |
| 304 | // Addr implements net.Listener.Addr just returning this object. |
| 305 | func (o *OnionService) Addr() net.Addr { |
| 306 | return o |
| 307 | } |
| 308 | |
| 309 | // Network implements net.Addr.Network always returning "tcp". |
| 310 | func (o *OnionService) Network() string { |
| 311 | return "tcp" |
| 312 | } |
| 313 | |
| 314 | // String implements net.Addr.String and returns "<serviceID>.onion:<virtport>". |
| 315 | func (o *OnionService) String() string { |
| 316 | return fmt.Sprintf("%v.onion:%v", o.ID, o.RemotePorts[0]) |
| 317 | } |
| 318 | |
| 319 | // Close implements net.Listener.Close and deletes the onion service and closes |
| 320 | // the LocalListener if CloseLocalListenerOnClose is true. |
| 321 | func (o *OnionService) Close() (err error) { |
| 322 | o.Tor.Debugf("Closing onion %v", o) |
| 323 | // Delete the onion first |
| 324 | if o.ID != "" { |
| 325 | err = o.Tor.Control.DelOnion(o.ID) |
| 326 | o.ID = "" |
| 327 | } |
| 328 | // Now if the local one needs to be closed, do it |
| 329 | if o.CloseLocalListenerOnClose && o.LocalListener != nil { |
| 330 | if closeErr := o.LocalListener.Close(); closeErr != nil { |
| 331 | if err != nil { |
| 332 | err = fmt.Errorf("Unable to close onion: %v (also unable to close local listener: %v)", err, closeErr) |
| 333 | } else { |
| 334 | err = closeErr |
| 335 | } |
| 336 | } |
| 337 | o.LocalListener = nil |
| 338 | } |
| 339 | if err != nil { |
| 340 | o.Tor.Debugf("Failed closing onion: %v", err) |
| 341 | } |
| 342 | return |
| 343 | } |