1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00

Added encryption/decryption

Former-commit-id: 4cd1a24aec45fbfeff04fab18abde8e2f9f01b16 [formerly f10b9db62ba2289af4b48b2086258b7995f16caf] [formerly d7020bfd45870f48485982fc05e671df8ffc9307 [formerly e97bfb05a9]]
Former-commit-id: f6cdb6634f8329f8d87634a86d2ff8af1f5d4c3c [formerly 6ddc94157b82f131bcfd890ab27e8021931b65cd]
Former-commit-id: 2287c335a383ed5c85b97b76459fd49e62a65f8c
This commit is contained in:
Zack Scholl 2016-03-14 09:42:19 -04:00
parent 8645d3a3ac
commit b99cb7ce70
6 changed files with 307 additions and 54 deletions

9
db.go
View File

@ -39,6 +39,7 @@ type WikiData struct {
CurrentText string CurrentText string
Diffs []string Diffs []string
Timestamps []string Timestamps []string
Encrypted bool
} }
func hasPassword(title string) (bool, error) { func hasPassword(title string) (bool, error) {
@ -77,14 +78,15 @@ func hasPassword(title string) (bool, error) {
return hasPassword, nil return hasPassword, nil
} }
func getCurrentText(title string, version int) (string, []versionsInfo, bool, time.Duration) { func getCurrentText(title string, version int) (string, []versionsInfo, bool, time.Duration, bool) {
title = strings.ToLower(title) title = strings.ToLower(title)
var vi []versionsInfo var vi []versionsInfo
totalTime := time.Now().Sub(time.Now()) totalTime := time.Now().Sub(time.Now())
isCurrent := true isCurrent := true
currentText := "" currentText := ""
encrypted := false
if !open { if !open {
return currentText, vi, isCurrent, totalTime return currentText, vi, isCurrent, totalTime, encrypted
} }
err := db.View(func(tx *bolt.Tx) error { err := db.View(func(tx *bolt.Tx) error {
var err error var err error
@ -103,6 +105,7 @@ func getCurrentText(title string, version int) (string, []versionsInfo, bool, ti
return err return err
} }
currentText = p.CurrentText currentText = p.CurrentText
encrypted = p.Encrypted
if version > -1 && version < len(p.Diffs) { if version > -1 && version < len(p.Diffs) {
// get that version of text instead // get that version of text instead
currentText = rebuildTextsToDiffN(p, version) currentText = rebuildTextsToDiffN(p, version)
@ -115,7 +118,7 @@ func getCurrentText(title string, version int) (string, []versionsInfo, bool, ti
if err != nil { if err != nil {
fmt.Printf("Could not get WikiData: %s", err) fmt.Printf("Could not get WikiData: %s", err)
} }
return currentText, vi, isCurrent, totalTime return currentText, vi, isCurrent, totalTime, encrypted
} }
func (p *WikiData) load(title string) error { func (p *WikiData) load(title string) error {

73
encryption.go Executable file
View File

@ -0,0 +1,73 @@
package main
import (
"bytes"
"errors"
"io/ioutil"
"log"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
)
var encryptionType string
func init() {
encryptionType = "PGP SIGNATURE"
}
func encryptString(encryptionText string, encryptionPassphraseString string) string {
encryptionPassphrase := []byte(encryptionPassphraseString)
encbuf := bytes.NewBuffer(nil)
w, err := armor.Encode(encbuf, encryptionType, nil)
if err != nil {
log.Fatal(err)
}
plaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)
if err != nil {
log.Fatal(err)
}
message := []byte(encryptionText)
_, err = plaintext.Write(message)
plaintext.Close()
w.Close()
return encbuf.String()
}
func decryptString(decryptionString string, encryptionPassphraseString string) (string, error) {
encryptionPassphrase := []byte(encryptionPassphraseString)
decbuf := bytes.NewBuffer([]byte(decryptionString))
result, err := armor.Decode(decbuf)
if err != nil {
return "", err
}
alreadyPrompted := false
md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if alreadyPrompted {
return nil, errors.New("Could not decrypt using passphrase")
} else {
alreadyPrompted = true
}
return encryptionPassphrase, nil
}, nil)
if err != nil {
return "", err
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(bytes), nil
}
// func main() {
// test := encryptString("This is some string", "golang")
// fmt.Println(test)
// testD := decryptString(test, "golang")
// fmt.Println(testD)
//
// }

View File

@ -90,7 +90,7 @@ Options:`)
// Default page // Default page
aboutFile, _ := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "templates/aboutpage.md")) aboutFile, _ := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "templates/aboutpage.md"))
p := WikiData{"about", "", []string{}, []string{}} p := WikiData{"about", "", []string{}, []string{}, false}
p.save(string(aboutFile)) p.save(string(aboutFile))
// var q WikiData // var q WikiData
@ -103,6 +103,7 @@ Options:`)
r.HEAD("/", func(c *gin.Context) { c.Status(200) }) r.HEAD("/", func(c *gin.Context) { c.Status(200) })
r.GET("/:title", editNote) r.GET("/:title", editNote)
r.GET("/:title/*option", everythingElse) r.GET("/:title/*option", everythingElse)
r.POST("/:title/*option", encryptionRoute)
r.DELETE("/listitem", deleteListItem) r.DELETE("/listitem", deleteListItem)
r.DELETE("/deletepage", deletePage) r.DELETE("/deletepage", deletePage)
if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" { if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {

116
routes.go
View File

@ -18,6 +18,74 @@ import (
"github.com/russross/blackfriday" "github.com/russross/blackfriday"
) )
type EncryptionPost struct {
Text string `form:"text" json:"text" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func encryptionRoute(c *gin.Context) {
title := c.Param("title")
option := c.Param("option")
fmt.Println(option, title)
var jsonLoad EncryptionPost
if option == "/decrypt" {
fmt.Println("Decrypting...")
if c.BindJSON(&jsonLoad) == nil {
var err error
currentText, _, _, _, encrypted := getCurrentText(title, -1)
fmt.Println(currentText, encrypted, jsonLoad.Password)
if encrypted == true {
currentText, err = decryptString(currentText, jsonLoad.Password)
if err != nil {
c.JSON(200, gin.H{
"status": "Inorrect passphrase.",
"title": title,
"option": option,
"success": false,
})
} else {
p := WikiData{strings.ToLower(title), "", []string{}, []string{}, false}
p.save(currentText)
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": true,
})
}
}
} else {
c.JSON(200, gin.H{
"status": "Could not bind",
"title": title,
"option": option,
"success": false,
})
}
}
if option == "/encrypt" {
if c.BindJSON(&jsonLoad) == nil {
fmt.Println(jsonLoad)
p := WikiData{strings.ToLower(title), "", []string{}, []string{}, true}
p.save(encryptString(jsonLoad.Text, jsonLoad.Password))
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": true,
})
} else {
c.JSON(200, gin.H{
"status": "posted",
"title": title,
"option": option,
"success": false,
})
}
}
}
func newNote(c *gin.Context) { func newNote(c *gin.Context) {
title := randomAlliterateCombo() title := randomAlliterateCombo()
c.Redirect(302, "/"+title) c.Redirect(302, "/"+title)
@ -38,7 +106,10 @@ func editNote(c *gin.Context) {
} else { } else {
version := c.DefaultQuery("version", "-1") version := c.DefaultQuery("version", "-1")
versionNum, _ := strconv.Atoi(version) versionNum, _ := strconv.Atoi(version)
currentText, versions, currentVersion, totalTime := getCurrentText(title, versionNum) currentText, versions, currentVersion, totalTime, encrypted := getCurrentText(title, versionNum)
if encrypted {
c.Redirect(302, "/"+title+"/view")
}
if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") { if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") {
c.Redirect(302, "/"+title+"/view") c.Redirect(302, "/"+title+"/view")
} }
@ -81,16 +152,16 @@ func everythingElse(c *gin.Context) {
if strings.ToLower(title) == "about" { if strings.ToLower(title) == "about" {
versionNum = -1 versionNum = -1
} }
currentText, versions, _, totalTime := getCurrentText(title, versionNum) currentText, versions, _, totalTime, encrypted := getCurrentText(title, versionNum)
if (strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct")) && strings.ToLower(title) != "about" { if (strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct")) && strings.ToLower(title) != "about" {
currentText = strings.Replace(currentText, "self-destruct\n", `> *This page has been deleted, you cannot return after closing.*`+"\n", 1) currentText = strings.Replace(currentText, "self-destruct\n", `> *This page has been deleted, you cannot return after closing.*`+"\n", 1)
currentText = strings.Replace(currentText, "\nself-destruct", "\n"+`> *This page has been deleted, you cannot return after closing.*`, 1) currentText = strings.Replace(currentText, "\nself-destruct", "\n"+`> *This page has been deleted, you cannot return after closing.*`, 1)
p := WikiData{strings.ToLower(title), "", []string{}, []string{}} p := WikiData{strings.ToLower(title), "", []string{}, []string{}, false}
p.save("") p.save("")
} }
renderMarkdown(c, currentText, title, versions, "", totalTime) renderMarkdown(c, currentText, title, versions, "", totalTime, encrypted)
} else if title == "ls" && option == "/"+RuntimeArgs.AdminKey && len(RuntimeArgs.AdminKey) > 1 { } else if title == "ls" && option == "/"+RuntimeArgs.AdminKey && len(RuntimeArgs.AdminKey) > 1 {
renderMarkdown(c, listEverything(), "ls", nil, RuntimeArgs.AdminKey, time.Now().Sub(time.Now())) renderMarkdown(c, listEverything(), "ls", nil, RuntimeArgs.AdminKey, time.Now().Sub(time.Now()), false)
} else if option == "/list" { } else if option == "/list" {
renderList(c, title) renderList(c, title)
} else if title == "static" { } else if title == "static" {
@ -109,7 +180,7 @@ func serveStaticFile(c *gin.Context, option string) {
} }
} }
func renderMarkdown(c *gin.Context, currentText string, title string, versions []versionsInfo, AdminKey string, totalTime time.Duration) { func renderMarkdown(c *gin.Context, currentText string, title string, versions []versionsInfo, AdminKey string, totalTime time.Duration, encrypted bool) {
r, _ := regexp.Compile("\\[\\[(.*?)\\]\\]") r, _ := regexp.Compile("\\[\\[(.*?)\\]\\]")
for _, s := range r.FindAllString(currentText, -1) { for _, s := range r.FindAllString(currentText, -1) {
currentText = strings.Replace(currentText, s, "["+s[2:len(s)-2]+"](/"+s[2:len(s)-2]+"/view)", 1) currentText = strings.Replace(currentText, s, "["+s[2:len(s)-2]+"](/"+s[2:len(s)-2]+"/view)", 1)
@ -139,24 +210,16 @@ func renderMarkdown(c *gin.Context, currentText string, title string, versions [
html2 = strings.Replace(html2, "&amp;#93;", "&#93;", -1) html2 = strings.Replace(html2, "&amp;#93;", "&#93;", -1)
html2 = strings.Replace(html2, "&amp35;", "&#35;", -1) html2 = strings.Replace(html2, "&amp35;", "&#35;", -1)
if AdminKey == "" { c.HTML(http.StatusOK, "view.tmpl", gin.H{
c.HTML(http.StatusOK, "view.tmpl", gin.H{ "Title": title,
"Title": title, "WikiName": RuntimeArgs.WikiName,
"WikiName": RuntimeArgs.WikiName, "Body": template.HTML([]byte(html2)),
"Body": template.HTML([]byte(html2)), "Versions": versions,
"TotalTime": totalTime.String(), "TotalTime": totalTime.String(),
"Versions": versions, "AdminKey": AdminKey,
}) "Encrypted": encrypted,
} else { })
c.HTML(http.StatusOK, "view.tmpl", gin.H{
"Title": title,
"WikiName": RuntimeArgs.WikiName,
"Body": template.HTML([]byte(html2)),
"Versions": versions,
"TotalTime": totalTime.String(),
"AdminKey": AdminKey,
})
}
} }
func reorderList(text string) ([]template.HTML, []string) { func reorderList(text string) ([]template.HTML, []string) {
@ -214,6 +277,9 @@ func renderList(c *gin.Context, title string) {
if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") { if strings.Contains(currentText, "self-destruct\n") || strings.Contains(currentText, "\nself-destruct") {
c.Redirect(302, "/"+title+"/view") c.Redirect(302, "/"+title+"/view")
} }
if p.Encrypted {
c.Redirect(302, "/"+title+"/view")
}
pClean := bluemonday.UGCPolicy() pClean := bluemonday.UGCPolicy()
pClean.AllowElements("img") pClean.AllowElements("img")
@ -277,7 +343,7 @@ func deletePage(c *gin.Context) {
fmt.Println(deleteName) fmt.Println(deleteName)
// if adminKey == RuntimeArgs.AdminKey || true == true { // if adminKey == RuntimeArgs.AdminKey || true == true {
if strings.ToLower(deleteName) != "about" { if strings.ToLower(deleteName) != "about" {
p := WikiData{strings.ToLower(deleteName), "", []string{}, []string{}} p := WikiData{strings.ToLower(deleteName), "", []string{}, []string{}, false}
p.save("") p.save("")
} }
// // remove from program data // // remove from program data

View File

@ -9,7 +9,8 @@
<script src="/static/js/jquery.autogrowtextarea.min.js"></script> <script src="/static/js/jquery.autogrowtextarea.min.js"></script>
{{if .NoEdit}} {{else}} <script src="/static/js/websockets.js"></script> {{end}} {{if .NoEdit}} {{else}}
<script src="/static/js/websockets.js"></script> {{end}}
<script> <script>
external_ip = '{{ .ExternalIP }}' external_ip = '{{ .ExternalIP }}'
@ -41,13 +42,11 @@
margin: 0 auto; margin: 0 auto;
} }
@media (min-width: 1200px) { @media (min-width: 1200px) {
.container{ .container {
max-width: 800px; max-width: 800px;
}
} }
}
</style> </style>
<script src="/static/js/sweetalert-dev.js"></script> <script src="/static/js/sweetalert-dev.js"></script>
<link rel="stylesheet" href="/static/css/sweetalert.css"> <link rel="stylesheet" href="/static/css/sweetalert.css">
@ -74,7 +73,7 @@
<div id="navbar" class="collapse navbar-collapse"> <div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">
<li class="dropdown active"> <li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" class="active"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit <span class="caret"></span></a> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" class="active"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit <span class="caret"></span></a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li class="dropdown-header">Time edited: {{ .TotalTime }}</li> <li class="dropdown-header">Time edited: {{ .TotalTime }}</li>
<li role="separator" class="divider"></li> <li role="separator" class="divider"></li>
@ -85,8 +84,9 @@
{{ end }} {{ end }}
<li><a href="/{{ .Title }}">Current</a></li> <li><a href="/{{ .Title }}">Current</a></li>
<li role="separator" class="divider"></li> <li role="separator" class="divider"></li>
<li class="dropdown-header">Options</li> <li class="dropdown-header">Options</li>
<li><a href="#" id="{{ .Title }}" class="deleteable">Erase</a></li> <li><a href="#" class="postencrypt">Encrypt</a></li>
<li><a href="#" id="{{ .Title }}" class="deleteable">Erase</a></li>
</ul> </ul>
</li> </li>
<li><a href="/{{ .Title }}/view"><span class="glyphicon glyphicon-sunglasses" aria-hidden="true"></span> View</a></li> <li><a href="/{{ .Title }}/view"><span class="glyphicon glyphicon-sunglasses" aria-hidden="true"></span> View</a></li>
@ -111,33 +111,94 @@
$("#emit_data").autoGrow(); $("#emit_data").autoGrow();
}); });
$(document).keydown(function(e){ $(document).keydown(function(e) {
if( e.which === 90 && e.ctrlKey && e.shiftKey ){ if (e.which === 90 && e.ctrlKey && e.shiftKey) {
console.log('control + shift + z'); console.log('control + shift + z');
window.location = "/{{ .Title }}/view"; window.location = "/{{ .Title }}/view";
} }
}); });
$(document).keydown(function(e){ $(document).keydown(function(e) {
if( e.which === 76 && e.ctrlKey && e.shiftKey ){ if (e.which === 76 && e.ctrlKey && e.shiftKey) {
console.log('control + shift + l'); console.log('control + shift + l');
window.location = "/{{ .Title }}/list"; window.location = "/{{ .Title }}/list";
} }
}); });
$('.postencrypt').click(function(event) {
var pass1 = "";
var pass2 = "";
event.preventDefault();
swal({
title: "Encryption",
text: "Enter your passphrase:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass1 = inputValue;
swal({
title: "Encryption",
text: "Enter your passphrase again:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass2 = inputValue
if (pass1 == pass2) {
swal("Encryption", "Passwords match!", "success");
$.ajax({
type: "POST",
//the url where you want to sent the userName and password to
url: '/{{ .Title }}/encrypt',
dataType: 'json',
data: JSON.stringify({
text: $('#emit_data').val(),
password: pass1
}),
success: function (data) {
if (data['success'] == true) {
swal("Encryption", "Encrypted!", "success");
window.location.href = '/{{ .Title }}/view';
} else {
swal("Encryption", "Something went wrong.", "error");
}
}
});
} else {
swal("Encryption", "Passwords do not match.", "error");
}
});
});
});
$('.deleteable').click(function(event) { $('.deleteable').click(function(event) {
event.preventDefault(); event.preventDefault();
var deleteName = $(this).attr('id') var deleteName = $(this).attr('id')
var href = $(this).attr('href') var href = $(this).attr('href')
swal({ swal({
title: "Are you sure?", title: "Are you sure?",
text: "You will not be able to recover /{{ .Title }}!", text: "You will not be able to recover /{{ .Title }}!",
type: "warning", type: "warning",
showCancelButton: true, showCancelButton: true,
confirmButtonColor: "#DD6B55", confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!", confirmButtonText: "Yes, delete it!",
closeOnConfirm: false closeOnConfirm: false
}, function() { }, function() {
$.ajax({ $.ajax({
url: "/deletepage" + '?' + $.param({ url: "/deletepage" + '?' + $.param({
@ -147,7 +208,9 @@
type: 'DELETE', type: 'DELETE',
success: function() { success: function() {
swal("Deleted!", "/{{ .Title }} has been deleted.", "success"); swal("Deleted!", "/{{ .Title }} has been deleted.", "success");
setTimeout(function(){ window.location.reload(true); }, 1000); setTimeout(function() {
window.location.reload(true);
}, 1000);
} }
}); });

View File

@ -15,6 +15,8 @@ a.deleteable {
cursor: pointer; cursor: pointer;
} }
</style> </style>
<script src="/static/js/sweetalert-dev.js"></script>
<link rel="stylesheet" href="/static/css/sweetalert.css">
</head> </head>
<body> <body>
@ -44,6 +46,10 @@ a.deleteable {
<li><a href="/{{ $.Title }}/view?version={{ .VersionNum }}">{{ .VersionDate }}</a></li> <li><a href="/{{ $.Title }}/view?version={{ .VersionNum }}">{{ .VersionDate }}</a></li>
{{ end }} {{ end }}
<li><a href="/{{ .Title }}/view">Current</a></li> <li><a href="/{{ .Title }}/view">Current</a></li>
{{ if .Encrypted }}
<li class="dropdown-header">Options</li>
<li><a href="#" class="postdecrypt">Decrypt</a></li>
{{ end }}
</ul> </ul>
</li> </li>
<li><a href="/{{ .Title }}/list"><span class="glyphicon glyphicon-align-left" aria-hidden="true"></span> List</a></li> <li><a href="/{{ .Title }}/list"><span class="glyphicon glyphicon-align-left" aria-hidden="true"></span> List</a></li>
@ -71,6 +77,46 @@ $( document ).ready(function() {
katex.render(el.getAttribute("data-expr"), el, { displayMode: true }); katex.render(el.getAttribute("data-expr"), el, { displayMode: true });
}); });
$('.postdecrypt').click(function(event) {
var pass1 = "";
event.preventDefault();
swal({
title: "Encryption",
text: "Enter your passphrase:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
pass1 = inputValue;
$.ajax({
type: "POST",
//the url where you want to sent the userName and password to
url: '/{{ .Title }}/decrypt',
dataType: 'json',
data: JSON.stringify({
text: " ",
password: pass1
}),
success: function (data) {
if (data['success'] == true) {
swal("Decryption", "Decrypted!", "success");
window.location.href = '/{{ .Title }}/view';
} else {
swal("Decryption", data['status'], "error");
}
}
});
});
});
}); });
$(document).keydown(function(e){ $(document).keydown(function(e){
@ -88,6 +134,7 @@ $(document).keydown(function(e){
} }
}); });
{{ if .AdminKey }} {{ if .AdminKey }}
$('.deleteable').click(function(event) { $('.deleteable').click(function(event) {
event.preventDefault(); event.preventDefault();