Unable to open tcp connection. No connection could be made because the target machine actively refused it. exit status 1 - sql

I tried to fetch data from a SQL Server database. When I run, it keeps giving me this error:
unable to open tcp connection with host 'localhost:1433': dial tcp [::1]:1433: connectex: No connection could be made because the target machine actively refused it.
exit status 1
My code:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/denisenkom/go-mssqldb"
)
var kiosk string
var server = ".\\MSSQLSERVER01"
var port = 1433
var user = "DESKTOP-37624KK"
var password = "**********"
var database = "Kiosk"
func main() {
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s", server, user, password, port, database)
db, err := sql.Open("mssql", connString)
if err != nil {
fmt.Println("Error in connect DB")
log.Fatal(err)
}
rows, err := db.Query("SELECT * FROM Kiosk")
if err != nil {
log.Fatal(err)
}
for rows.Next() {
if err := rows.Scan(&kiosk); err != nil {
log.Fatal(err)
}
fmt.Println(kiosk)
}
defer rows.Close()
}
Checked if firewall is blocking needed port
Tried to change and connect to new ports
Tried to search on the internet for other solutions. Nothing has helped yet

The server variable value is wrong. The dot (.) means "localhost". If the SQL server is installed locally just use "." (or ".\InstanceName" - if there are multiple instances installed). If the server is installed in the network just use SERVERNAME (without the leading backslashes), or SERVERNAME\InstanceName.

Related

Telegram Bot Webhook - Connection Refused (Golang)

I have configured a Telegram bot to use Webhooks according to the following configuration:
OS: Ubuntu
Server: Apache2
Virtual Host:
Sucessfully linked to domain
Listening on port 8843
Ports 443, 8843 all open with ufw allow
Webhook:
Set to "domain.app:8843/" bot.Token
HandleFunc set to "/" + bot.Token
certFile and keyFile are used succesfully with ListenAndServeTLS
Still, however, my bot just won't work, spend literally the entire last 18 hours trying to fix it. It is 3 at night now, and I just am at my wits end.
When I start my binary it prints the following to stdout:
2023/01/07 01:50:15 Authorized on account ExampleAccount
2023/01/07 01:50:15 setWebhook resp:
{"ok":true,"result":true,"description":"Webhook is already set"}
2023/01/07 01:50:15 getWebhookInfo resp:
{"ok":true,"result":{"url":"https://domain.app:8443/MY_BOT_TOKEN","has_custom_certificate":false,"pending_update_count":0,"last_error_date":1673052633,"last_error_message":"Connection
refused","max_connections":40,"ip_address":"x.x.x.x"}}
2023/01/07 01:50:15 Telegram callback failed: Connection refused
If somebody has any idea please help me!
2023/01/07 02:07:57 getWebhookInfo resp:
{"ok":true,"result":{"url":"https://domain.app:8443/MY_BOT_TOKEN","has_custom_certificate":false,"pending_update_count":3,"last_error_date":1673052633,"last_error_message":"Connection
refused","max_connections":40,"ip_address":"167.99.34.89"}}
If I issue start commands to the bot, the pending_update_count actually gets incremented as well, so this is a really strange issue.
My code:
func main() {
// Create a new bot
bot, err := tgbotapi.NewBotAPI("PLACEHOLDER")
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
// Set the webhook
_, err = bot.SetWebhook(tgbotapi.NewWebhook("https://domain.app:8443/" + bot.Token))
if err != nil {
log.Panic(err)
}
info, err := bot.GetWebhookInfo()
if err != nil {
log.Fatal(err)
}
if info.LastErrorDate != 0 {
log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
}
// Start the webhook server
http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) {
update := tgbotapi.Update{}
err := json.NewDecoder(r.Body).Decode(&update)
if err != nil {
log.Println(err)
return
}
// Check if the update is a callback query (button press)
if update.CallbackQuery != nil {
callbackQuery := update.CallbackQuery
data := callbackQuery.Data
// Create a new message
msg := tgbotapi.NewMessage(callbackQuery.Message.Chat.ID, "")
// Set the text and keyboard based on the button pressed
switch data {
case "get_information":
msg.Text = "Here is some information about which formats are supported:"
msg.ReplyMarkup = tgbotapi.NewRemoveKeyboard(true)
case "start_file_conversion":
msg.Text = "Great! Click the link to download your file: https://example.com/ks283dj"
msg.ReplyMarkup = tgbotapi.NewRemoveKeyboard(true)
}
// Send the message
bot.Send(msg)
}
})
log.Printf("About to listen on 0.0.0.0:8443:8443")
errServe := http.ListenAndServeTLS("0.0.0.0:8443", "fullchain.pem", "privkey.pem", nil)
log.Fatal(errServe)
}
The Webhook setup is wrong here:
Instead of:
_, err = bot.SetWebhook(tgbotapi.NewWebhook("https://domain.app:8443/" + bot.Token))
http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request)
Use:
_, err = bot.SetWebhook(tgbotapi.NewWebhook("https://domain.app:8443/bot" + bot.Token))
http.HandleFunc("/bot"+bot.Token, func(w http.ResponseWriter, r *http.Request)
As described here: https://core.telegram.org/bots/api:
All queries to the Telegram Bot API must be served over HTTPS and need
to be presented in this form:
https://api.telegram.org/bot/METHOD_NAME.

Http get request through socks5 | EOF error

What I'm trying to do:
Build a package (later usage) that provides a method to execute a get-request to any page through a given socks5 proxy.
My problem:
When ever I try to request a page with SSL (https) I get the following error:
Error executing request Get https://www.xxxxxxx.com: socks connect tcp 83.234.8.214:4145->www.xxxxxxx.com:443: EOF
However requesting http://www.google.com is working fine. So there must be a problem with the SSL connection. Can't imagine why this isn't working as I'm not very experienced with SSL-connections. End of file makes no sense to me.
My current code:
func main() {
// public socks5 - worked when I created this question
proxy_addr := "83.234.8.214:4145"
// With this address I get the error
web_addr := "https://www.whatismyip.com"
// Requesting google works fine
//web_addr := "http://www.google.com"
dialer, err := proxy.SOCKS5("tcp", proxy_addr, nil, proxy.Direct)
handleError(err, "error creating dialer")
httpTransport := &http.Transport{}
httpClient := &http.Client{Transport: httpTransport}
httpTransport.DialTLS = dialer.Dial
req, err := http.NewRequest("GET", web_addr, nil)
handleError(err, "error creating request")
httpClient.Timeout = 5 * time.Second
resp, err := httpClient.Do(req)
handleError(err, "error executing request")
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
handleError(err, "error reading body")
fmt.Println(string(b))
}
func handleError(err error, msg string) {
if err != nil {
log.Fatal(err)
}
}
So what am I missing in here to deal with ssl-connections?
Thank you very much.
Edit 1:
In case someone would think this is an issue with whatismyip.com I've done some more tests:
https://www.google.com
EOF error
https://stackoverflow.com
EOF error
https://www.youtube.com/
EOF error
Connection between your program and your socks5 proxy goes not through SSL/TLS
So you should change line
httpTransport.DialTLS = dialer.Dial
to
httpTransport.Dial = dialer.Dial
I checked https://www.whatismyip.com and https://www.google.com.
URLs are downloaded fine.
For test I set up 3proxy service on my server, test your code with fixed line and check 3proxy logs.
All made requests was in proxy server logs.
If you need more help - please let me know, I'll help
Things to notice:
Socks5 proxies need to support SSL connections.
The code from the question won't work with this answer as the proxy (used in the code) isn't supporting SSL connections.

Proxy golang https

i am trying to make one get in https://www.google.com using proxy with authentication, i already passing header parameter
Proxy-Authorization
but proxy server return
Proxy Authentication Required
code:
package main
import (
"crypto/tls"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://www.google.com.br", nil)
req.Header.Set("Host", "www.google.com.br")
proxyURL := url.URL{
Host: "IP-HERE:PORT-HEERE"}
transport := &http.Transport{
Proxy: http.ProxyURL(&proxyURL),
TLSClientConfig: &tls.Config{},
}
client := &http.Client{Transport: transport}
req.RequestURI = ""
auth := fmt.Sprintf("USER:PASSWORD")
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Proxy-Authorization", basic)
resp, err := client.Do(req)
if err != nil {
fmt.Printf("erro: %s", err)
}
fmt.Printf("code: %s", resp.StatusCode)
htmlData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(os.Stdout, string(htmlData))
}
I have to pass another parameter?
When i perform one get in http://www.google.com.br, without https.. proxy authentication with success. why?
I found the solution. Golang don't pass header parameters in method CONNECT, then parameter Proxy-Authorization aren't sent to proxy server.
to resolve this, field ProxyConnectHeader was added to struct Transport. but this change until released, this change are only in master.
to test this new field using golang from master, i made on project in github and worked.
link to golang path
link to project in github that test this new field

SSH through multiple hosts in go

Is it possible to SSH to another host while in an SSH session in golang? I tried chaining some stuff together like this, but the printout says the remote addr of client 2 is 0.0.0.0 and an error is given when I try to execute anything on an ssh.Session from client2.
host1 := "host1.com"
host2 := "host2.com"
client1, err := ssh.Dial("tcp", host, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
conn, err := client1.Dial("tcp", host2)
if err != nil {
panic(err)
}
sshConn, newChan, requestChan, err := ssh.NewClientConn(conn, host2, config)
if err != nil {
panic(err)
}
client2 := ssh.NewClient(sshConn, newChan, requestChan)
fmt.Println("Client 2 RemoteAddr():", client2.RemoteAddr())
The problem is that you are running all of this code on the same host. Let's call the host you run your app on host0 for convenience.
You start out making a connection from host0 to host1. That works fine. What you seem to want to do next is make a connection from host1 to host2. To do that you need to run the SSH code on host1. But your app, which is and always has been running on host0, is not in the place to do that.
You will need to put a program on host1 that does the connection to host2 and then send a command down the SSH connection to host1 that will start that program.

SCP Client in Go

I was struggling with and ssh client for golang but was told that the ciphers for the freesshd server was incompatible with the ssh client for Go, so I just installed another one (PowerShell Server) and I can successfully connect to the server.
My problem is not over because I now need to transfer files from local to remote, and this can only be done through scp. I was directed to this scp client for go and have two issues.
I run it and get this:
Where or how can I access the contents of id_rsa needed for privateKey? I just went in my .ssh folder and saw a github_rsa and used that private key, I'm sure that this is not the correct one to use but wouldn't I see some kind of error or invalid private key and not the result above?
The code you were directed to is broken. The example also uses the public key authentication, which is not necessarily your only option. If you can allow password authentication instead, you can make it a bit easier for yourself.
I just made an upload myself by modifying the example you used:
package main
import (
"code.google.com/p/go.crypto/ssh"
"fmt"
)
type password string
func (p password) Password(_ string) (string, error) {
return string(p), nil
}
func main() {
// Dial code is taken from the ssh package example
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.ClientAuth{
ssh.ClientAuthPassword(password("password")),
},
}
client, err := ssh.Dial("tcp", "127.0.0.1:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
go func() {
w, _ := session.StdinPipe()
defer w.Close()
content := "123456789\n"
fmt.Fprintln(w, "C0644", len(content), "testfile")
fmt.Fprint(w, content)
fmt.Fprint(w, "\x00")
}()
if err := session.Run("/usr/bin/scp -qrt ./"); err != nil {
panic("Failed to run: " + err.Error())
}
}